Metadata-Version: 2.5
Name: azem
Version: 0.2.0
Summary: Compile an Apache Ossie semantic model into correct SQL, attest it against a live database, and serve it to agents.
License-Expression: MIT
License-File: LICENSE
Keywords: agent,mcp,ossie,semantic-layer,sql
Requires-Python: >=3.11
Requires-Dist: clickhouse-connect[sqlalchemy]>=1.9
Requires-Dist: jsonschema>=4.26
Requires-Dist: psycopg[binary]>=3.2
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: sqlglot>=30.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: mcp
Requires-Dist: fastmcp>=4.0.10; extra == 'mcp'
Description-Content-Type: text/markdown

# azem

Turn a data definition into correct SQL and agent tools.

Write your data once as an [Apache Ossie](https://github.com/apache/ossie)
semantic model. azem compiles that model into correct SQL, proves the model
against a live database, and serves it to agents over MCP.

The agent does not guess joins, filters, or metric formulas. That logic lives in
the model and the compiler.

## Why

An agent that writes SQL from scratch gets three things wrong:

1. It guesses joins.
1. It forgets metric filters, such as `status = 'completed'`.
1. It picks the wrong column, such as the product list price instead of the price at time of sale.

azem removes all three. The model declares the joins and the metric formula.
The compiler builds the SQL. The attestation layer proves the model still
matches the database.

## How it works

```
 Ossie YAML        Compiler          Agent tools          Database
+-----------+    +-----------+     +---------------+    +-----------+
| datasets  |    | base      |     | list/describe |    | read-only |
| joins     | -> | join path | ->  | search/metric | -> | SQL       |
| metrics   |    | fan-out   |     | compile/run   |    |           |
+-----------+    +-----------+     +---------------+    +-----------+
       \                                                /
        \------------ attest (prove it still holds) ---/
```

Five steps:

1. **Define** the data in Ossie YAML.
1. **Connect** to PostgreSQL, SQLite, or ClickHouse (read-only).
1. **Compile** a structured request into SQL.
1. **Attest** the model against the live database.
1. **Serve** the model to an agent over MCP.

## Intended use case

A commerce analyst asks: **“What was completed-order revenue by customer region in Q3 2026?”**
The model defines `revenue` as quantity times the line-item price at sale, counts only
`completed` orders, and declares the path through orders, customers, and regions. The
agent supplies the question and date range; azem compiles the joins and metric logic.

For the seeded example, the result is Asia Pacific **$165.00** and Europe **$200.00**.
The sample includes an instruction not to show customer email, but model context is
advisory—not field-level access control. Protect sensitive columns with database
grants or views. See the [walkthrough](wiki/use-cases/ecommerce-analytics.md) for the
full flow and boundaries.

## Quick start

Requirements: Python 3.11 or later, and SQLite, PostgreSQL, or ClickHouse.
SQLite needs no server, so it is the fastest start. All three connectors are read-only;
use least-privilege database credentials as well as azem's connection safeguards.

```bash
# 1. Install azem with the MCP extra
uv sync --extra dev --extra mcp

# 2. Load the example data into a fresh/demo SQLite file. The seed drops and
#    recreates its ecommerce table names; do not target valuable existing data.
sqlite3 ecommerce.db < examples/ecommerce.sql

# 3. Validate the model
uv run azem validate examples/ecommerce.yaml

# 4. Attest the model against the database
uv run azem attest examples/ecommerce.yaml \
  --db sqlite:///ecommerce.db \
  --out attestation.yaml

# 5. Serve the model to an agent
uv run azem serve examples/ecommerce.yaml \
  --db sqlite:///ecommerce.db \
  --attestation attestation.yaml
```

`sqlite3` is the SQLite command-line tool. The Python `sqlite3` module also
works. The read-only mode is `PRAGMA query_only = ON`.

### PostgreSQL instead

PostgreSQL needs a server. `compose.yaml` starts one on port 15432. Use these
commands in place of steps 2, 4, and 5:

```bash
# 2. Start PostgreSQL, create a dedicated demo database, and load the seed
#    (the seed drops/recreates its ecommerce table names in this database).
docker compose up -d postgres-db
docker exec postgres-db createdb -U admin ecommerce_demo
psql 'postgresql://admin:pass@localhost:15432/ecommerce_demo' -f examples/ecommerce.sql

# 4. Attest the model against the database
uv run azem attest examples/ecommerce.yaml \
  --db 'postgresql+psycopg://admin:pass@localhost:15432/ecommerce_demo' \
  --out attestation.yaml

# 5. Serve the model to an agent
uv run azem serve examples/ecommerce.yaml \
  --db 'postgresql+psycopg://admin:pass@localhost:15432/ecommerce_demo' \
  --attestation attestation.yaml
```

### ClickHouse instead

ClickHouse needs a server. `compose.yaml` starts one on ports 8123 (HTTP) and
9000 (native). Use these commands in place of steps 2, 4, and 5:

```bash
# 2. Start ClickHouse, create a dedicated demo database, and load the seed
#    (the seed drops/recreates its ecommerce table names in this database).
docker compose up -d clickhouse-db
docker exec clickhouse-db clickhouse-client \
  --user default --password changeme --query 'CREATE DATABASE ecommerce_demo'
docker exec -i clickhouse-db clickhouse-client \
  --user default --password changeme --database ecommerce_demo --multiquery \
  < examples/ecommerce.clickhouse.sql

# 4. Attest the model against the database
uv run azem attest examples/ecommerce.yaml \
  --db 'clickhousedb://default:changeme@localhost:8123/ecommerce_demo' \
  --out attestation.yaml

# 5. Serve the model to an agent
uv run azem serve examples/ecommerce.yaml \
  --db 'clickhousedb://default:changeme@localhost:8123/ecommerce_demo' \
  --attestation attestation.yaml
```

ClickHouse does not enforce `REFERENCES` or `PRIMARY KEY`, so the seed file
omits them. The connector sets `readonly=2`, a query timeout, and scan/result
caps on every connect. The seed is a small demo schema, not a production schema
recommendation. Its sort keys reflect the sample query patterns and it uses
native numeric types, `LowCardinality(String)`, and `Enum8`. The compiler emits
`LEFT ANY JOIN` for many-to-one joins. The local password and ports are for
development only.

### Calendar time grains and window limits

Structured requests can group a declared time dimension by `day`, `week`,
`month`, `quarter`, or `year`. For example, the monthly request groups revenue
and order count by `orders.order_date`:

```bash
uv run azem compile examples/ecommerce.yaml \
  examples/monthly_revenue_request.json --dialect sqlite \
  --max-time-range-months 3
```

The sample returns August 2026 revenue of `$75.00` (1 completed order) and
September revenue of `$290.00` (2 completed orders). The optional
`--max-time-range-months 3` requires bounded `between` filters on modeled time
dimensions and rejects any range wider than three calendar months. Configure the
same guard on MCP serving with `--max-time-range-months 3`; while active, raw
SQL execution and `sample_values` are disabled as bypasses. The example's date
filter aligns with the ClickHouse `orders` sort key. The Python `compile_query`
API accepts the equivalent `max_time_range_months=3` argument.

The example asks a real question. Revenue counts only completed orders and uses
the price at time of sale:

```
$ uv run azem compile examples/ecommerce.yaml examples/request.json
SELECT regions.region_name AS region_name,
       SUM(CASE WHEN orders.status = 'completed'
                THEN order_items.quantity * order_items.unit_price END) AS revenue
FROM order_items AS order_items
LEFT JOIN orders AS orders ON order_items.order_id = orders.order_id
LEFT JOIN customers AS customers ON orders.customer_id = customers.customer_id
LEFT JOIN regions AS regions ON customers.region_id = regions.region_id
WHERE orders.order_date BETWEEN '2026-07-01' AND '2026-09-30'
GROUP BY regions.region_name
ORDER BY revenue DESC NULLS LAST
LIMIT 5
```

The compiler added the join path, the `completed` filter, and the price at time
of sale. The agent did not guess any of them. `examples/request.json` holds this
request.

## The model

The model is one Apache Ossie document. Datasets point at physical tables.
Relationships point from the many side to the one side. Metrics hold aggregate
SQL and reference columns as `dataset.column`.

```yaml
version: 0.2.0.dev0
name: ecommerce_analytics
datasets:
  - name: orders
    source: orders
    primary_key: [order_id]
    fields:
      - name: status
        expression: { dialects: [{ dialect: ANSI_SQL, expression: status }] }
        datatype: String
        ai_context:
          instructions: "Values: completed, cancelled, pending."
  - name: order_items
    source: order_items
    fields:
      - name: unit_price
        expression: { dialects: [{ dialect: ANSI_SQL, expression: unit_price }] }
        datatype: Decimal
relationships:
  - { name: order_items_to_orders, from: order_items, to: orders,
      from_columns: [order_id], to_columns: [order_id] }
metrics:
  - name: revenue
    datatype: Decimal
    expression:
      dialects:
        - dialect: ANSI_SQL
          expression: >
            SUM(CASE WHEN orders.status = 'completed'
                     THEN order_items.quantity * order_items.unit_price END)
```

See `examples/ecommerce.yaml` for the full model.

## Command line

| Command                                                   | Purpose                                                                                        |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `azem validate <model>`                                   | Validate the model against the Ossie spec                                                      |
| `azem compile <model> <request.json>`                     | Compile SQL; optional `--max-time-range-months N` guard                                        |
| `azem attest <model> --db <url> [--out report.yaml]`      | Check the model against the database                                                           |
| `azem serve <model> --db <url> --attestation report.yaml` | Serve after attestation; optional time-window guard; `--force` explicitly bypasses attestation |

A request file looks like this:

```json
{
  "metrics": ["revenue"],
  "dimensions": ["regions.region_name"],
  "filters": [
    {"field": "orders.order_date", "op": "between", "value": ["2026-07-01", "2026-09-30"]}
  ],
  "order_by": [{"field": "revenue", "direction": "desc"}],
  "limit": 5
}
```

`time_grains` is an optional map from a requested time dimension to `day`,
`week`, `month`, `quarter`, or `year`; see the monthly request example.

Operators: `=`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not_in`, `between`, `like`,
`not_like`, `is_null`, `is_not_null`.

## Python API

```python
from azem import Connection, SemanticModel

model = SemanticModel.from_file("examples/ecommerce.yaml")

with Connection.from_url("sqlite:///ecommerce.db") as conn:
    sql = model.compile({"metrics": ["revenue"], "dimensions": ["regions.region_name"]}, "sqlite")
    rows = conn.run(sql)
    report = model.attest(conn)
    print(report.result, report.summary)
```

## Agent tools

`ToolSet` defines each tool once. `azem serve` exposes them over MCP.
`as_anthropic()` and `as_openai()` return the same tools for those APIs.

| Tool               | Purpose                                               |
| ------------------ | ----------------------------------------------------- |
| `list_datasets`    | Names and one-line descriptions                       |
| `describe_dataset` | Fields, types, keys, allowed values                   |
| `search_model`     | Find datasets, fields, metrics by name or synonym     |
| `get_metric`       | Formula, description, synonyms                        |
| `find_join_path`   | Shortest valid join path; never a guessed join        |
| `sample_values`    | Real distinct values for spelling and case            |
| `compile_query`    | Structured request in, correct SQL out                |
| `validate_sql`     | Check agent SQL: SELECT only, known tables, row limit |
| `run_query`        | Run SQL after the safety check                        |

### Connect an agent

```json
{
  "mcpServers": {
    "azem": {
      "command": "uvx",
      "args": ["--from", "azem[mcp]", "azem", "serve",
               "/path/to/ecommerce.yaml",
               "--db", "postgresql+psycopg://admin:pass@localhost:15432/ecommerce_demo",
               "--attestation", "/path/to/attestation.yaml"]
    }
  }
}
```

The first run downloads `azem` and the MCP extra. Use absolute paths for the
model and the report. `uvx` does not run in a project directory.

`serve` requires an attestation report unless `--force` is explicitly supplied.
The report must pass and match both the current model hash and the database URL
(identity is recorded without the password); a failure blocks startup. `--force`
prints a warning and bypasses the gate. Model `ai_context` is guidance to an
agent, not an access-control boundary.

## Compiler rules

**Base dataset.** For each metric, the compiler parses its expression and
collects the datasets it references. It picks the dataset that reaches the
others by many-to-one steps. For `revenue`, that is `order_items`. For
`order_count`, that is `orders`.

When a request includes several metrics, the compiler pre-aggregates each one
in its own CTE at the requested dimensions, then combines the results. This
keeps a join for one metric from multiplying another metric's rows.

**Fan-out.** A step from the one side to the many side copies rows. That
inflates a plain `SUM`. The compiler allows the step only when every aggregate
in that metric uses `DISTINCT`. Each metric is checked independently before
multi-metric results are combined. Otherwise compilation stops and names the
datasets.

**Dialect.** Each field and metric can hold one expression per dialect. The
compiler picks the matching dialect, then ANSI SQL. SQL is rendered with
`sqlglot`.

## Attestation

Checks come from the model. No extra YAML is needed.

| Declared           | Check                           |
| ------------------ | ------------------------------- |
| `source`           | table runs                      |
| field `expression` | expression runs                 |
| `primary_key`      | unique and not null             |
| relationship       | no orphan foreign keys          |
| relationship       | the one-side key is unique      |
| metric             | query runs and returns a number |

The report is YAML. It records the model hash, the database, the time, the
result, and every check.

```yaml
attestation:
  model: ecommerce_analytics
  spec_version: 0.2.0.dev0
  model_hash: sha256:b9f0d671...
  database: postgresql+psycopg://admin:***@localhost:15432/ecommerce_demo
  run_at: '2026-10-03T01:29:35+00:00'
  result: passed
  summary: { passed: 31, failed: 0, warned: 0 }
```

The model hash binds the report to one model revision. Run attest in CI on every
model change. Serve only after a pass.

## Install

```bash
uv add azem
```

With the MCP server extra:

```bash
uv add "azem[mcp]"
```

To run the `azem` command-line tool:

```bash
uv tool install azem
```

Or install from source:

```bash
git clone <repo> azem
cd azem
uv sync --extra dev --extra mcp
```

## Development

```bash
# Unit tests and the SQLite smoke test (no server needed)
uv run --extra dev pytest

# Full suite. Use dedicated, disposable databases: the seed fixtures drop and
# recreate the example table names inside the database URLs below.
docker compose up -d
# Create each database once; use unused names.
docker exec postgres-db createdb -U admin azem_test
docker exec clickhouse-db clickhouse-client \
  --user default --password changeme --query 'CREATE DATABASE azem_test'
AZEM_TEST_DB_URL='postgresql+psycopg://admin:pass@localhost:15432/azem_test' \
AZEM_TEST_CLICKHOUSE_URL='clickhousedb://default:changeme@localhost:8123/azem_test' \
  uv run --extra dev --extra mcp pytest
```

The suite contains 88 logical test functions and collects 110 test cases,
including PostgreSQL and ClickHouse parametrizations. The SQLite smoke tests
always run. PostgreSQL and ClickHouse tests skip when their respective
`AZEM_TEST_*_URL` is unset; server tests require the `mcp` extra. **Never point
these destructive seed fixtures at a shared or production database.**

## Architecture

- `src/azem/spec/` — vendored Apache Ossie models and JSON Schema.
- `src/azem/model/` — load, validate, and join-path search.
- `src/azem/compiler/` — build SQL from a structured request.
- `src/azem/safety.py` — gate agent-written SQL.
- `src/azem/connectors.py` — database connections (PostgreSQL, SQLite, ClickHouse).
- `src/azem/attest.py` — check the model against the live database.
- `src/azem/tools.py` — agent tool definitions and adapters.
- `src/azem/server.py` — FastMCP 4 server.

The `model/` and `compiler/` packages know nothing about databases or agents.

## Beta readiness

The current package version is **0.2.0**. PostgreSQL, SQLite, and ClickHouse
connectors are implemented; the examples and test suite are the compatibility
contract. The suite has 88 logical test functions (110 collected cases,
including PostgreSQL and ClickHouse parametrizations). A minimal local run
intentionally skips server-gated tests when those services are not configured.

The supported path is read-only semantic analytics: Ossie model validation,
fan-out-aware SQL compilation, calendar time grains, derived attestation, SQL
safety checks, and nine MCP tools. An optional `--max-time-range-months 3`
server policy requires bounded time filters and disables raw-query execution as
a bypass. This is a beta-quality starting point, not a general-purpose SQL
proxy or an ingestion/migration system. Known gaps include automatic model
drafting, configurable freshness/reconcile checks, sub-day time grains, and a
SQLite query timeout. The network MCP transport also needs an external
authenticated boundary before deployment. See the [0.2.0 release notes](CHANGELOG.md)
and [beta readiness guide](wiki/operations/beta-readiness.md) for the support
matrix, safety caveats, and release checklist.

## License

MIT. The vendored Apache Ossie files stay under Apache-2.0. See
`src/azem/spec/LICENSE-APACHE`.
