lu-mcp-server
Lingua Universale
Язык для верифицируемых протоколов AI-агентов.
Попробуйте в браузере -- установка не требуется. Наблюдайте за AI-агентами в реальном времени -- 3 агента на верифицированном протоколе.
Проблема
Ваши AI-агенты общаются друг с другом, но ничто не гарантирует, что они следуют правилам. Неверный отправитель, неправильный порядок сообщений, пропущенные шаги — и вы узнаете об этом только в продакшене.
Lingua Universale (LU) — это средство проверки типов для диалогов AI-агентов. Вы определяете протокол, LU доказывает его корректность, а среда выполнения обеспечивает его соблюдение.
from cervellaswarm_lingua_universale import Protocol, ProtocolStep, MessageKind, SessionChecker, TaskRequest
# Define: who sends what, to whom, in what order
review = Protocol(name="Review", roles=("dev", "reviewer"), elements=(
ProtocolStep(sender="dev", receiver="reviewer", message_kind=MessageKind.TASK_REQUEST),
ProtocolStep(sender="reviewer", receiver="dev", message_kind=MessageKind.TASK_RESULT),
))
checker = SessionChecker(review)
checker.send("dev", "reviewer", TaskRequest(task_id="1", description="Review auth")) # OK
checker.send("dev", "reviewer", TaskRequest(task_id="2", description="Oops")) # ProtocolViolation!
# ^^^ wrong turn: reviewer must send nextПротокол гласит, что следующим должен быть рецензент. Среда выполнения блокирует это. Не потому, что вы доверяете коду, а потому, что сессионный тип делает это невозможным.
Related MCP server: correctover-mcp-server
Установка
pip install cervellaswarm-lingua-universaleИли попробуйте сначала: Playground (запускается в браузере через Pyodide).
Написание протокола
protocol DelegateTask:
roles: supervisor, worker, validator
supervisor asks worker to execute analysis
worker returns result to supervisor
supervisor asks validator to verify result
when validator decides:
pass:
validator returns approval to supervisor
fail:
validator sends feedback to supervisor
properties:
always terminates
no deadlock
no deletion
all roles participateЗатем верифицируйте его:
lu verify delegate_task.lu [1/4] always_terminates ... PROVED
[2/4] no_deadlock ... PROVED
[3/4] no_deletion ... PROVED
[4/4] all_roles_participate ... PROVED
All 4 properties PASSED.Математическое доказательство. Не тест, который проходит сегодня и падает завтра.
Что вы получаете
Функция | Описание |
Полный компилятор | Токенизатор, парсер (64 правила), AST, проверка контрактов, генерация кода Python |
9 верифицируемых свойств |
|
20 протоколов stdlib | AI/ML, бизнес, коммуникации, данные, безопасность — готовы к использованию |
Линтер + Форматтер |
|
LSP-сервер | Диагностика, подсказки при наведении, автодополнение, переход к определению, форматирование |
Расширение VS Code | |
Интерактивный чат |
|
Браузерный playground | Попробуйте сейчас — проверка, линтинг, запуск, чат |
Мост Lean 4 | Генерация и проверка математических доказательств |
REPL |
|
Скаффолдинг проектов |
|
37 модулей. 3979 тестов. Ноль внешних зависимостей. Чистая стандартная библиотека Python.
CLI
lu check file.lu # Parse and compile
lu verify file.lu # Formal property verification
lu run file.lu # Execute
lu lint file.lu # 10 style and correctness rules
lu fmt file.lu # Zero-config auto-formatter
lu chat --lang en # Build a protocol conversationally
lu demo --lang it # See the La Nonna demo
lu init --template NAME # Scaffold from stdlib templates
lu visualize file.lu # Generate Mermaid sequence diagram
lu mcp-audit --manifest t.json # Audit MCP server protocols
lu repl # Interactive REPL
lu lsp # Start LSP serverИнтеграция с CI
Добавьте проверку протоколов в ваш рабочий процесс GitHub Actions:
# .github/workflows/lu-check.yml
on:
push:
paths: ["**/*.lu"]
jobs:
lu-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v6
with:
python-version: "3.11"
- run: pip install cervellaswarm-lingua-universale
- run: lu lint protocols/
- run: lu verify protocols/Код выхода ненулевой при нарушениях — работает с любой системой CI.
Как это работает
LU основан на сессионных типах для многих участников (Honda, Yoshida, Carbone — POPL 2008). Сессионные типы описывают протоколы связи как типы: если два процесса следуют одному и тому же сессионному типу, они не могут войти в состояние взаимной блокировки (deadlock), сообщения не могут прийти в неправильном порядке, и диалог всегда завершается.
Конвейер:
.lu source → Tokenizer → Parser → AST → Spec Checker → Lean 4 Proofs → Python Codegen
↓
PROVED or VIOLATEDLU не заменяет ваш фреймворк для AI-агентов. Он делает его безопасным. Как TypeScript для JavaScript — вы сохраняете свои инструменты, но добавляете гарантии.
Примеры
LU Debugger — веб-приложение в реальном времени: 3 AI-агента (Клиент, Склад, Оплата) общаются по верифицированному протоколу OrderProcessing. Нажмите "Break", чтобы увидеть, как нарушение протокола блокируется в реальном времени. Исходный код.
Смотрите директорию examples/:
Оркестрация агентов — 3 AI-агента с вложенным выбором, доказано 8/8 свойств
Live Runner — реальные агенты Claude API на верифицированном протоколе
Стандартная библиотека — 20 верифицированных протоколов в 5 категориях
Или попробуйте интерактивный блокнот Colab — 2 минуты, никакой настройки.
Больше от CervellaSwarm
Lingua Universale — это основной проект от CervellaSwarm. Мы также публикуем следующие пакеты Python:
Пакет | Что он делает |
Понимание кода на основе AST (tree-sitter, PageRank) | |
Хуки жизненного цикла для агентов Claude Code | |
Шаблоны определения агентов и конфигурация команд | |
Детерминированная маршрутизация и валидация задач | |
Управление процессами мультиагентных систем | |
Постоянный контекст сессии между диалогами | |
Неизменяемое логирование событий и аудит | |
Автоматизированные проверки качества и скоринг |
Все под лицензией Apache 2.0, Python 3.10+, протестировано, задокументировано.
Участие в разработке
Мы приветствуем вклад! См. CONTRIBUTING.md для получения инструкций.
Отчеты об ошибках: GitHub Issues
Безопасность: См. SECURITY.md для ответственного раскрытия информации
Лицензия
Apache License 2.0 — см. LICENSE.
Copyright 2025-2026 CervellaSwarm Contributors.
Lingua Universale — Верифицированные протоколы для AI-агентов.
Playground | LU Debugger | PyPI | VS Code | Блог | Демо Colab
Available Tools
4 toolslu_check_propertiesA
Verify the formal safety properties declared in a .lu protocol.
Runs the static property checker (Layer 1) on all protocols found in
the source. Optionally, if Lean 4 is installed, also runs formal
verification (Layer 2).
Args:
protocol_text: Full .lu protocol definition text including a
"properties:" block, e.g.:
" properties:\n"
" always terminates\n"
" no deadlock\n"
" all roles participate\n"
Returns:
JSON string with:
ok (bool), protocols (list of protocol results), summary (dict).
Each protocol result has: protocol_name, all_passed, results (list).
Each result has: kind, verdict, evidence, params.
Inputs: protocol_text (required). Returns: result
lu_list_templatesA
List available Lingua Universale standard library protocol templates.
The standard library contains 20 verified protocols across 5 categories:
communication, data, business, ai_ml, security.
Args:
category: Optional filter. One of: communication, data, business,
ai_ml, security. Leave empty to list all templates.
Returns:
JSON string with:
ok (bool), templates (list), category_filter (str), total (int).
Each template has: name, category, description.
Inputs: category. Returns: result
lu_load_protocolA
Parse a Lingua Universale (.lu) protocol definition.
Accepts the full text of a .lu file and returns the parsed protocol
structure: name, roles, steps, choices, and declared properties.
Args:
protocol_text: Content of a .lu file, e.g.:
"protocol RequestResponse:\n"
" roles: client, server\n"
" client asks server to process request\n"
" server returns response to client\n"
" properties:\n"
" always terminates\n"
" no deadlock\n"
Returns:
JSON string with keys:
ok (bool), protocol_name (str), roles (list[str]),
steps (list), properties (list), error (str on failure).
Inputs: protocol_text (required). Returns: result
lu_verify_messageA
Verify whether a message is valid in the context of an ongoing session.
Replays the existing message history against the protocol, then checks
whether next_message is the expected next step.
Args:
protocol_text: Full .lu protocol definition text.
messages: List of already-sent messages, each a dict with keys:
sender (str), receiver (str), action (str).
Actions are LU action names: "asks", "returns", "sends",
"proposes", "tells". These match the verbs in .lu source files.
next_message: The message to validate, same format as above.
Returns:
JSON string:
On success: {"valid": true, "step": N, "next_expected": "..."}
On violation: {"valid": false, "violation": "...", "expected": "...", "got": "..."}
On error: {"valid": false, "error": "..."}
Example:
protocol_text = "protocol Ping:\n roles: a, b\n a asks b to ping\n b returns pong to a\n properties:\n always terminates\n"
messages = [{"sender": "a", "receiver": "b", "action": "asks"}]
next_message = {"sender": "b", "receiver": "a", "action": "returns"}
# Returns: {"valid": true, ...}
Inputs: protocol_text (required), messages (required), next_message (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool has a distinct purpose: parsing, message verification, property checking, and template listing. No overlap in functionality; agents can easily select the right tool for their task.
Names follow a consistent 'lu_' prefix and verb_noun pattern (load_protocol, verify_message, check_properties, list_templates). Minor deviation: 'load_protocol' could be 'parse_protocol' but still clear and consistent.
With only 4 tools, the server is slightly under the typical 3-15 range, but this is appropriate for a niche protocol validation domain. The tools cover the core needs without bloat.
The server covers parsing, verification, property checking, and template listing, but misses a 'simulate' or 'validate full session' tool. Gaps exist for agents needing end-to-end protocol simulation or editing, but core workflows are supported.
Maintenance
Related MCP Connectors
Verify an agent's output before you pay: JSON Schema + rules, signed receipts. Free during launch.
AI-native programming language and toolchain for accountable, verifiable agent-driven development.
Tamper-evident proof creation and verification for AI agents via MCP, A2A, and REST.
Design, build and run teams of AI agents with checked handoffs between them.
Related MCP Servers
- AlicenseAqualityCmaintenanceIntegrates the Quint formal specification language into LLM workflows for accessible formal verification. It provides tools for type-checking, random simulation, exhaustive model checking, and syntax documentation.62PolyForm Noncommercial 1.0.0
- AlicenseNot gradedqualityBmaintenanceEnables protocol-level runtime verification of AI agent tool calls across six dimensions with a fail-closed guarantee, blocking any action that fails verification before execution.2Elastic 2.0
- -licenseNot gradedqualityBmaintenanceEnables AI agents to safely run Pact 5 REPL tests, scan modules for critical language traps, estimate gas, generate contracts, and invoke formal verification via a standalone prover plugin.-
- AlicenseCqualityBmaintenanceEnables AI assistants and autonomous agents to intercept arithmetic and algebraic hallucinations via exact rational verification, seal multi-step reasoning chains with SHA-256 Merkle commitments, and optionally bridge deep verification to a remote sovereign enclave. It also supports BFT epistemic consensus across multi-agent proposals and tamper-evident session sealing.15MIT