Skip to main content
The MCP server (canonic/mcp/server.py) registers 14 tools, 13 of them always and decompose_change unless it is switched off. Each does transport translation only: parse arguments, call the same core service the CLI calls, serialize the result. No resolution, compilation, or execution logic lives in the MCP layer itself.

Session / contract

A client that supports MCP server extensions (SEP-2133) does not need either tool below: canonic advertises its contract version under capabilities.extensions["app.getcanonic/contract"] on connect, on both protocol eras:
A client that declares its own major/minor for a request gets a MAJOR mismatch, or a MINOR above what the server implements, rejected before the tool body runs, with no extra round trip. contract_info and negotiate_contract are the fallback for a client without extension support.

contract_info

Returns the serving contract version this daemon implements, the canonic version, and which project state it serves. Call at session start to confirm compatibility.
project_fingerprint is a hash over the contents of canonic.yaml, contracts/ and semantics/, not their modification times, so the same project checked out twice gives the same value. canonic status prints the same value, which tells whether a running daemon has loaded the files on disk. project_loaded_at is when the daemon last loaded them. project_reload is the reload mode, off or auto. Under off, project_files_changed is true once the files on disk differ in content from the state the daemon serves, so a deployment that was not rolled out shows as drift. A file that was only touched does not count. Under auto the daemon reloads, so it stays false. Both are null for a daemon that was not started from a project directory. Knowledge pages are not part of the fingerprint, they reload on their own.

negotiate_contract(contract_major: int)

Declares the contract-schema major version your client was built against. The daemon accepts iff contract_major == server major version. Otherwise it fails fast with a clear message rather than serving mismatched behavior.

Discovery

get_overview(domain: str | None = None)

The recommended first call: active metrics grouped by domain with plain-language sample questions, so an agent (or a human) can see what’s askable before drilling into list_metrics or query. Pass domain to narrow to one owning-source group.

list_metrics()

Lists all active canonical metrics this project defines, plus a deduplicated catalog of every dimension queryable against them. Each metric’s dimensions list holds canonical names only: look those up in the top-level dimensions catalog for the human-readable label and source. Use canonical names directly in query() calls. Each metric also carries knowledge_refs, the ids of the knowledge pages that define or qualify it, resolved as described under describe_metric, so an agent choosing between related metrics can read the page that tells them apart.

describe_metric(name: str)

Returns grain, dimensions, measures, and freshness for one metric, plus how it is built: kind, components and population_filter, and knowledge_refs, the ids of the knowledge pages that define or qualify it. Read them with read_knowledge_page before choosing between related metrics, for example a broad and a narrow variant of one measure. knowledge_refs lists only pages the caller may see, sorted, and comes from the first of these that applies:
  1. The knowledge_refs declared on the metric binding. Ids that are not visible to the caller are dropped.
  2. The pages that name the metric in their front matter metrics: list.
  3. The definition and caveat pages whose sl_refs overlap the columns, or the dimensions declared on them, that the metric’s population_filter reads. For a composite this includes the filters of its components. The measure itself is not used, because many metrics share one measure and every page touching it would match them all.
A composite metric gets its own list. The pages of its components are not merged in: call describe_metric on a component when you need them. Only global pages are listed. For a composite metric (ratio, weighted_avg) source and measure are null, components names the numerator and denominator metrics (plus numerator_parts when the binding declares them, see Numerator parts), measures lists the measures those components read, and grain is the shared grain when both components sit on one source (empty otherwise).

resolve_metric(name: str, context: str | None = None)

Resolves a metric name or alias to its canonical binding. Returns the binding on success, or a structured error when the name is ambiguous or unresolved.
source and measure are set for a single-source metric and null for a composite. components is null unless the metric is a composite. components.numerator_parts lists the declared parts of the numerator and is null when none are declared. on_zero_denominator is null, zero or error. For a cumulative metric, resolve_metric and describe_metric also return cumulative: its order_by, the trailing window (such as 7 days) or the grain_to_date it restarts at (such as month), period_agg, on_gap and history. It is null for every other kind. This is how an agent tells “revenue over the last 7 days” from “revenue to date”. An offset metric returns offset (base, time_dimension, offset) a derived metric derived (expr, inputs with alias, metric and resolved, on_zero_denominator), and a conversion metric conversion (base_metric, conversion_metric, entity, base_time, conversion_time, window, calculation, constant_properties, attribution), each null for other kinds. A conversion metric offers the dimensions of its base metric.

Query execution

compile_query(query: dict)

Compiles a semantic query to dialect-correct SQL + metadata without executing it. query accepts:
  • metrics (list[str])
  • dimensions (list[str]): canonical name values as returned by describe_metric, not natural-language terms
  • filters (list[str]): SQL WHERE predicates, e.g. ["segment = 'smb'", "status = 'active'"]
  • via (list[str]): routes join paths through specific intermediate sources, required when multiple join paths exist between the metric source and a dimension source
  • time_range (dict | null): a typed range on one time dimension, preferred over a hand-written relative-date filter. {"dimension": "order_date", "last": "90 days"} is the last 90 complete days before the anchor day. last takes days, weeks, months, quarters or years and counts whole units before the current one, so "3 months" on 20 October is July to September. "include_current": true extends the range to the end of the anchor day. {"dimension": "order_date", "start": "2026-01-01", "end": "2026-04-01"} takes ISO dates, end exclusive, either side may be left out. The range compiles to literal dates, and metadata.time_range returns them with the anchor, so quote start and end rather than re-deriving them
  • as_of (ISO datetime | null): the anchor of time_range and the instant finality is judged at. Without it, the anchor is the current UTC time
  • limit (int | null)
On an ambiguous_join_path error, inspect the returned candidates (each has a via list and a human-readable route) and re-issue with that via value. On an unreachable error for a dimension, check candidates for the correct canonical name and re-issue.

query(query: dict)

Same query shape as compile_query, but compiles and executes read-only. Returns rows, with the dimension columns first and then one column per requested metric, named after that metric, plus compiler metadata: resolved bindings, guardrails fired, freshness, project_fingerprint (the project state that produced the answer, the same value contract_info returns) and trust_score (tier plus reasons, see Trust score). A query with a cumulative metric also carries cumulative: the metric, its order_by, the partition_by resolved for this query, on_gap, history, the visibility_filters that only chose which rows are shown, and for a trailing window or a period-to-date total its window, grain_to_date, period_agg and lookback (how far before the first shown day rows were read). A query with a time_range carries time_range: the dimension, the resolved start (inclusive) and end (exclusive), last, include_current and the anchor. A query with an offset metric carries offset, keyed by metric, with base, time_dimension, offset and the shifted_filters that were read in output time, one with a derived metric carries derived, keyed by metric, with its expr and inputs, and one with a conversion metric carries conversion, keyed by metric, with the same fields describe_metric returns. Each entry of guardrails_fired carries the predicate the guardrail applied and knowledge_refs, the ids of the knowledge pages that explain it, which read_knowledge_page returns in full, see Guardrails and knowledge. A query with a composite metric (ratio, weighted_avg) also carries composition: one entry per composite, keyed by the requested metric name, with its kind, the numerator and denominator (each with metric, resolved and the population_filter it counts over), on_zero_denominator and numerator_parts (null unless declared). Under on_zero_denominator: zero a row with a zero denominator is returned as 0 without a warning, so this is where a caller reads that the policy applies. zero_denominator_rows counts how many rows of the returned result were such rows and got the policy’s value (NULL or 0), so a real zero can be told from a substituted one. It is null when nothing was counted: from compile_query, which has no result, and under on_zero_denominator: error. The compiled SQL of a ratio carries one extra column for this count, _canonic_zero_denominator_<metric>, and the SQL of a query that filters on a time dimension carries _canonic_latest_period_<dimension>. query removes both from the result. This is the main path: with --json/over MCP, the payload is identical to canonic query --json.

decompose_change(request: dict)

Attributes the change of one metric between two periods of one time dimension, overall and by member of one or more split dimensions. Use it for “why did X change” questions instead of querying both periods and subtracting: for a ratio, per-member differences do not add up to the total change. request accepts:
  • metric (str): a metric name or alias
  • period ({dimension, base, compare}): a time dimension with a period grain (time_grain, or a granularity of hour, day, week, month, quarter or year) and two distinct values of it, such as {"dimension": "order_month", "base": "2026-08", "compare": "2026-09"}. A bucketed dimension (granularity) takes any form canonic reads as a period, such as 2026-08, 2026-Q3 or 2026-W34, and is filtered by date range. A label dimension (time_grain) takes its labels as they are in the data, such as 2026-43, and is filtered and matched by that text. A label that does not fit the dimension’s time_format is rejected with validation_failed. Without a time_format, a label canonic cannot read is still decomposed, with a warning that its open-period check did not run, see Period labels
  • by (list[str]): split dimensions, at most decompose.max_by. Empty returns the overall effects only. Names work as in query: a canonical name, an alias, or alias.dimension when a name is on several join-reachable sources and fails with ambiguous. Each entry of by in the result is keyed by the name as requested
  • filters, via, context, as_of: as in query, applied to both periods. A filter on the period dimension is rejected with validation_failed
  • top_n (int): members listed per dimension, default decompose.top_n, capped at decompose.max_top_n
  • allow_open_period (bool, default false)
method follows the metric’s kind, and every method is exact: contributions sum to total.delta, and swapping base and compare negates each of them. A member without a denominator in one period has no rate there. Its whole term counts as mix, and presence is base_only or compare_only. Rows are sorted by absolute contribution, then by member with NULL last. Members beyond top_n are merged into one row with member: null and rest: true. residual is what the listed rows miss of the total, 0 up to rounding. A part that is the denominator itself is the constant 1 and has no effect. A member without a denominator in either period has no row in denominator.rows. A ratio whose numerator and denominator read the same source and measure, without numerator_parts, carries a warning to declare them. The warning is left out when the numerator’s population_filter keeps every condition of the denominator’s and adds at least one, since the numerator is then a share of the denominator. To drill into one member, call again with a filter on it and the next dimension in by, for example filters: ["region = 'north'"], by: ["channel"]. For ratio_parts, drill into the part instead: decompose the part metric with that filter. A filter on one member can leave the ratio without a denominator, for example a savings rate filtered to one expense category. Each call runs one statement for the overall values and one per split dimension, through the same path as query, so guardrails, tenancy, population filters and finality apply unchanged. Errors:
  • period_open: the base or the compare period has not ended at the serving clock (or as_of). With allow_open_period: true the decomposition runs, warns, and caps the trust tier at provisional. A finality rule governing the query takes precedence, and with trust.flag_open_periods: false nothing is checked.
  • unsupported_measure: the metric is semi_additive, distinct_count, percentile, opaque or cumulative, or a ratio with a composite component. A ratio with a distinct_count component returns its overall effects, but not a split by member, because one entity can count in several members.
  • decomposition_inconsistent: the declared numerator_parts do not sum to the numerator, within decompose.parts_tolerance.
  • validation_failed: a malformed request, a dimension without a period grain, equal periods, a filter on the period dimension, or more than decompose.max_by split dimensions.
The tool is registered while decompose.enabled is true (the default, see decompose). canonic mcp start --decompose or --no-decompose overrides that for one server. With --json, the payload is identical to canonic decompose --json.

run_sql(sql: str, connection: str | None = None)

Executes a read-only SQL SELECT on a named connection (or the project default). Rejects non-SELECT statements with READ_ONLY_VIOLATION. Use only when no metric/dimension in list_metrics() covers the question: query/compile_query route joins through the resolved join graph and apply guardrails that a hand-written join across fact tables won’t get, and can silently multiply values like revenue.

Knowledge

search_knowledge(query: str, user: str | None = None, limit: int = 5)

Searches the project’s knowledge pages for business context: definitions, caveats, and policies. Returns ranked hits plus any caveats auto-surfaced because a hit references their bound semantic entity. Call this before answering any question about what a metric means or how it’s calculated: this project’s definitions may differ from textbook ones. Returns empty hits when the project has no knowledge pages. Each hit’s score is a rank-fusion value (RRF), not a confidence or relevance percentage. Use hit order, not the raw number, to judge how well a result matches. See canonic knowledge search for the exact formula.

read_knowledge_page(page: str, user: str | None = None)

Retrieves the full content of a knowledge page by its id (page slug). Use after search_knowledge() to read the complete definition, caveat, or policy: the rendered body has live {{ sl:entity.expr }} definitions substituted, plus metadata, drift review flags, staleness warnings, and linked references. The meta block carries last_validated_at, drift_flag (a bound measure’s expr changed, so the prose needs review) and staleness. staleness is null while the page’s references were validated within knowledge.staleness_window_days (default 90), otherwise {"age_days": int | null, "message": str}, with age_days: null for a page that was never validated. Relay the message as a caveat.

Reports

A report (reports/*.yaml) names an ordered sequence of already-existing calls: no new execution semantics, no new authority. run_report is a deterministic loop over query(), optionally attaching a rendered knowledge page per section. See Report schema for the file format.

list_reports(domain: str | None = None)

A directory listing of every committed report: id, title, description, owner, domain. No execution, no per-section detail. Pass domain to narrow to reports declaring a matching domain field. Call this when a user asks for a report by name (e.g. “the customer report”) rather than an ad-hoc question, then call run_report() with the matching id.

run_report(report_id: str, as_of: str | None = None, user: str | None = None)

Runs every section of a committed report through query(), in declared order, and returns an ordered array of section results. Each entry carries the section’s title and either its unmodified QueryResult (with an optional attached narrative, the rendered body of the section’s narrative_from knowledge page) or a structured {code, message, candidates?} error in place of a result. A failing section does not abort the report: the other sections still return normal results, and the call as a whole never raises for a per-section failure. An unknown report_id reuses the existing unresolved error code: there is no dedicated “report not found” code. as_of is an optional ISO-8601 reference point for finality-watermark evaluation, applied to every section that doesn’t set its own.