# React and MCP clients (/docs/python/client-endpoints)

A Python backend can feed the same `@hypequery/react` hooks that TypeScript backends use, and serves AI agents with its
own `hypequery mcp` server.
Python keeps ownership of SQL, authentication and the tenant. The frontend and the agent only ever see a **client
contract**: a JSON description of each endpoint's fields, operators, limits and schema hash.

| Step | Where | Command or API |
| --- | --- | --- |
| [1. Declare datasets](#1-declare-datasets) | Python | Datasets and a `ClientQueryProfile` |
| [2. Install the endpoints](#2-install-the-endpoints) | Python | `create_api(..., client_profile=...)`, or `add_dataset_endpoint(..., client_profile=...)` and `add_metric_endpoint` |
| [3. Export the contract](#3-export-the-contract) | Python, then frontend | `python -m hypequery export client-contract --factory analytics.api:api`, then `npx hypequery generate:client` |
| [4. Connect MCP](#4-connect-mcp) | Python | `hypequery mcp app:api` (or `--client-contract-url https://…/v1/client-contract`) |

The Python side, including the MCP server (`pip install "hypequery[mcp]"`), needs no Node process. Only generating the
React client does. On the frontend, see [React: datasets served from Python](/docs/react/getting-started#datasets-served-from-python)
for per-login clients, cache scope and result types.

## 1. Declare datasets [#1-declare-datasets]

Datasets are ordinary [dataset definitions](/docs/python/datasets/overview). A `ClientQueryProfile` sets the default
and maximum page size clients may request; dataset limits and the endpoint policy can only lower it.

<CodeBlock>
```python
# analytics/definitions.py
from hypequery.datasets import (
    ClientQueryProfile,
    belongs_to,
    create_dataset_registry,
    dataset,
    dimension,
    measure,
)

customers = dataset(
    "customers",
    source="customers",
    tenant_key="org_id",
    dimensions={"country": dimension.string(), "segment": dimension.string()},
    measures={"customerCount": measure.count_distinct("customer_id")},
)

orders = dataset(
    "orders",
    source="orders",
    tenant_key="org_id",
    time_key="created_at",
    dimensions={
        "status": dimension.string(),
        "createdAt": dimension.timestamp(column="created_at"),
    },
    measures={"revenue": measure.sum("amount"), "orderCount": measure.count("order_id")},
    relationships={
        "customer": belongs_to(lambda: customers, from_field="customer_id", to_field="customer_id")
    },
)

registry = create_dataset_registry(orders, customers)
profile = ClientQueryProfile(default_limit=50, max_limit=500)
```
</CodeBlock>

## 2. Install the endpoints [#2-install-the-endpoints]

An endpoint is in the client contract when it is installed with a client profile. `create_api(client_profile=...)`
applies one to every `Dataset` in `datasets=`; an endpoint from `create_dataset_endpoint` or `create_metric_endpoint`
takes its own `client_profile=`. Add `add_client_contract_endpoint` for live discovery, and allow your frontend's origin
with `CorsPolicy`:

<CodeBlock>
```python
# analytics/api.py
from hypequery.datasets import create_dataset_client
from hypequery.execution import ClickHouseConnection, create_clickhouse_executor
from hypequery.serve import (
    CorsPolicy,
    EndpointPolicy,
    HttpSecurity,
    add_client_contract_endpoint,
    create_api,
    create_dataset_endpoint,
    create_metric_endpoint,
    to_asgi_app,
)

from .auth import authenticate  # your credential lookup, or jwt_strategy(...)
from .definitions import orders, profile, registry

executor = create_clickhouse_executor(ClickHouseConnection.from_env())
client = create_dataset_client(executor=executor, registry=registry)
policy = EndpointPolicy(tenant="required", required_scopes=frozenset({"analytics:read"}))

api = create_api(
    auth=authenticate,
    security=HttpSecurity(
        allowed_hosts=("analytics.example.com",),
        cors=CorsPolicy(origins=("https://app.example.com",)),
    ),
    datasets={  # POST /datasets/orders/query
        "orders": create_dataset_endpoint(
            dataset=orders, client=client, policy=policy, client_profile=profile
        ),
    },
    metrics={  # POST /metrics/revenue
        "revenue": create_metric_endpoint(
            dataset=orders, measure="revenue", client=client, policy=policy, client_profile=profile
        ),
    },
)
add_client_contract_endpoint(api, "/v1/client-contract", policy=policy)

app = to_asgi_app(api)
```
</CodeBlock>

- A metric's key in `metrics=` is its name: its ID in the contract (and so its React hook key), the output alias of its
  measure, and its path. `create_metric_endpoint(..., name=...)` may only repeat the key.
- Every route here takes the same `policy`, so a caller needs the `analytics:read` scope for the orders query, the
  metric and the contract alike. When the default policy is enough, a bare `Dataset` is shorter:
  `datasets={"orders": orders}` with `create_api(..., client=client, client_profile=profile)` serves it under the
  default policy and puts it in the contract.
- Related fields (`customer.country`, related measures) are left out unless the endpoint names the relationship:
  `create_dataset_endpoint(..., include_related={"customer"})`.
- To choose your own paths, install endpoints with `add_dataset_endpoint(api, "/v1/orders", ..., client_profile=...)`
  and `add_metric_endpoint(api, "/v1/revenue", ..., name="revenue", client_profile=...)`.

`CorsPolicy` already allows the `X-Hypequery-Client-Schema` header that generated clients send. The same API can be
served from [Django](/docs/python/django#serve-hypequerys-endpoints) with `urls(api)` or
[Flask](/docs/python/flask#serve-hypequerys-endpoints) with `blueprint(api)` instead of `to_asgi_app`. Strict client
endpoints are checked when the adapter is created, so a mismatch fails at startup. Close the executor at shutdown, for
example with `to_asgi_app(api, lifespan=...)`.

Endpoints installed **without** a client profile keep their ordinary request handling and are left out of client
contracts, so they get no generated hooks.

## 3. Export the contract [#3-export-the-contract]

Export from the installed API, so the contract always names the paths and limits the API serves. `--factory` names the
API (or its `to_asgi_app` or `to_wsgi_app` application), or a zero-argument function that returns it:

<CodeBlock>
```bash
python -m hypequery export client-contract \
  --factory analytics.api:api \
  --output web/client-contract.json
```
</CodeBlock>

Run it from the directory that makes `analytics` importable. Use `--check` in CI to fail when the API changed but the
committed contract did not, and `--force` to replace an existing file. See [Python CLI](/docs/python/cli). In code,
`hypequery.serve.export_client_contract(api)` returns the same contract.

An export that would contain no endpoints fails, naming every dataset and metric route installed without a client
profile:

<CodeBlock>
```text
hypequery: The client contract has no endpoints: POST /datasets/orders/query has no client_profile. Pass
client_profile= to create_api for Dataset entries, or to create_dataset_endpoint, create_metric_endpoint or the add_*
functions.
```
</CodeBlock>

The export imports your module but never queries. Django's `get_client()` and Flask's `client_for(app)` connect on
their first query, so their APIs export with no database reachable; see the [Django](/docs/python/django#typed-react-hooks)
and [Flask](/docs/python/flask#typed-react-hooks) guides. `create_clickhouse_executor` connects when it is called, so an
API module that calls it at import needs ClickHouse to answer during the export.

### Exporting without importing the API [#exporting-without-importing-the-api]

Where importing the API is not possible, for example in a CI job with no database or secrets, export from
definition-only metadata instead. Each `ClientEndpointDefinition` must repeat the path and relationships its endpoint is
installed with:

<CodeBlock>
```python
# analytics/contract.py
from hypequery.datasets import ClientEndpointDefinition, export_client_contract

from .definitions import orders, profile, registry


def build():
    """Zero-argument factory for `hypequery export client-contract --factory analytics.contract:build`."""
    return export_client_contract(
        [
            ClientEndpointDefinition(orders, "/datasets/orders/query", profile),
            ClientEndpointDefinition(orders, "/metrics/revenue", profile, measure="revenue", name="revenue"),
        ],
        registry=registry,
    )
```
</CodeBlock>

Add `related=` for the relationships an endpoint passes as `include_related=`. Keep this module free of
`hypequery.serve`, database drivers and credentials.

<Callout type="warn" title="Keep both sides in step">
  The schema hash covers the path, profile and related fields. If a definition's path or `related=` differs from the
  installed endpoint's, the exported contract does not match the live endpoint, and every request from the generated
  client gets `409 CLIENT_SCHEMA_CHANGED`. Exporting from the installed API avoids this.
</Callout>

The live `/v1/client-contract` route returns a different, **authorized** view for the calling principal. That view is
for MCP and discovery; `generate:client` refuses it, because a build must come from the definition owner.

If the API is mounted under a prefix, set `client_mount_path=` on `create_api(...)` (or `mount_path=` for
definition-only exports) so exported paths match the URLs browsers call.

Then generate the React client in the frontend project (`web/` here, where the contract was written), as described in
[React: datasets served from Python](/docs/react/getting-started#datasets-served-from-python):

<CodeBlock>
```bash
npm install -D @hypequery/cli
npx hypequery generate:client client-contract.json --output src/hypequery-client.ts
```
</CodeBlock>

## 4. Connect MCP [#4-connect-mcp]

`hypequery mcp` serves the same authorized contract to AI agents over MCP stdio. Tool calls become the same requests a
React client sends, through `Api.handle` in-process, and each server process acts as one principal:

<CodeBlock>
```bash
pip install "hypequery[mcp]"
HYPEQUERY_API_KEY=… hypequery mcp app:agents_api --self-test
hypequery mcp app:agents_api --print-config
```
</CodeBlock>

Use `--client-contract-url https://…/v1/client-contract` instead of an app to bridge an API that is already deployed.
See [MCP: datasets served from Python](/docs/mcp/overview#datasets-served-from-python) for URL rules, credentials and
client configuration.

## What the generated types guarantee [#what-the-generated-types-guarantee]

Generated hooks are checked against the contract at compile time:

- Only declared endpoints, dimensions, measures and `orderBy` fields are accepted. Related fields appear only on
  endpoints that opted in, and there is no tenant input at all.
- Filter values follow each field's type and operator; `between` takes exactly two values and `in` at least one.
- Metric endpoints take no `measures`; dataset endpoints accept `having` on their measures.
- Rows contain exactly the selected fields: omitted `measures` select the endpoint's defaults, and `measures: []`
  selects none. Fields named in a literal selection are always present; fields picked from a runtime `string[]` are
  optional.
- Measure values are `string | null`, so decimals keep their precision. Numeric dimensions are `number | string |
  null`; timestamps are strings. Base dimensions include `null`, because the contract does not declare columns
  non-nullable.

Types describe what the server accepts; a contract describes capabilities and grants no permission. Python still
authorizes, validates and clamps every request.

A `label` and `description` on datasets, dimensions and measures travel in the contract as presentation annotations:
`list_datasets` shows each dataset's description to agents, `get_dataset_schema` includes field text, and
`generate:client` emits it as JSDoc. Editing that text changes the view hash but not an endpoint's schema pin, so it
never triggers a 409.

`synonyms`, `examples`, `format`, `unit` and `currency` on dimensions and measures travel as field metadata in the
same annotations. Live discovery sends them only to a client that asks with an `X-Hypequery-Client-Features:
field-metadata` request header (both MCP servers do), because `@hypequery/mcp` and `@hypequery/cli` releases from
before 5 November 2026 reject them. Other requests, and `export_client_contract` unless you pass
`field_metadata=True`, get the label and description only. Both views have the same schema pins.

## Keeping clients in sync [#keeping-clients-in-sync]

| Change | What catches it |
| --- | --- |
| Python definitions changed, contract not re-exported | `hypequery export client-contract … --check` in CI |
| Contract re-exported, client not regenerated | `npx hypequery generate:client … --check` in CI |
| Deployed server ahead of a running frontend | The server answers `409 CLIENT_SCHEMA_CHANGED`; rebuild and redeploy the frontend |

Each request carries its endpoint's schema hash in `X-Hypequery-Client-Schema`, so a stale client never receives data in
a shape its types don't describe. When debugging a 409, compare per-endpoint `schemaHash` values: they are identical in
the exported contract and the live discovery route. The document-level `contentHash` (and the generated
`clientContractHash`) always differs between the two, because the build view lists every endpoint and the live view
only those the caller may use. Neither the hooks nor the MCP server automatically adopts a changed contract: the hooks
keep their generated types, and the server re-reads the live contract but refuses one that changed
(`MCP_STALE_CONTRACT`) until you restart it.

A complete runnable version of this setup, with two tenants, a React app and MCP checks, is in
[`examples/client_dashboard`](https://github.com/hypequery/hypequery/tree/main/python/hypequery/examples/client_dashboard).
