Skip to main content
Glama

CSL-Core

PyPI version PyPI Downloads Python License Z3 Verified TLA+ Verified

❤️ Наши контрибьюторы!

Contributors

CSL-Core (Chimera Specification Language) — это детерминированный уровень безопасности для ИИ-агентов. Пишите правила в файлах .csl, проверяйте их математически с помощью Z3, обеспечивайте их соблюдение во время выполнения — вне модели. LLM никогда не видит эти правила. Она просто не может их нарушить.

pip install csl-core

Изначально создано для Project Chimera, теперь с открытым исходным кодом для любой системы ИИ.


Related MCP server: nobulex-mcp-server

Зачем?

prompt = """You are a helpful assistant. IMPORTANT RULES:
- Never transfer more than $1000 for junior users
- Never send PII to external emails
- Never query the secrets table"""

Это не работает. LLM подвержены промпт-инъекциям, правила носят вероятностный характер (99% ≠ 100%), и нет аудиторского следа, когда что-то идет не так.

CSL-Core меняет подход: правила находятся вне модели в скомпилированных, проверенных Z3 файлах политик. Принудительное исполнение является детерминированным — это не рекомендация.


Быстрый старт (60 секунд)

1. Напишите политику

Создайте my_policy.csl:

CONFIG {
  ENFORCEMENT_MODE: BLOCK
  CHECK_LOGICAL_CONSISTENCY: TRUE
}

DOMAIN MyGuard {
  VARIABLES {
    action: {"READ", "WRITE", "DELETE"}
    user_level: 0..5
  }

  STATE_CONSTRAINT strict_delete {
    WHEN action == "DELETE"
    THEN user_level >= 4
  }
}

2. Проверка и тестирование (CLI)

# Compile + Z3 formal verification
cslcore verify my_policy.csl

# Test a scenario
cslcore simulate my_policy.csl --input '{"action": "DELETE", "user_level": 2}'
# → BLOCKED: Constraint 'strict_delete' violated.

# Interactive REPL
cslcore repl my_policy.csl

3. Использование в Python

from chimera_core import load_guard

guard = load_guard("my_policy.csl")

result = guard.verify({"action": "READ", "user_level": 1})
print(result.allowed)  # True

result = guard.verify({"action": "DELETE", "user_level": 2})
print(result.allowed)  # False

Бенчмарк: Устойчивость к состязательным атакам

Мы протестировали правила безопасности на основе промптов против принудительного исполнения CSL-Core на 4 передовых LLM с использованием 22 состязательных атак и 15 легитимных операций:

Подход

Заблокировано атак

Уровень обхода

Пройдено легитимных операций

Задержка

GPT-4.1 (промпт-правила)

10/22 (45%)

55%

15/15 (100%)

~850мс

GPT-4o (промпт-правила)

15/22 (68%)

32%

15/15 (100%)

~620мс

Claude Sonnet 4 (промпт-правила)

19/22 (86%)

14%

15/15 (100%)

~480мс

Gemini 2.0 Flash (промпт-правила)

11/22 (50%)

50%

15/15 (100%)

~410мс

CSL-Core (детерминированный)

22/22 (100%)

0%

15/15 (100%)

~0.84мс

Почему 100%? Принудительное исполнение происходит вне модели. Промпт-инъекция не имеет значения, потому что нет ничего, против чего можно было бы совершить инъекцию. Категории атак: прямое переопределение инструкций, джейлбрейки через ролевые игры, трюки с кодированием, эскалация в несколько шагов, подмена имен инструментов и многое другое.

Полная методология: benchmarks/


Интеграция с LangChain

Защитите любого агента LangChain с помощью 3 строк — никаких изменений промптов, никакого дообучения:

from chimera_core import load_guard
from chimera_core.plugins.langchain import guard_tools
from langchain_classic.agents import AgentExecutor, create_tool_calling_agent

guard = load_guard("agent_policy.csl")

# Wrap tools — enforcement is automatic
safe_tools = guard_tools(
    tools=[search_tool, transfer_tool, delete_tool],
    guard=guard,
    inject={"user_role": "JUNIOR", "environment": "prod"},  # LLM can't override these
    tool_field="tool"  # Auto-inject tool name
)

agent = create_tool_calling_agent(llm, safe_tools, prompt)
executor = AgentExecutor(agent=agent, tools=safe_tools)

Каждый вызов инструмента перехватывается до выполнения. Если политика запрещает, инструмент не запускается. Точка.

Внедрение контекста

Передавайте контекст выполнения, который LLM не может переопределить — роли пользователей, окружение, лимиты запросов:

safe_tools = guard_tools(
    tools=tools,
    guard=guard,
    inject={
        "user_role": current_user.role,         # From your auth system
        "environment": os.getenv("ENV"),        # prod/dev/staging
        "rate_limit_remaining": quota.remaining # Dynamic limits
    }
)

Защита цепочек LCEL

from chimera_core.plugins.langchain import gate

chain = (
    {"query": RunnablePassthrough()}
    | gate(guard, inject={"user_role": "USER"})  # Policy checkpoint
    | prompt | llm | StrOutputParser()
)

Инструменты CLI

CLI — это полноценная среда разработки для политик: тестируйте, отлаживайте и развертывайте без написания кода на Python.

verify — Компиляция + доказательство Z3

cslcore verify my_policy.csl

# ⚙️  Compiling Domain: MyGuard
#    • Validating Syntax... ✅ OK
#    ├── Verifying Logic Model (Z3 Engine)... ✅ Mathematically Consistent
#    • Generating IR... ✅ OK

simulate — Тестовые сценарии

# Single input
cslcore simulate policy.csl --input '{"action": "DELETE", "user_level": 2}'

# Batch testing from file
cslcore simulate policy.csl --input-file test_cases.json --dashboard

# CI/CD: JSON output
cslcore simulate policy.csl --input-file tests.json --json --quiet

repl — Интерактивная разработка

cslcore repl my_policy.csl --dashboard

cslcore> {"action": "DELETE", "user_level": 2}
🛡️ BLOCKED: Constraint 'strict_delete' violated.

cslcore> {"action": "DELETE", "user_level": 5}
✅ ALLOWED

formal — Модельная проверка TLA⁺

cslcore formal my_policy.csl

Запускает официальный инструмент проверки моделей TLC (java -jar tla2tools.jar) для вашей политики. TLC исчерпывающе исследует каждое достижимое состояние в пространстве абстрактных состояний и доказывает, что каждое временное свойство соблюдается — или возвращает конкретный контрпример с точным состоянием, которое нарушает ваш инвариант.

╔══════════════════════════════════════════════════════════════════════════════╗
║                       TLA⁺ FORMAL VERIFICATION ENGINE                        ║
║          Chimera Specification Language · Temporal Logic of Actions          ║
║                                                                              ║
║    ⚡  REAL TLC  ·  java -jar tla2tools.jar  ·  Exhaustive Model Checking    ║
║       TLC2 Version 2026.03.31.154134 (rev: becec35)  ·  pid 48146  ·  1      ║
║                                  worker(s)                                   ║
╚══════════════════════════════════════════════════════════════════════════════╝

  Variable      Domain                         Cardinality
 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  agent_tier    {"STANDARD", "PREMIUM"}                |2|
  task_type     {"READ", "WRITE", "ANALYZE"}           |3|
  risk_score    0..5                                   |6|

  ├─ □(no_destructive_ops)      ✅  HOLDS  [288 states  349ms]
  ├─ □(no_production_access)    ✅  HOLDS  [288 states  349ms]
  ├─ □(bounded_risk)            ✅  HOLDS  [288 states  349ms]

  └─ Proof hash: 17dd1564897d242fc045a3a884a52bbb… ✅

╔══════════════ TLA⁺ VERIFICATION COMPLETE — ALL PROPERTIES HOLD ══════════════╗
║  ✅  Domain: AIAgentSafetyDemo  ·  ⬡ 144 states  ·  ⏱ 1047ms               ║
╚══════════════════════════════════════════════════════════════════════════════╝

Включите в любой политике, добавив одну строку в CONFIG:

CONFIG {
  ENFORCEMENT_MODE: BLOCK
  ENABLE_FORMAL_VERIFICATION: TRUE   // ← triggers cslcore formal automatically
}

Или запустите отдельно:

cslcore formal policy.csl              # real TLC (Java required, JAR auto-downloaded)
cslcore formal policy.csl --mock       # Python BFS fallback (no Java needed)
cslcore formal policy.csl --timeout 120
cslcore formal policy.csl --export-tla ./specs/   # save .tla + .cfg for TLA+ Toolbox

Нет Java? CSL-Core автоматически переключается на Python-реализацию проверки моделей BFS. Баннер четко указывает, какой движок был запущен. JAR скачивается автоматически при первом использовании (~4 МБ из официального релиза TLA+ на GitHub).

CI/CD конвейер

# GitHub Actions
- name: Verify policies
  run: |
    for policy in policies/*.csl; do
      cslcore verify "$policy" || exit 1
    done

MCP-сервер (Claude Desktop / Cursor / VS Code)

Пишите, проверяйте и обеспечивайте соблюдение политик безопасности прямо из вашего ИИ-ассистента — код не требуется.

pip install "csl-core[mcp]"

Добавьте в конфигурацию Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "csl-core": {
      "command": "uv",
      "args": ["run", "--with", "csl-core[mcp]", "csl-core-mcp"]
    }
  }
}

Инструмент

Что он делает

verify_policy

Формальная верификация Z3 — обнаруживает противоречия на этапе компиляции

simulate_policy

Тестирование политик на входных данных JSON — РАЗРЕШЕНО/ЗАБЛОКИРОВАНО

explain_policy

Понятное человеку резюме любой политики CSL

scaffold_policy

Генерация шаблона CSL на основе описания на обычном английском

Вы: "Напиши мне политику безопасности, которая предотвращает переводы свыше $5000 без одобрения администратора"

Claude: scaffold_policy → вы редактируете → verify_policy обнаруживает противоречие → вы исправляете → simulate_policy подтверждает работу


Архитектура

┌──────────────────────────────────────────────────────────┐
│  1. COMPILER    .csl → AST → IR → Compiled Artifact      │
│     Syntax validation, semantic checks, functor gen       │
├──────────────────────────────────────────────────────────┤
│  2. Z3 VERIFIER    Theorem Prover — Static Analysis       │
│     Contradiction detection, reachability, rule shadowing │
│     ⚠️ If verification fails → policy will NOT compile    │
├──────────────────────────────────────────────────────────┤
│  3. TLA⁺ VERIFIER  Model Checker — Temporal Safety        │
│     Exhaustive state-space exploration via TLC            │
│     Predicate abstraction for large numeric domains       │
│     Counterexample traces + automated fix suggestions     │
│     (opt-in: ENABLE_FORMAL_VERIFICATION: TRUE)            │
├──────────────────────────────────────────────────────────┤
│  4. RUNTIME     Deterministic Policy Enforcement          │
│     Fail-closed, zero dependencies, <1ms latency          │
└──────────────────────────────────────────────────────────┘

Тяжелые вычисления выполняются один раз на этапе компиляции. Время выполнения — это чистая оценка.


Используется в продакшене

Используете CSL-Core? Дайте нам знать, и мы добавим вас сюда.


Примеры политик

Пример

Домен

Ключевые особенности

agent_tool_guard.csl

Безопасность ИИ

RBAC, защита PII, разрешения инструментов

chimera_banking_case_study.csl

Финансы

Скоринг рисков, VIP-уровни, санкции

dao_treasury_guard.csl

Web3

Мультиподпись, временные блокировки, аварийный обход

tla_demo.csl

Формальные методы

Модельная проверка TLA⁺ — все свойства соблюдаются

tla_demo_violation.csl

Формальные методы

Контрпример TLA⁺ + предложения по исправлению

python examples/run_examples.py          # Run all with test suites
python examples/run_examples.py banking  # Run specific example

Справочник API

from chimera_core import load_guard, RuntimeConfig

# Load + compile + verify
guard = load_guard("policy.csl")

# With custom config
guard = load_guard("policy.csl", config=RuntimeConfig(
    raise_on_block=False,          # Return result instead of raising
    collect_all_violations=True,   # Report all violations, not just first
    missing_key_behavior="block"   # "block", "warn", or "ignore"
))

# Verify
result = guard.verify({"action": "DELETE", "user_level": 2})
print(result.allowed)     # False
print(result.violations)  # ['strict_delete']

Полная документация: Начало работы · Спецификация синтаксиса · Справочник CLI · Философия


Дорожная карта

✅ Сделано: Базовый язык и парсер · Верификация Z3 · Среда выполнения с отказом по умолчанию · Интеграция с LangChain · CLI (verify, simulate, repl, formal) · MCP-сервер · Модельная проверка TLA⁺ с реальным TLC · Абстракция предикатов · Анализ контрпримеров · Развертывание в продакшене в Chimera v1.7.0

🚧 В процессе: Версионирование политик · Интеграция с LangGraph

🔮 Планируется: LlamaIndex и AutoGen · Композиция нескольких политик · Горячая перезагрузка · Маркетплейс политик · Облачные шаблоны

🔒 Enterprise (исследования): Причинно-следственный вывод · Мультиарендность


Вклад в проект

Мы приветствуем вклад! Начните с good first issue или ознакомьтесь с CONTRIBUTING.md.

Области с высоким влиянием: Реальные примеры политик · Интеграции с фреймворками · Веб-редактор политик · Покрытие тестами


Лицензия

Apache 2.0 (open-core модель). Весь язык, компилятор, верификатор Z3, среда выполнения, CLI, MCP-сервер и все примеры имеют открытый исходный код. См. LICENSE.


Создано с ❤️ компанией Chimera Protocol · Issues · Discussions · Email

Available Tools

11 tools
explain_policyA

Parse a CSL policy and return a structured Markdown summary.

Shows: domain name, all variables with types/ranges, all constraints with triggers and actions, and configuration settings. Does NOT compile or verify — use verify_policy for that.

Args: csl_content: The complete CSL policy source code as a string.

Inputs: csl_content (required). Returns: result

scaffold_policyA

Generate a CSL policy scaffold from a description.

Returns a ready-to-edit .csl template with CONFIG, DOMAIN, VARIABLES, and placeholder constraints.

Common CSL patterns: WHEN amount > 1000 THEN role MUST BE "ADMIN" WHEN risk_score > 0.8 THEN action MUST NOT BE "TRANSFER" ALWAYS True THEN tool MUST NOT BE "DELETE" WHEN user_age < 18 AND category == "ALCOHOL" THEN allowed MUST BE "NO"

Variable types: amount: 0..100000 (integer range) role: {"ADMIN", "USER"} (enum / string set) score: 0..1 (numeric range)

Args: domain_name: Name for the policy domain (e.g., "PaymentGuard", "AgentSafety"). description: Plain-English description of what the policy should enforce. variables: Optional comma-separated variable hints (e.g., "amount, role, risk_score").

Inputs: description (required), domain_name (required), variables. Returns: result

simulate_policyA

Simulate a CSL policy against one or more JSON inputs.

Compiles the policy, then runs the runtime guard against the provided context. Returns ALLOWED or BLOCKED with full violation details.

Supports batch simulation: pass a JSON array of objects to test multiple inputs.

Args: csl_content: The complete CSL policy source code as a string. context_json: JSON object (single input) or JSON array (batch) to test. dry_run: If true, evaluates all rules but never blocks. Useful for shadow testing.

Inputs: csl_content (required), context_json (required), dry_run. Returns: result

tla_verifyA

Run TLA+ formal verification (real TLC model checking) on a CSL policy.

Performs exhaustive state-space exploration to verify temporal safety properties. Unlike Z3 (which checks static logical consistency), TLA+ checks ALL possible state transitions over time.

Returns:

  • Whether all safety properties hold

  • Number of states explored / distinct states

  • Counterexample traces for any violations

  • TLC identity proof (version, PID, workers)

  • Automated fix suggestions for violations

  • Generated TLA+ spec (for transparency)

Use verify_policy for quick Z3 consistency checks. Use tla_verify when you need exhaustive temporal verification.

Args: csl_content: The complete CSL policy source code as a string. timeout: TLC subprocess timeout in seconds (default: 60). use_mock: If true, use Python BFS fallback instead of real TLC.

Inputs: csl_content (required), timeout, use_mock. Returns: result

universe_infoA

Analyze the state space "universe" of a CSL policy.

Returns structural information about the policy's state space:

  • All variables with their domains, TLA+ set representations, and cardinalities

  • Total state space size (product of all variable cardinalities)

  • All constraints with their conditions and actions

  • Constraint coverage analysis (which variables are constrained vs unconstrained)

  • State space breakdown visualization

Essential for understanding the "universe" an agent lives in, planning Evolving Universe experiments, and estimating TLC verification cost before running tla_verify.

Args: csl_content: The complete CSL policy source code as a string.

Inputs: csl_content (required). Returns: result

venom_agentA

One agent in detail: its tools with parameters and risk classes, triggers, guard status and the agent key to use in policies. No secrets, no prompt text.

Args: agent_id: agent id, name or key (from venom_inventory). workspace: Venom workspace folder.

Inputs: agent_id (required), workspace. Returns: result

venom_inventoryB

Summary of the AI agents Venom discovered on this machine: kind, state, tool count, riskiest tool class, guard status, coverage and top findings. Redacted: no credential values, no prompt text.

Args: workspace: Venom workspace folder (default: CSL_VENOM_WORKSPACE or the server's folder).

Inputs: workspace. Returns: result

venom_policy_contextA

Everything needed to draft or revise a policy for one agent: the active policy (or a deterministic starting draft on first install), its findings, vocabulary drift and the rules a valid draft must follow.

Args: agent_id: agent id, name or key. workspace: Venom workspace folder.

Inputs: agent_id (required), workspace. Returns: result

venom_propose_exemptionB

Propose that an agent (scope "agent") or one tool (scope "tool") be exempted from guarding. Always recorded as proposed; only the operator can approve it in the CLI.

Args: agent: agent id (or "*" with scope "tool"). scope: "agent" or "tool". reason: why it can be trusted. tool: tool name when scope is "tool". workspace: Venom workspace folder.

Inputs: agent (required), scope (required), reason (required), tool, +1 more. Returns: result

venom_save_draftA

Verify a CSL draft (parse, validate, Z3) and, only if it passes, save it to the workspace's .csl/venom/drafts/. Never activates anything: the operator reviews and activates drafts with the cslcore CLI.

Args: agent_id: the agent the draft is for. csl_content: complete CSL policy source. note: one line explaining the draft (kept as a comment). workspace: Venom workspace folder.

Inputs: agent_id (required), csl_content (required), note, workspace. Returns: result

verify_policyA

Verify a CSL policy for logical consistency using Z3 formal verification.

Performs four-stage analysis:

  1. Syntax validation (parser)

  2. Semantic validation (scope, types, function whitelist)

  3. Z3 logic verification (reachability, internal consistency, pairwise conflicts, policy-wide conflicts)

  4. IR compilation

Returns verification result with actionable error details if any issues are found.

Args: csl_content: The complete CSL policy source code as a string.

Inputs: csl_content (required). Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 11 tools

    Disambiguation4/5

    Most tools are clearly distinct, especially the verification tools which have explicit guidance on when to use which (verify_policy vs tla_verify vs simulate_policy). The venom_* tools form a coherent workflow, though venom_inventory and venom_agent share the inspection space—inventory gives all agents, agent gives one—but the distinction is clear from descriptions. No major overlap or misselection risk.

    Naming Consistency3/5

    Mixed naming conventions: venom_* tools use a clear prefix, but the rest are a mix of verb_noun (explain_policy, scaffold_policy), verb_verb (verify_policy, simulate_policy), and noun_verb (tla_verify, universe_info) patterns. While readable, there is no single consistent verb_noun pattern across the set.

    Tool Count5/5

    11 tools are well-scoped for a CSL policy management and verification server. Each tool covers a distinct facet: inventory, agent inspection, policy context, drafting, exemptions, explanation, scaffolding, simulation, TLA+ verification, universe analysis, and Z3 verification. No tool feels redundant or missing.

    Completeness4/5

    The surface covers the full lifecycle of CSL policy work: inspection, drafting, verification, simulation, formal analysis, and exemption handling. One potential gap is direct activation or deployment of policies, but the descriptions explicitly state that activation is done via CLI by the operator, which aligns with the tool's design. No critical dead ends for the stated purpose.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables formal verification of LLM outputs against compliance ontologies using Z3 SMT solver. Validates that AI-generated content adheres to regulatory requirements like HIPAA or mortgage compliance rules.
      MIT
    • A
      license
      A
      quality
      A
      maintenance
      Proof-of-behavior enforcement for AI agents. Declare behavioral constraints, enforce at runtime, produce SHA-256 hash-chained audit trails. Supports covenants (permit/forbid/require), real-time verification, and cross-agent trust handshakes.
      4
      40
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables deterministic verification for AI assistants by executing Python code that uses symbolic engines like SymPy and Z3 for math, logic, and code analysis.
      2
      152 PyPI
      Apache 2.0
    • A
      license
      Not graded
      quality
      C
      maintenance
      A runtime gate for coding agents. Blocks the tool calls that wreck a repo (force-push main, rm -rf, secret exfiltration, CI wipe) and lets normal build and commit work through. Machine-checked git-branch core (z3); the rest is high-precision heuristics. Tested on 3,790 real CI commands, 0 false blocks.
      1
      MIT