chiasmus.cr v0.3.2

Crystal port of chiasmus: MCP server for formal verification with Z3 SMT solver, SWI-Prolog, and tree-sitter-based source code analysis. Uses Crig for LLM integration with DeepSeek support.

Chiasmus.cr

CI

Crystal port of yogthos/chiasmus, built as an MCP server for formal verification and source-code analysis.

Chiasmus.cr combines:

  • Z3 for SMT-based reasoning
  • SWI-Prolog, driven through crolog, for graph and rule queries
  • tree-sitter for multi-language code extraction
  • crig for provider-backed LLM and embedding calls

The upstream TypeScript project in vendor/chiasmus remains the behavioral source of truth. This repo ports that behavior into Crystal and adds native binaries for MCP serving, grammar management, discovery, parity checking, and an interactive agent CLI.

What It Does

At a high level, Chiasmus gives an LLM a toolbelt for turning vague questions into executable checks.

  • chiasmus_formalize finds an existing formalization template and returns the skeleton, required slots, and instructions.
  • chiasmus_verify runs either Z3 or Prolog on a filled-in spec and returns the actual solver result.
  • chiasmus_solve runs the full loop: template selection, slot filling, linting, verification, and correction.
  • chiasmus_graph parses source files with tree-sitter, extracts a call graph, and runs analyses such as reachability, dead-code detection, cycles, impact, and facts export.
  • chiasmus_search builds an embedding corpus from extracted defines and performs semantic code search.
  • chiasmus_review generates a structured review plan that tells an LLM which graph and verification steps to run and in what order.

This is useful when you want answers that are grounded in either:

  • a formal proof or counterexample
  • a concrete call path in real code
  • a constrained, inspectable workflow rather than free-form speculation

How It Works

1. MCP server lifecycle

The main chiasmus binary starts an MCP server over stdio by default. It can also run an HTTP streamable transport for debugging.

  • ./bin/chiasmus
  • ./bin/chiasmus --healthcheck
  • ./bin/chiasmus --streamable --port 8899

The healthcheck does a real in-memory MCP initialize plus tools/list, so it verifies the server’s actual runtime wiring instead of just checking that the process starts.

2. LLM-backed and no-LLM modes

LLM configuration comes from environment variables. The default provider is deepseek, and the model can also imply the provider when only a model name is given.

When an LLM backend is not configured, the server still starts:

  • chiasmus_formalize falls back to template search
  • chiasmus_solve falls back to the formalize path
  • chiasmus_learn is retired: it is never listed, and a client that still calls it gets a notice pointing at chiasmus_craft

That design keeps the verification and graph-analysis parts useful even on machines without API keys.

3. Formal verification flow

The formal side has three layers:

  1. A skill/template library describing reusable solver patterns
  2. Tooling that selects and fills those templates
  3. Solver adapters for Z3 and Prolog

Typical flow:

  1. Ask chiasmus_formalize for a template matching the problem
  2. Fill the returned slots with concrete declarations, rules, facts, or constraints
  3. Run chiasmus_verify
  4. Optionally use chiasmus_craft to store a reusable, validated template

4. Code analysis flow

The graph side parses files with language-specific walkers where available and a generic fallback otherwise.

Typical flow:

  1. chiasmus_graph loads files and extracts defines/calls/facts
  2. Graph algorithms answer reachability, callers, callees, cycles, impact, and dead-code questions
  3. chiasmus_map projects a large graph into an LLM-friendly summary
  4. chiasmus_search embeds the extracted defines for semantic lookup
  5. chiasmus_review composes these pieces into a review recipe

Extraction is wired for concurrent use. Long-running operations are exposed through async boundaries internally so MCP requests can overlap without blocking the server loop.

MCP Tools

The server currently exposes these tool families:

  • chiasmus_verify: run Z3 or Prolog directly
  • chiasmus_skills: search and inspect formalization templates
  • chiasmus_formalize: pick a template for a natural-language problem
  • chiasmus_solve: run the end-to-end solve loop
  • chiasmus_lint: clean and validate a formal spec without executing it
  • chiasmus_graph: extract and analyze call graphs
  • chiasmus_map: return a compact codebase map
  • chiasmus_search: semantic code search over extracted defines
  • chiasmus_craft: author a new template and add it to the library
  • chiasmus_review: generate a phased code-review plan

chiasmus_learn is retired and no longer listed; calls by that name return {"status":"error","error":"chiasmus_learn was retired; use chiasmus_craft"}.

  • chiasmus_crig: run a direct prompt against the configured LLM provider

Included Binaries

shard.yml defines multiple targets:

  • chiasmus: MCP server entrypoint (stdio / streamable HTTP)
  • chiasmus-agent: interactive CLI for graph-aware formal solving
  • chiasmus-grammar: grammar manager for install, compile, update, and cache operations
  • chiasmus-discover: tree-sitter discovery CLI for parity manifests
  • chiasmus-facts: extracts layer-A Prolog facts from a source tree
  • chiasmus-parity: curated-ledger parity report + reconciliation/diff formats
  • chiasmus-plan: plans a port from source facts (rank/slice/seed/track)
  • chiasmus-complete: completion gate over the curated ledger

See docs/CLI-BINARIES.md for each binary's synopsis, options, and exit codes.

Quick Start

Setup

git clone --recursive https://github.com/dsisnero/chiasmus.cr.git
cd chiasmus.cr
shards install
make build
make build-clis
make setup-grammars

Verify the server

./bin/chiasmus --healthcheck

Start the MCP server

./bin/chiasmus

Run the agent CLI

./bin/chiasmus-agent --help

Inspect grammar tooling

./bin/chiasmus-grammar --help
./bin/chiasmus-discover --help
./bin/chiasmus-parity --help

Configuration

LLM provider selection

Common environment variables:

export CHIASMUS_LLM_PROVIDER=deepseek
export CHIASMUS_LLM_MODEL=deepseek-chat
export DEEPSEEK_API_KEY=...

Supported provider families in the server factory include:

  • deepseek
  • openai
  • anthropic
  • gemini
  • groq
  • ollama
  • mistral
  • cohere

Embeddings for semantic search

chiasmus_search uses embeddings plus cosine similarity over extracted defines. Pass either a files array or an absolute directory; directory mode discovers supported source files and accepts optional include globs relative to that directory:

{"query":"where are model calls retried?","directory":"/absolute/path/to/repo","include":["src/**/*.cr"]}

Directory mode uses Git-aware file discovery, then filters before extraction and embedding. It returns searched_files with the hits and fails clearly above 500 files or 25 MiB of source. Use files for a small, exact corpus.

A reachable local Ollama embedding model is used by default, so no API key is required:

ollama pull nomic-embed-text   # 768 dimensions

Selection order when CHIASMUS_EMBED_PROVIDER is unset:

  1. A local Ollama endpoint serving the embedding model (local-first: free, private, no source code leaves the machine)
  2. OPENAI_API_KEY → OpenAI text-embedding-3-small
  3. OPENROUTER_API_KEY → OpenRouter
  4. DEEPSEEK_API_KEY + CHIASMUS_EMBED_URL → that OpenAI-compatible endpoint

Name a provider explicitly to override the order:

export CHIASMUS_EMBED_PROVIDER=ollama      # ollama | openai | openrouter | deepseek
export CHIASMUS_EMBED_MODEL=nomic-embed-text
export CHIASMUS_EMBED_URL=http://localhost:11434   # optional base URL override

DEEPSEEK_API_KEY alone is never auto-selected: DeepSeek has no /embeddings endpoint, so it only backs search when CHIASMUS_EMBED_URL points at an OpenAI-compatible embeddings endpoint (a gateway, or a local Ollama).

chiasmus_search is only advertised when the backend is actually usable: an explicit provider counts immediately, while the implicit Ollama default is probed and hidden from the tool list until Ollama serves the model.

The TypeScript upstream's CHIASMUS_LOCAL_EMBED* / localEmbeddings options use the Node-only node-llama-cpp backend and are not supported by this Crystal build. Use CHIASMUS_EMBED_PROVIDER=ollama with an embedding model such as nomic-embed-text instead.

Grammar installation and lookup

shards install downloads the tree-sitter-manager library only. It does not build a dependency's executable target or put tree-sitter-manager on PATH. make build-clis builds this project's manager-backed wrapper instead:

make build-clis
make setup-grammars

make setup-grammars installs Chiasmus's preinstalled baseline, including Scheme and Common Lisp. Racket files use the Scheme grammar. To install only those S-expression grammars, run:

./bin/chiasmus-grammar batch scheme,commonlisp

The wrapper delegates downloads, native builds, and cache management to tree-sitter-manager; a checked-out grammar source tree or the separate native tree-sitter command is not needed for normal installation. Use chiasmus-grammar compile LANGUAGE only when intentionally compiling a local grammar source under ./grammars.

Graph extraction and discovery look for grammars in this order:

  1. CHIASMUS_GRAMMAR_DIR
  2. bundled ./grammars
  3. XDG cache directories
  4. project grammar directories when available

The chiasmus-grammar binary is the supported way to manage those parser artifacts.

Supported Analysis Surface

The graph subsystem has dedicated walkers for the primary languages Chiasmus is optimized around:

  • Crystal
  • TypeScript and TSX
  • JavaScript
  • Python
  • Go
  • Rust
  • Java
  • C#
  • C++
  • C
  • Kotlin
  • Scala
  • Dart
  • PHP
  • Perl
  • Bash
  • Protobuf
  • Clojure
  • Scheme and Racket
  • Common Lisp

The language registry also tracks additional languages and extensions for grammar management and future expansion.

Repository Layout

chiasmus.cr/
├── src/
│   ├── chiasmus_cli.cr         # MCP server executable entrypoint
│   ├── chiasmus-agent.cr       # Interactive agent CLI entrypoint
│   ├── chiasmus_discover.cr    # Discovery CLI entrypoint
│   ├── chiasmus_grammar.cr     # Grammar manager entrypoint
│   ├── chiasmus_parity.cr      # Parity CLI entrypoint
│   └── chiasmus/
│       ├── mcp_server/         # Server core and MCP tools
│       ├── graph/              # tree-sitter parsing and graph analyses
│       ├── formalize/          # Template selection and slot-filling flow
│       ├── solvers/            # Z3 and Prolog integrations
│       ├── llm/                # Provider config and adapters
│       ├── search/             # Embedding-based semantic search
│       └── skills/             # Template storage, relationships, learning
├── spec/                       # Crystal specs
├── docs/                       # Maintained prose docs
├── plans/                      # Parity and design plans
├── shards_issues/              # Notes for upstream shard/library bugs
└── vendor/chiasmus/            # Upstream TypeScript source of truth

Development

Core local commands:

make format
make lint
make test
make build
make build-clis

For deeper guidance, use:

Release Notes and Issue Tracking

License

MIT. See LICENSE.

Repository

chiasmus.cr

Owner
Statistic
  • 0
  • 0
  • 1
  • 0
  • 17
  • 5 days ago
  • April 18, 2026
License

MIT License

Links
Synced at

Thu, 19 Nov 2026 00:48:09 GMT

Languages