Skip to main content
Glama

CSL-Core

PyPI version PyPI Downloads Python License Z3 Verified TLA+ Verified

❤️ 기여자분들!

Contributors

CSL-Core(Chimera Specification Language)는 AI 에이전트를 위한 결정론적 안전 계층입니다. .csl 파일로 규칙을 작성하고, Z3를 통해 수학적으로 검증하며, 런타임 시 모델 외부에서 이를 강제합니다. LLM은 규칙을 전혀 볼 수 없으며, 규칙을 위반하는 것은 불가능합니다.

pip install csl-core

원래 Project Chimera를 위해 구축되었으며, 현재는 모든 AI 시스템을 위해 오픈 소스로 공개되었습니다.


왜 필요한가요?

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

벤치마크: 적대적 공격 저항성

4개의 최첨단 LLM을 대상으로 프롬프트 기반 안전 규칙과 CSL-Core 강제 조치를 22개의 적대적 공격 및 15개의 정상 작업으로 테스트했습니다:

접근 방식

차단된 공격

우회율

통과된 정상 작업

지연 시간

GPT-4.1 (프롬프트 규칙)

10/22 (45%)

55%

15/15 (100%)

~850ms

GPT-4o (프롬프트 규칙)

15/22 (68%)

32%

15/15 (100%)

~620ms

Claude Sonnet 4 (프롬프트 규칙)

19/22 (86%)

14%

15/15 (100%)

~480ms

Gemini 2.0 Flash (프롬프트 규칙)

11/22 (50%)

50%

15/15 (100%)

~410ms

CSL-Core (결정론적)

22/22 (100%)

0%

15/15 (100%)

~0.84ms

왜 100%인가요? 강제 조치가 모델 외부에서 발생하기 때문입니다. 프롬프트 인젝션은 인젝션할 대상이 없으므로 무의미합니다. 공격 범주: 직접적인 지시 재정의, 역할극 탈옥, 인코딩 트릭, 다중 턴 에스컬레이션, 도구 이름 스푸핑 등.

전체 방법론: benchmarks/


LangChain 통합

프롬프트 변경이나 파인튜닝 없이 3줄의 코드로 모든 LangChain 에이전트를 보호하세요:

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 파일은 처음 사용 시 자동으로 다운로드됩니다(공식 TLA+ GitHub 릴리스에서 약 4MB).

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)

코드 작성 없이 AI 어시스턴트에서 직접 안전 정책을 작성, 검증 및 강제하세요.

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

AI 안전

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 검증 · Fail-closed 런타임 · LangChain 통합 · CLI (verify, simulate, repl, formal) · MCP 서버 · 실제 TLC를 사용한 TLA⁺ 모델 검증 · 술어 추상화 · 반례 분석 · Chimera v1.7.0 프로덕션 배포

🚧 진행 중: 정책 버전 관리 · LangGraph 통합

🔮 계획 중: LlamaIndex 및 AutoGen · 다중 정책 구성 · 핫 리로드 · 정책 마켓플레이스 · 클라우드 템플릿

🔒 엔터프라이즈 (연구 중): 인과 추론 · 멀티 테넌시


기여하기

기여를 환영합니다! good first issue에서 시작하거나 CONTRIBUTING.md를 확인하세요.

영향력이 큰 분야: 실제 정책 예시 · 프레임워크 통합 · 웹 기반 정책 편집기 · 테스트 커버리지


라이선스

Apache 2.0 (오픈 코어 모델). 전체 언어, 컴파일러, Z3 검증기, 런타임, CLI, MCP 서버 및 모든 예제는 오픈 소스입니다. LICENSE를 참조하세요.


Chimera Protocol이 ❤️를 담아 제작 · 이슈 · 토론 · 이메일

Install Server
A
security – no known vulnerabilities
A
license - permissive license
A
quality - A tier

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Chimera-Protocol/csl-core'

If you have feedback or need assistance with the MCP directory API, please join our Discord server