# Canonry MCP Adapters

Canonry is CLI/API-first. MCP exists to make that same public surface easier to use from MCP clients such as Claude Desktop, Codex, and custom agent shells that prefer a tool catalog over shell commands or raw HTTP.

Config-as-code writes have a read-only preview tool. Call
`canonry_apply_config_preview` first to inspect field, query, competitor,
schedule and notification changes. The preview transaction rolls back before
responding and exposes notification hosts without webhook paths or secrets.
Then call `canonry_apply_config` to commit the reviewed document.

MCP is useful here because many agent clients can discover typed tools, validate arguments, and call them without asking the user to compose `curl` or `canonry ... --format json` invocations. It is not more authoritative than the API or CLI. `canonry-mcp` is an adapter over `createApiClient()` only, so it must not expose capabilities that do not already exist through Canonry's public API/CLI.

New public API/CLI capabilities should get MCP parity by default. If a capability is intentionally not exposed as an MCP tool, classify its OpenAPI operation as `deferred` or `excluded-protocol` in `packages/canonry/src/mcp/openapi-classification.ts` and include the reason there. Credential, bearer-token, browser-session, and other high-risk operations may be deferred, but they should be explicit exceptions rather than silent omissions.

## Universal operations guidance

Connected agents start with initialization guidance and `canonry_help`, not a
skill installation. Call `canonry_help({intent: "status"})`, or use `diagnose`,
`prospecting`, `measurement`, `integrations`, `reports`, `seo`, `operations`,
`start`, or a short task description. Use `start` when the user is new or unsure
what to ask: it routes to the first-run setup read and the `getting-started`
playbook. The default response is a compact route, not the full catalog:

Operation boundaries are visible without executing a tool. REST responses carry
`x-canonry-access: stored|live|write`, CLI help and the machine catalog show the
same access value, and `canonry_help` includes `liveTools` beside core and
toolkit tool names. A live tool still requires approval even when its MCP
annotation says it is read-only.

Use stored-only mode when a workflow must stay within saved evidence. The CLI
accepts `--stored-only` or `CANONRY_STORED_ONLY=1`; the MCP adapter accepts
`--stored-only`, `--scope=stored-only`, `CANONRY_MCP_SCOPE=stored-only`, or the
same stored-only environment variable. MCP stored-only removes live and write
tools from its stdio catalog; CLI stored-only refuses provider operations before
a handler or network request with
`STORED_ONLY_REFUSED` (CLI exit 1), and sends
`x-canonry-stored-only: 1` on permitted API reads. CLI and API clients refuse
live and write operations; stored semantic previews
remain available when they do not call a provider or mutate state.
Writing a requested results export to the operator's chosen output is still a
stored read; stored-only blocks provider work and Canonry state changes. Doctor
is a live diagnostic and is refused as a whole in stored-only mode. Hosted MCP
catalogs remain fixed; stored-only narrows the caller's visible tools locally.
Ordinary server startup, schedulers, autonomous jobs, authentication, and
request accounting remain unchanged; the guard covers this request and client
housekeeping only.

When a newer canonry is published, both stdio and hosted MCP tell the agent without a CLI run: the notice is appended to the initialize instructions (`Update available (UPDATE_AVAILABLE): ...`) and every `canonry_help` result carries `updateAvailable: { code, current, latest, installMethod, upgradeCommand, url }`. The source is the connected server's `/health`: only the versions and install method are taken from it, and the upgrade command is rebuilt locally. Stdio `canonry-mcp` refreshes it hourly and skips it entirely when `CANONRY_DISABLE_UPDATE_CHECK=1`, `DO_NOT_TRACK=1`, or `CI` is set in its environment. Agents should tell the operator and upgrade only with approval; `canonry_doctor` reports the same as `canonry.version.current`.

```json
{
  "guideVersion": "v1",
  "mode": "hosted-fixed-catalog",
  "scope": "read-only",
  "workflow": "status",
  "next": ["canonry_projects_list", "canonry_project_overview"],
  "workflows": ["seo", "operations", "status", "diagnose", "prospecting", "measurement", "integrations", "reports", "start"],
  "approvalBoundary": ["provider reads", "sweeps", "writes"],
  "operationsGuideUrl": "https://github.com/Canonry/canonry/blob/main/docs/agent-operations/v1.md"
}
```

The response also contains short `guidance`, `approvalRule`, and `authority`
fields. It is returned as both JSON text and MCP `structuredContent`. `next`
contains only available stored-evidence tools; it never executes them. Use
listed tool schemas for arguments and keep the server's permission boundary.

Hosted catalogs are fixed and never offer toolkit loading. Progressive stdio
may return `loadToolkits`; load one, await its response, and ask help again.
Eager stdio reports `stdio-fixed-catalog`. Set `includeCatalog: true` for the
existing scope, core-tools, loaded-toolkit, and toolkit-details fields. Default
help no longer includes that large catalog; clients that parsed `toolkits`
should opt in explicitly.

Analysis routes also return `playbooks` and a one-line `playbookRule`. These are
Canonry's analyst playbooks: the Aero skill (`aero`) and its references, the
same files built-in Aero reads, served from the installed package.
`canonry_help({ playbook: "regression-playbook" })` returns one as plain text: a
three-line header (the slug, a note on using it over MCP, and every available
slug), then the playbook. It carries no `structuredContent`, because ChatGPT
shows the model both copies and a playbook is up to 20 KB. The
`agent-operations` slug returns this guide without Aero's built-in-agent preface.
An unknown slug returns `NOT_FOUND` with `availablePlaybooks` in its details.

The [Operations Guide v1](agent-operations/v1.md) is the public source of truth.
`canonry://agent-operations/v1` exposes the same guide as an optional MCP
resource. Resource support, browser access, local CLI installation, and plugins
are not prerequisites: every remote agent can navigate with help alone.
Codex/Claude `SKILL.md` files are generated from that source as optional native
guidance. Guidance never grants permissions; the server enforces authority.

## Protocol compatibility

The adapters use the official TypeScript SDK v2. Hosted endpoints accept both
sessionless `2026-07-28` requests and legacy initialized sessions on the same
URL. Modern clients use `server/discover`, include the protocol version and
client capabilities in each request's `_meta`, and send the matching
`MCP-Protocol-Version`, `Mcp-Method`, and applicable `Mcp-Name` headers.
The SDK rejects malformed modern requests without falling back to legacy.

Legacy clients continue to initialize and send their `Mcp-Session-Id` on later
requests. Sessions bind the exact bearer and current authority; a refreshed
bearer, authority change, or server restart requires initialization again.
Modern requests authenticate independently and need no session ID. Their
internal credentials last through response completion or cancellation and are
then retired. Cleanup failures are logged and retried on subsequent requests,
the periodic sweep, and shutdown. Internal OAuth-derived API keys expire after
one hour even if persistence cleanup fails; legacy sessions must initialize
again at that limit. HTTP cancellation also cancels an in-flight internal API
fetch.

Stdio uses the SDK's `serveStdio` factory with one server per connection. It
accepts modern sessionless messages and legacy initialization while preserving
progressive toolkit loading and the existing CLI flags.

## Install

For a local stdio runtime, install Canonry normally. Agents using an existing
hosted MCP connection do not need this installation:

```bash
npm install -g @canonry/canonry
```

The package exposes one MCP executable:

```bash
canonry-mcp
```

`canonry-mcp` itself stays out of the main CLI to keep stdio clean — telemetry, help text, or stray logs would corrupt the protocol. The main CLI does ship two read/write *helpers* that operate on client config files only:

```bash
canonry mcp install --client claude-desktop
canonry mcp install --client cursor --read-only
canonry mcp config  --client codex            # print snippet for clients without auto-install
```

`install` merges the server entry into the config for Claude Desktop, Claude Code, or Cursor. Before changing an existing file, it backs it up to `<config>.canonry.bak`. An identical entry needs no update. For Codex CLI, `install` prints a TOML snippet. The `config` helper prints the selected client's snippet without changing files. Both helpers accept `--name <server>`, `--read-only`, and `--format json`. Only `install` accepts `--dry-run`.

## Auth

Operational settings support uses the same API permissions: `canonry_telemetry_update`
and `canonry_provider_settings_update` require `settings.write`. The provider tool
accepts model/quota changes and explicit resets for an existing configuration,
including restoring a built-in endpoint or removing an optional Local key. Setting credentials, base URLs and
credential rotation remain in the operator setup flow. Resets require install
administrator authority. `canonry_provider_settings_get` is a stored, credential-free
administrator read of defaults, overrides, capabilities, host-managed settings,
blockers and project usage (including Advanced plans/drafts). Pass its `revision`
as `expectedRevision` when updating to reject stale edits.

`canonry_provider_disconnect` requires explicit operator approval, install
administrator authority and `settings.write`. Inspect the connection first and
show its impact; its `impactRevision` is required as `expectedImpactRevision`.
Stale previews and outstanding work block removal. Disconnect preserves project
selections and historical results and does not revoke the vendor key. Provider
updates, disconnect and reload are excluded from native Aero.
`canonry_provider_test` mirrors `canonry settings provider test <name>` and
`POST /settings/providers/{name}/test`: after explicit operator approval it runs
one saved connection's own healthcheck against the provider (usually one tiny
prompt on the operator's account) and returns `status` `connected`, `failed` or
`not-verified`, with the provider's redacted message and the model checked. A
failed check is a normal result with `ok: false`, not a tool error. The result is
kept as `lastTest` on the connection (`canonry_provider_settings_get`, and
`providerConnections` in `canonry_settings_get`) until its key, endpoint, model,
Vertex project, region or credentials, or CDP endpoint changes, or the
connection is disconnected, so read it before testing again. Request-limit,
batch and pricing edits keep it. It accepts no credentials, changes no
saved settings, requires install administrator authority plus `settings.write`
(project, narrow, viewer and read-only credentials are refused), and is excluded
from native Aero and read-only or stored-only catalogs. A check the server stops
waiting for also stops retrying, and a second test of a connection whose test is
still running returns `OPERATION_IN_PROGRESS`.
`canonry_providers_reload` mirrors `canonry settings reload-providers`: after
explicit operator approval it reloads the connected host's saved provider
credentials, models, quotas and batch settings without restarting the server.
It accepts no credentials and requires install administrator authority plus
`settings.write`; project, narrow, viewer and read-only credentials are refused.
Optional `configPath` and `databasePath` must be supplied together and match the
host's captured install. They never choose an arbitrary file. A pair naming
another install returns `VALIDATION_ERROR` with
`details.reason: install-identity-mismatch`. The response is
credential-free provider status, and unsupported hosts return `NOT_IMPLEMENTED`.
Removing or changing a provider with a submitting, submitted or ended batch,
or an executing sweep that can still submit or cancel one, returns
`OPERATION_IN_PROGRESS` until that work settles; quota-only changes remain
available. This preserves dispatch, polling, result ingestion and cancellation.
Native Aero excludes this operator action.
`canonry_logs_list` requires a host-approved direct bearer key with
instance-wide `logs.read` or wildcard authority. It returns redacted application and HTTP runtime events
with identity/time filters, retention limits, and loss counters. File-backed
hosts retain up to 10,000 events for seven days across restarts; in-memory hosts
report process retention. This is separate from durable audit history.
Entries include `context.provider`, the answer engine a sweep failure came from.
The tool asks for it with the `x-canonry-log-fields: provider` request header;
the API leaves it out for callers that do not ask, so an older `canonry-mcp`
keeps reading pages. The tool drops context keys it does not know instead of
rejecting the page.
See the [operations guide](agent-operations/v1.md#agent-operations) for the
operator allowlist and credential boundary.

`canonry-mcp` inherits the normal local config at `~/.canonry/config.yaml` through `createApiClient()`.

For a local server, use the same config created by `canonry init` and run `canonry serve`. For a remote API, set `apiUrl` and `apiKey` in `~/.canonry/config.yaml`. The stdio adapter uses that API key; hosted HTTP clients can instead use the instance's OAuth authorization flow.

### Research access

Research is an explicit `research.run` capability shared by REST, CLI, the
dashboard, and MCP. It spends provider quota and saves isolated evidence; it
does not grant tracked-query changes, sweeps, ICP discovery, settings writes,
key creation, or saving/applying query patterns. A direct research run submits
one provider/model/location context. A reviewed batch submits independently
reviewed destinations under one retry key. Both send exact final query strings:
the client expands any pattern before submission, and selecting an Advanced
market or Property only records the destination—it never rewrites queries or
automatically fans out a group.

An administrator can create a project-bound agent credential:

```sh
canonry key create --name research-agent --project demo --scope read --scope research.run --format json
```

Configure that key in the normal Canonry client config. Then use
`canonry research run demo "Which platform fits an agency?" --provider openai --format json`,
`canonry research list demo --format json`, and `canonry research show demo <run-id> --format json`.
REST uses `POST /api/v1/projects/demo/research/runs` and the matching list/detail
GET routes. Research history also returns safe provider/model choices and
`access: { canRun, dailyRunLimit }`, so agents can discover their permission
without trial runs. Model choices use the configured provider's cached catalog
or bundled defaults; listing history never triggers or waits for live model
discovery, including on a cold or expired cache.

For hosted OAuth, request `read research.run` (optionally `offline_access`) and
approve the research permission. Viewer accounts also require the deployment's
`research.allowViewers` opt-in. Re-authorize existing connections with the new
scope; a token approved for `read` remains read-only, including for admins.
Current account authority is rechecked on every request.
Each HTTP session is bound to its exact bearer token and effective scopes and
project boundary, not just the signed-in account. A replacement/refreshed token
or changed authority must initialize a new session; reuse returns HTTP 404.
Revoked or expired tokens remain rejected by authentication.

Use `/api/v1/mcp` or `/api/v1/mcp/x/discovery`. Authorized catalogs include
`canonry_research_run_start`, `canonry_research_batch_start`,
`canonry_research_runs_list`, and `canonry_research_run_get`; stdio exposes
them after loading `discovery` or with `--eager`. Narrow research credentials do
not expose unrelated mutation tools, including pattern save/apply tools.
Explicit `--read-only` and `/readonly` always remove research creation.

Limited research credentials and viewer sessions share the deployment's
per-project UTC daily cap (default 20). New keys and MCP reconnects do not reset
the cap. Idempotent retries return the existing receipt. MCP runs retain the
initiating account, and API/CLI key runs retain the key identity. Root/admin
full-authority research keeps its existing uncapped behavior; an admin OAuth
grant containing only `research.run` still uses the limited budget.

## Client Config

Claude Desktop:

```json
{
  "mcpServers": {
    "canonry": {
      "command": "canonry-mcp",
      "args": []
    }
  }
}
```

Read-only mode:

```json
{
  "mcpServers": {
    "canonry": {
      "command": "canonry-mcp",
      "args": ["--read-only"]
    }
  }
}
```

Codex-style TOML:

```toml
[mcp_servers.canonry]
command = "canonry-mcp"
args = []
```

## Hosted connections

### Connect from ChatGPT or Claude Desktop

Open **Agent setup** in your hosted Canonry dashboard and copy the MCP URL.
Add it as a remote connector in your client's settings, choose OAuth, and
complete Canonry's sign-in and permission approval. Use your named Canonry
account; a dashboard password or API key is not an account login. Your client
handles registration and tokens. You do not need a local Canonry installation,
plugin, Node.js, or an API key pasted into chat.

After connecting, use the page's verification prompt to list accessible
projects through stored reads. An empty list can still verify the connection.
The server's readiness label confirms configuration prerequisites, not that
the client has authorized or can reach the service. In Claude, set the OAuth
client option to **Register automatically**; Canonry does not accept Claude's
published identity. On Claude Team and Enterprise plans, an Owner adds custom
connectors before members connect.

### Connect with the Canonry plugin

When the operator registered the instance with the shared MCP gateway, **Agent
setup** leads with the Canonry plugin for the ChatGPT desktop app and Codex: add
the Canonry marketplace, install `canonry-remote`, enter the workspace the page
shows, then sign in with the instance's own Canonry account. The plugin reads
stored results only. Claude Code installs the same plugin with `claude plugin
marketplace add Canonry/canonry` and `claude plugin install
canonry-remote@canonry`; the page does not show those commands yet. Claude on
the web, desktop and mobile uses the same gateway as a custom connector: add
`https://mcp.canonry.ai/mcp`, choose **Use your own OAuth client**, enter
`canonry-claude` and leave the secret blank. Claude keeps one connector per URL,
so to connect a second workspace add it at its own address,
`https://mcp.canonry.ai/mcp/<workspace>`; its sign-in asks for that workspace
only. Direct connection stays available under **Connect directly** for Claude and
other MCP clients.

The operator sets this once per instance, after registering the instance with
the gateway ([gateway runbook](../apps/mcp-gateway/README.md)):

```yaml
mcpGateway:
  url: https://mcp.canonry.ai/mcp
  # workspace: tenant-id   # optional; defaults to the public URL's host
  # clientId: dcr_...      # optional; the gateway's client on this instance
```

`/health`, `/api/v1/status`, `canonry status` and `canonry_status` then report
`mcp.hosted.plugin` (`gatewayUrl`, `workspace`) while hosted sign-in is ready.
The page never shows plugin steps for an instance without this setting.

The gateway registers its client on the instance through open registration, so
the instance's consent page would warn that the client chose its own name.
`clientId` names that client as the operator's: its consent page then shows no
warning, as long as every redirect it registered is on the gateway's origin.
People still approve access on the instance.

For the host operator:

- Hosted tenants run `canonry serve` with a reachable HTTPS `publicUrl` and at
  least one named account. Keep each customer's instance isolated.
- The public URL, reverse proxy and configured base path must agree. For a
  `/canonry/` mount, MCP is at `/canonry/api/v1/mcp` and browser sign-in and
  consent are at `/canonry/oauth/authorize`. Cookies stay scoped to `/canonry/`.
  Cached `/oauth/authorize` URLs redirect to that canonical path.
  Set `publicUrl` to include `/canonry/`, set `basePath` to `/canonry/`, and
  preserve that prefix when forwarding. A mismatched public path makes hosted
  setup unavailable.
- Forward the root `/.well-known/*` discovery paths and `/oauth/*` token,
  registration and revocation paths as well as the instance's base path.
- `/health` and `/api/v1/status` expose the same `mcp.hosted` readiness and
  canonical URL. `canonry status --all --format json` and `canonry_status`
  expose it too. Missing public URL, HTTPS, accounts or OAuth routes produces
  an unavailable reason. Health never starts an MCP session or calls a provider.
- OAuth sessions and MCP connections belong to this running instance. A
  server restart requires legacy clients to initialize again; this is not an autoscaling,
  shared-session deployment. The separate `apps/api` REST service does not
  serve remote MCP.

Connect to `/api/v1/mcp` on the instance for the entire API tool catalog, available immediately: all toolkits allowed by the endpoint and credential. Use `/api/v1/mcp/readonly` to force stored-evidence tools even with a write-capable credential. Every `/readonly` segment also enforces stored-only policy in its API client: live provider reads, research execution and mutations are refused before the inner HTTP request, independently of tool annotations. A read-only credential retains the existing read-only catalog on the default endpoint.

The default connection includes visibility reports, Property rankings, stored query results and competitors, changes, data quality, and all integration and setup tools. Listing tools does not execute them or grant new permissions; each call still uses the caller’s existing authority. The full catalog includes provider-spending and write operations, subject to the approval and access rules below.

The hosted inventory has one optional Markdown resource, `canonry://agent-operations/v1`, and no prompts or resource templates. Tools publish explicit read-only, idempotency, destructive and open-world annotations; OAuth discovery and the HTTP bearer challenge define their authorization boundary.

Specialist connections remain at `/api/v1/mcp/x/<toolkit>` and `/api/v1/mcp/x/<toolkit>/readonly`, exposing core plus that toolkit. Hosted catalogs are fixed by the endpoint and current credential and do not offer `canonry_load_toolkit`. After upgrading the server, refresh or re-import the connector's tools and reconnect so the client sees the expanded catalog.

## Tool Surface

`canonry_seo_trends` requires a saved `profileId` and accepts `days` (30, 90 or
180, default 180), ending on the latest observation. It reads comparable SEO refreshes with exact observation
dates, source scope, nullable readings and a server-calculated change basis.
Domain metrics are provider estimates. Market counts track non-brand query
assignments across matching markets and search settings. Each point's `runId`
opens its saved evidence. For ranked-keywords profiles, `keyword` selects one
search, and the response includes suggested `rankedKeywords` and its organic
positions. A missing position indicates no usable rank in the saved sample.
The tool is available to stored-only readers.

The `seo` toolkit exposes provider-neutral saved keyword metrics, ranked keywords, organic competitors (`canonry_seo_competitors`), keyword gaps (`canonry_seo_keyword_gaps`), domain intelligence, market rankings (the site's Google position for its tracked queries by market, with `canonry_seo_market_summary` counting them by outcome), profile management and explicit refreshes. Start with `canonry_seo_context` and `canonry_seo_overview`. A refresh uses `canonry_seo_refresh_intent` followed by `canonry_seo_sync` with an idempotency key. Preparation has no provider side effects; submission requires `seo.run`. Profile writes require `seo.write`. Host financial controls stay internal, and operator receipt tools require separate host authority. Competitor discovery and gaps compare whole domains in project scope for Simple and Advanced portfolios. Discovery does not pin rivals; gap reads preserve explicit comparison domains and locale. `kind=shared` includes outranked searches, `missing` means no target rank in the source comparison, and `outranked` means the rival ranks higher. `rankGap` is target minus rival position, null without both. Both research tools accept `sort` to order all matching saved rows before pagination; a leading minus descends, missing values stay last, and omission retains source order. Sorting is read-only tuning; keep run ID, filters and sort fixed across pages. See [SEO data](seo-data.md).

`canonry_research_run_start` is for one direct context. It accepts the final
editable query text and optional saved destination/provenance; it does not
expand a pattern or a group.

`canonry_research_batch_start` accepts reviewed queries across explicit markets, Properties, or configured locations.
Its request contains a required `idempotencyKey` and at most 20 `runs`, with at most 50 total queries.
Each run specifies final query text, provider, model, and location (a configured object or `null`).
Market and Property scopes also require `expectedPlanRevision`.
If a saved pattern is used, the caller substitutes it client-side and submits
the resulting exact query text plus optional template provenance. A selected
scope records where the result belongs; it does not substitute text or create
additional destinations.
The API accepts all runs together or accepts none. Individual saved runs then complete independently.
An unchanged retry returns the same runs. A changed request with the same key conflicts.
This paid operation remains write-only and never changes tracking.
The matching CLI is `canonry research batch <project> <json-file|-> [--wait] --format json|jsonl`.
The browser offers the same [reviewed Research workflow](query-visibility.md#repeat-research-across-destinations).

`canonry_discover_harvest` ranks search queries from saved discovery probes.
It can send candidate and tracked query text to Gemini to check for paraphrases.
Get approval before calling it. Over MCP, use a bearer key with `*` scope and
access to the project. The hosted OAuth grants do not authorize harvest. A
signed-in administrator can also use the REST route. Stored-only connections
exclude harvest. Use `canonry_discover_session_get` for saved
probes and `canonry_discover_promote_preview` to review promotion candidates.

The catalog includes API tools, `canonry_help`, and [deprecated Agent Readiness aliases](#agent-readiness-tools). Progressive stdio also offers `canonry_load_toolkit`. The API tools cover stored instance status (`canonry_status`), projects, project-overview and search composites, project and instance-wide change history (`canonry_project_history`, `canonry_history_global`), citation/mention trend analytics (`canonry_analytics_metrics`), the stored figures a dashboard tab's trend card leads with (`canonry_trends`: index coverage, the Agent Readiness score and Common Crawl backlinks, each with its readings and its change since the window's first reading), cited-source rankings (`canonry_analytics_sources`: the full ranked + per-provider + classified cited-domain surface), aggregated per-query mention/citation stats with sample size (`canonry_visibility_stats`: confidence-aware proportions, optional per-provider), statistically honest month-over-month AEO comparison (`canonry_visibility_compare`: share-of-voice-led, Wilson intervals, within-noise verdict, drift-aware), config apply and preview, versioned Target measurement plans (`canonry_measurement_plan_get`, `_versions`, `_version_get`, `_compile_preview`, `_diff_preview`, `_publish`, `_segment_retire`), one Property's paged evidence (`canonry_measurement_property_evidence`: `shape=sources` for one row per cited URL, `shape=answers` for one row per measured answer with its cited URLs nested, which is the only shape that shows the answers a Property was not cited in, `shape=other-queries` for answers to queries assigned only to other Properties that still cited its pages, kept out of its rates), runs, snapshots, insights, health, query generation and replacement, legacy keyword aliases, competitor add/remove, stored evidence suggestions (`canonry_competitors_suggest`), curated competitor aliases (`canonry_competitors_aliases_set`) and answer-derived auto aliases (`canonry_competitors_auto_aliases_detect` dry run, `canonry_competitors_auto_aliases_apply`, `canonry_competitors_aliases_block` / `_unblock`), schedules, settings, safe key identity, telemetry status, and supported notification event names, GSC reads plus the sitemap-submission write tool (`canonry_gsc_sitemaps_submit`, explicit URLs or `indexes` / `all-files` modes; all-files omits parent indexes), stored Bing index coverage (`canonry_bing_coverage` in the `bing` toolkit), GA reads including GA4's overview for a window against the period before it (`canonry_ga_overview`), per-day AI referral sessions (`canonry_ga_ai_referral_daily`), native-channel/lead/search-demand measurement analysis, and GA4's Search Console landing-page report (`canonry_ga_search_landing_pages`: stored 7/28/90/180-day snapshots with GA4's own Total), GBP local-AEO reads (incl. `canonry_gbp_attributes`: owner-set Business Profile attributes across categories, `canonry_gbp_places`: the Places rendered-listing cross-reference, and `canonry_gbp_reviews`: stored reviews with each location's review access, rating, and webhook alert state), live GBP reads for one selected location (`canonry_gbp_local_posts`, `canonry_gbp_local_post`, `canonry_gbp_reviews_live`) and the saved post-attempt read (`canonry_gbp_local_post_attempt`; publishing itself is not an MCP tool), Google Ads and GTM conversion evidence plus stored contract integrity, server-side traffic analytics (`canonry_traffic_analytics`: complete 7/14/30/90-day stored totals and breakdowns), AI visitor journeys (`canonry_journeys_summary`, `canonry_journeys_list`, `canonry_journey_get`), traffic ingestion (Cloud Run / WordPress / Vercel connect/sync + async backfill + crawler/AI-referral rollup reads, and `canonry_traffic_declare_gap` to record a skipped span that cannot be recovered), OpenAI ads live account/integrity state, geo target lookup, conversion pixels/event settings, stored ads snapshot-provenance/configuration diagnostics plus historical campaign activity (never a provider serving or eligibility verdict), the bounded live provider read with a stored-snapshot delta (`canonry_ads_live_delivery`), paid-surface snapshots/rollups, sync, durable operation receipts, unresolved-receipt listing, safe provider-state reconciliation, exact-executor activation recovery, image upload, paused campaign/ad-group/ad create/update/pause lifecycle, and exact-grant campaign-tree activation, the doctor health-check, Agent Readiness audit scans and canonical graph semantics (`canonry_agent_readiness_overview`, exact page audit evidence via `canonry_agent_readiness_page_audit`, focused subgraphs, directed shortest paths, cursor-paged scan changes, page inventory, structure, links, neighbors, and opt-in dead links), run trigger/cancel, schedule updates, insight dismiss, content gap/target/source analysis, the winnabilityClass gate (`canonry_content_map`: per-domain cited-surface classifications) and structured brief synthesis (`canonry_content_brief`, gated to ownable targets), source-aware backlinks (`canonry_backlinks_domains` reads either Common Crawl or Bing Webmaster via `source`; `canonry_backlinks_sources` reports per-source availability), durable Aero memory (list/set/forget), agent transcript clear, agent webhook attach/detach, the tracked-basket discovery pipeline, and saved Research (`canonry_research_run_start`, `canonry_research_batch_start`, `canonry_research_runs_list`, `canonry_research_run_get`) that return model answers and sources without adding a query to tracking.

### Agent Readiness tools

Agent Readiness audit scans a site's pages and internal links and scores how ready
each page is for AI agents and answer engines. Its tools are in the
`monitoring` toolkit and call `/api/v1/projects/{name}/agent-readiness/…`.

| Tool | Title | What it does |
| --- | --- | --- |
| `canonry_agent_readiness_score` | Get Agent Readiness score | Agent Readiness score, factor scorecard, fixes, and delta vs the previous scan |
| `canonry_agent_readiness_page_scores` | List Agent Readiness page scores | Per-page scores of audited pages, worst first |
| `canonry_agent_readiness_trend` | Get Agent Readiness score trend | Score history across past scans |
| `canonry_agent_readiness_overview` | Get Agent Readiness overview | Scan summary: root, completeness, counts, budgets, termination, dead-link check state |
| `canonry_agent_readiness_pages` | List Agent Readiness crawl pages | Cursor-paged crawl inventory with fetch, indexability, and audit state |
| `canonry_agent_readiness_page_audit` | Get Agent Readiness page audit | One page's exact factor scores, findings, and recommendations |
| `canonry_agent_readiness_issues` | List stored Agent Readiness issues | Stored findings grouped by issue, with affected-page counts and example URLs |
| `canonry_agent_readiness_issue_pages` | Read pages affected by a saved Agent Readiness issue | The affected URLs for one issue |
| `canonry_agent_readiness_structure` | List Agent Readiness site structure | One level of the site's path hierarchy |
| `canonry_agent_readiness_links` | List Agent Readiness internal links | Cursor-paged internal links |
| `canonry_agent_readiness_link_neighbors` | Get Agent Readiness page link neighbors | Inbound and outbound links of one page |
| `canonry_agent_readiness_dead_links` | List Agent Readiness dead links | Dead-link check state and findings |
| `canonry_agent_readiness_subgraph` | Inspect focused Agent Readiness subgraph | A focused neighborhood of the link graph |
| `canonry_agent_readiness_path` | Find shortest Agent Readiness link path | The shortest followable-link path to a page |
| `canonry_agent_readiness_changes` | Compare Agent Readiness audit scans | Page and link changes between two complete scans |
| `canonry_agent_readiness_run` | Run Agent Readiness audit scan | Start an Agent Readiness audit scan (write) |

`canonry_agent_readiness_issues` and `canonry_agent_readiness_issue_pages` read retained
findings without crawling or calling a provider. The issue list
includes passing-score findings, affected-page counts, example URLs and source
coverage; the second tool pages through one issue's affected URLs. Pin its
`runId` from the list and retain continuation metadata. Missing cross-page
evidence in an older scan and partial crawl coverage cannot establish a clean
site. Recommendations and advisory findings require review before edits.

The tools' earlier names still work as deprecated aliases with the same input,
output, access, and toolkit as the canonical tool. `canonry_help` and Aero list
only the canonical names, and the aliases will be removed only in a future
major version.

| Deprecated name | Canonical tool |
| --- | --- |
| `canonry_technical_aeo_score` | `canonry_agent_readiness_score` |
| `canonry_technical_aeo_pages` | `canonry_agent_readiness_page_scores` |
| `canonry_technical_aeo_trend` | `canonry_agent_readiness_trend` |
| `canonry_site_health_overview`, `canonry_technical_aeo_crawl` | `canonry_agent_readiness_overview` |
| `canonry_technical_aeo_crawl_pages` | `canonry_agent_readiness_pages` |
| `canonry_site_health_page_audit` | `canonry_agent_readiness_page_audit` |
| `canonry_site_health_issues` | `canonry_agent_readiness_issues` |
| `canonry_site_health_issue_pages` | `canonry_agent_readiness_issue_pages` |
| `canonry_technical_aeo_structure` | `canonry_agent_readiness_structure` |
| `canonry_technical_aeo_internal_links` | `canonry_agent_readiness_links` |
| `canonry_technical_aeo_link_neighbors` | `canonry_agent_readiness_link_neighbors` |
| `canonry_technical_aeo_dead_links` | `canonry_agent_readiness_dead_links` |
| `canonry_site_health_subgraph` | `canonry_agent_readiness_subgraph` |
| `canonry_site_health_path` | `canonry_agent_readiness_path` |
| `canonry_site_health_changes` | `canonry_agent_readiness_changes` |
| `canonry_technical_aeo_run` | `canonry_agent_readiness_run` |

`canonry_project_history` and `canonry_history_global` share `actionPrefix`,
`excludeEntityTypes`, `until`, and `entityId` investigation filters. `action`
still matches exactly. Prefixes treat percent and underscore literally; excluded
entity types are removed before paging. `since` and `until` are inclusive ISO
timestamps, normalized to UTC; invalid timestamps now return a validation error.
`actor: "api"` includes legacy API, API-key, and user actors. Notification secrets
remain redacted and internal telemetry requires operator authority.

`canonry_runs_list` accepts `kind`, `excludeKind`, `excludeKinds`, `status`, and `since`
together. Exclusions apply before `limit`; `excludeKinds: ["bing-inspect", "traffic-sync"]`
keeps meaningful jobs and failed sweeps from being displaced by single-URL
inspections or frequent traffic pulls. The CLI equivalent is
`canonry runs <project> --exclude-kinds bing-inspect,traffic-sync --limit 5 --format json`.
The `since` bound is inclusive and accepts ISO timestamps with offsets. Omitted
`since` reads all dates, and omitted `limit` returns every matching run.
`canonry run list <project>` is the CLI alias; traffic runs include their stored
`sourceId` when available.
Repeat `--exclude-kinds` or supply a comma list. The API accepts repeated or
comma-separated `excludeKinds`; the existing single-value `excludeKind` remains supported.
Project run lists still include probe runs; global `GET /runs` excludes them by default.

Advanced Measurement v2 spans monitoring and setup. Monitoring provides the stored portfolio summary, Property queries, results, and competitors, and change and data-quality reads. Setup provides setup state, the scoped overview and Property evidence, the draft plus its paginated Targets, assignments and groups, and saved query sets/templates. Seven write tools expose one discriminated `canonry_measurement_draft_action` surface, plan deactivation, and query-set/template mutations. The draft-action input is `{ project, operation }`; `operation` is a nested discriminated union whose twenty-five branches correlate each `action` with its request and header fields. Reads return stored state and never start provider work. Draft previews also never start provider work or mutate state, but they remain branches of the write-classified draft-action tool and are therefore absent from a read-only MCP catalog.

The matching CLI bridge is `canonry measurement-plan advanced <project> <operation> [<json|->] --format json|jsonl`. It accepts a JSON file or stdin; `--format json` returns the API response unchanged. Read operations take their endpoint query object; structured writes use an envelope so request body and required headers/IDs stay explicit. `draft-action` takes the same typed `{ action, request?, etag?, idempotencyKey? }` object as its MCP `operation` field; deactivation takes `{ request, idempotencyKey }`; query-set/template get, upsert, delete, and apply take their ID plus `request`/`idempotencyKey` where required. The operations are `setup`, `overview`, `portfolio-summary`, `property-questions`, `question-result`, `property-competitors`, `changes`, `data-quality`, `draft`, `draft-targets`, `draft-assignments`, `draft-groups`, `draft-action`, `deactivate`, and query-set/template list, get, upsert, delete, and apply variants. The paged draft collections and query-set/template lists stream a metadata header then records with `--format jsonl`.

For best/worst Property mention performance, use `canonry_measurement_portfolio_summary`.
It defaults to `queryClass=non-brand`; name that class in the report. Request branded
results separately, or `all` only when a combined comparison is intended.
`mentionRanking.strongest` and `.weakest` rank available mention rates before the
list limit, independently of citation availability. `eligiblePropertyCount` is
the ranked population. Raw reads list every excluded Property with its reason;
compact reads page exclusions with `list: excluded-mentions` and preserve
`excludedTotal`. `truncated` describes the two ranked lists. Keep numerator/denominator with each rate, plus any `unattributed`
(mention) or `unchecked` (citation) count of saved answers left out of both
sides; rates can tie and the stable label/key tie-break does not establish a
unique winner. These are
descriptive rates from each Property's assigned questions, not matched-query or
confidence-adjusted comparisons. An unavailable portfolio aggregate does not
invalidate known Property rates. Flag ambiguous Properties separately; never
substitute citation ranking without saying the metric changed. Aggregate metrics,
the existing combined-signal `weakestProperties`, and overview pagination retain
their existing semantics.

`canonry_measurement_portfolio_summary` defaults to `compact: true`; HTTP reads
retain the raw shape unless compact is requested. Compact pages contain whole
rows under an 18,000-character formatted budget. `nextCursor` advances only
`pageList`, default `weakest-properties`. Other first-page lists are bounded
summaries and later pages omit their row bodies. To enumerate a different list,
set `list` to `strongest-mentions`, `weakest-mentions`, `excluded-mentions`,
`markets`, `observed-names` or `cited-domains`. Selected-list mode omits sibling
row lists while retaining complete totals and `detailsOmitted`. Keep list and
filters unchanged across cursors; page size may change. Without `limit`, pages
auto-size up to 50 rows; the byte budget may return fewer. A null cursor completes
only `pageList`. `weakestMarkets` supplies the bounded full-rate weakest metro
headline; compact rows omit per-Property answer evidence and tie-cohort details,
available on drill-down tools or a raw `compact: false` read.
`canonry_measurement_changes` defaults `queryClass` to `non-brand` and caps
`limit` at 20. `canonry_measurement_overview`,
`canonry_measurement_property_competitors` and
`canonry_measurement_property_evidence` read `non-brand` when `queryClass` is
omitted; read branded as a separate call, and treat `all` as both classes
pooled into one rate. The overview and changes HTTP routes default to
`non-brand` too. `canonry_measurement_report` sends a class only when one is
named: a schema v2 revision then reads `non-brand`, and a schema v1 revision,
which records no class, reads every answer and echoes `queryClass: null`.
`canonry_measurement_overview` reads a market with `scope: market` and
`marketKey` (a market's id from `canonry_visibility_report` `scopeOptions`):
only that market's queries, as the dashboard counts it. `scope: group` reads
every query of the group's Properties, so a group figure is never a market's
figure even when the two share a name. `canonry_analytics_sources` and `canonry_competitor_landscape` read the
latest sweep (`runId=latest`) when `queryClass` is `branded` or `non-brand` and
neither `runId` nor `window` is given.
Competitor reads with `answers: not-mentioned` preserve evidence counts but
withhold competitive shares with reason `answer-selection`, including model
groups. A population selected by the project's mention cannot measure its
unconditioned competitive share.
Historical competitor percentages require explicit `queryClass: "non-brand"`
for a competitive comparison, or `"branded"` for brand recall. Omitting the
class or requesting `all` returns pooled counts with null shares.

`canonry_measurement_overview` ranks one revision-pinned run snapshot only; it does not infer a trend or compare across revisions. Its optional `sort` is `label-asc` (default), `label-desc`, `citationCoverage-asc`, `citationCoverage-desc`, `mentionCoverage-asc`, or `mentionCoverage-desc`. For coverage sorts, unavailable rows are always the first bucket, then available rates follow the selected direction. Its cursor is sort-aware and pins later pages to the active revision, displayed run, evidence snapshot, and filters even if a newer run completes: reuse it unchanged with the same sort and filters or the API rejects it. Evidence appended to a named running run also invalidates the cursor instead of silently reordering later pages. Legacy label cursors work only when `sort` is omitted; an explicit sort needs a new sort-bound cursor.

Ordinary read-only API keys intentionally may read unpublished setup and draft state for their bound project; treat those callers as authorized to see that portfolio and competitor structure. Embed mode is narrower: its explicit safe-read allowlist denies draft paths, including when a self-hosted embed uses a project-scoped key.

For an existing-draft mutation, pass the ETag returned by `canonry_measurement_draft_get` and a fresh `idempotencyKey`; reuse that key only when retrying the identical request. Omitting the ETag preserves the API's actionable `MEASUREMENT_DRAFT_ETAG_REQUIRED` response (HTTP 428), while a stale ETag preserves `MEASUREMENT_DRAFT_ETAG_STALE` (HTTP 412). Starting a draft needs an idempotency key but no ETag. Compile/diff previews need neither header. Plan deactivation and query-template apply need an idempotency key but no draft ETag. Query-set and query-template PUT/DELETE operations use their naturally idempotent HTTP methods.

`canonry_apply_config` accepts one config-as-code project document per call. For multi-document YAML or multiple project files, agents should call the tool once per project document. `canonry_queries_generate` returns suggestions only; persist accepted suggestions with `canonry_queries_add` or replace the tracked set with `canonry_queries_replace`. The `canonry_keywords_*` tools remain as legacy aliases over the same query store for older clients.

`canonry_queries_list` rows carry `queryClass`: `branded`, `non-brand`, or `null` when no single class exists (the project has no usable brand name, or its active measurement plan holds no single class for the query). `canonry_queries_add` returns `{ ok, queryClasses }`, where `queryClasses` lists each requested query with the class the server gave it. A row or entry with no `queryClass` key comes from a server older than the field: the class was not reported, which is not `null`. The server resolves the class; an agent reads it and never infers one from the query text. `canonry query list` and `canonry query add` show the same values.

`canonry_snapshot` (discovery toolkit) generates a prospect report without creating
a project. It calls `POST /api/v1/snapshot` and spends provider quota, so it is
unavailable to read-only connections. `providers: ["gemini"]` selects configured
providers; `providerMode: "all" | "api" | "browser"` filters by transport.
Omitting both uses all configured providers. Both selectors also constrain
analysis calls. Browser-only selection requires manual `queries` and uses
deterministic analysis. Unknown providers, mode conflicts, and empty selections
fail before site fetching or provider work.

Start with `canonry_help({intent: "prospect snapshot"})`. Help offers stored
provider settings in `next` and, on progressive stdio, the discovery toolkit to
load. After loading, `actions` includes `canonry_snapshot` when this connection
permits it. Fixed catalogs offer the action immediately when available. Help
starts no provider work; execution requires approval for the selected work.

```bash
canonry snapshot "Acme" --domain acme.example --provider gemini --format json
canonry snapshot "Acme" --domain acme.example --provider-mode api --format json
canonry snapshot "Acme" --domain acme.example --provider-mode browser --queries "best widget suppliers"
```

Repeat `--provider` to select several providers. The CLI and MCP accept the same
selection as the API; a named provider must match an explicitly selected mode.

Deferred from v1: Aero ask SSE, OAuth callbacks, raw screenshots, project delete, broad admin/provider writes, Google/Bing/GA connect/sync/inspect/indexing writes, WordPress writes, CDP screenshot, generic notifications, backlinks, raw OpenAPI, and raw HTTP escape hatches.

Some write tools compose existing API calls rather than using a native atomic endpoint. The agent webhook attach/detach tools are best-effort under concurrent calls until the public API grows narrower attach/detach operations for that domain.

`canonry_project_upsert` and `canonry_apply_config` use PUT semantics: fields omitted from the request are reset to their defaults, with one `canonry_apply_config` exception: a spec carrying neither `queries` nor `keywords` leaves the tracked-query basket unchanged. To clear the basket, pass an explicit `queries: []`; omitting the field never clears it. Pass the full intended project shape, including `providerModels` when retaining project model overrides. An empty map inherits instance settings. `providerDispatchModes` (provider → `sync`/`batch`, read by scheduled sweeps) is the second exception on both tools: omitted keeps the stored preference, `{}` clears it. `qualifiedAliases` (the aliases Simple sentiment treats as the brand's own names) is the third: omitted keeps the stored list, minus names that no longer qualify (a removed alias, a spelling of the display name, or a competitor's name), and `[]` clears it. Curated competitor aliases are the fourth, on `canonry_apply_config`: a competitor given as a plain domain keeps its stored aliases, `{ domain, aliases }` sets them exactly, and `aliases: []` clears them. On both tools, a project identity (display name, aliases, domains) that claims a competitor's alias drops that alias, and the drop is audited (`droppedCompetitorAliases`); a new competitor whose name overlaps another competitor's alias (one brand key contains the other, so the alias "Tune" claims `tunespoke.example`) fails the apply until that alias is removed, and so does a new competitor that is the project's own site. `siteAuditMaxPages` (the Agent Readiness page budget for scans that set none, 1 to 50,000) is the fifth: omitted keeps the stored budget, and `null` means the full site. `siteAuditDomains` (owned domains every Agent Readiness scan covers besides the main domain) follows it: omitted keeps the stored list, minus domains no longer owned, and `[]` means the main domain only. `competitorAutoAliases` (`off`, `preview` or `apply`: what the unattended answer-derived competitor alias pass does after a sweep, a competitor add, an unblock or a market pin write that changes the pins) is the sixth: omitted keeps the stored mode, and a new project starts in `preview`. `canonry_competitors_auto_aliases_apply` stores one detection pass in every mode. `canonry_apply_config` accepts one project document per call; loop on the client side for multi-project configs.

`canonry_agent_readiness_run` without `maxPages` uses the project's saved `siteAuditMaxPages`, else the full site (up to 50,000 pages), the same budget scheduled scans use. Without `sites` it covers the main domain plus the saved `siteAuditDomains`; `sites` names owned domains for this scan instead (at most 20 besides the main domain), and `[]` scans the main domain only. `canonry_agent_readiness_score` claims no change when the previous scan scored other sites (`deltaUnavailableReason: sites-changed`). `canonry_agent_readiness_pages`, `canonry_agent_readiness_structure`, `canonry_agent_readiness_issues` and `canonry_agent_readiness_issue_pages` take `site` to read one site the scan covered; the overview lists them in `sites`.

`canonry_run_preview` reads the next default full manual sweep without writes or provider calls: query classes, Advanced assignments and published revision, engines/models, locations, planned answer slots, runnable requests, and provider holds. It does not preview scoped, forced, or all-location overrides and reserves no work. A read-only project key can preview only its own project.

`canonry_project_setup` reads one project's first-run setup from stored state (`GET /projects/{name}/setup`, the same object as `cnry project setup <project> --format json`): the Agent Readiness audit scan and the AI Visibility check, each the latest non-probe run of its kind (`not_started` when there is none) with stored progress, result or error, and the server's `nextAction`. The AI Visibility blocker is the run preview's readiness, for Simple and Advanced projects, and its result keeps non-brand and branded query counts apart, as the run detail does. It makes no provider calls or crawls and grants nothing: the scan and the check each need their own approval.

`canonry_run_trigger` takes the same optional `request.dispatchMode` as the API. `batch` sends every provider that can to its batch API and is refused, with each provider's reason, when none can; see [batch-mode.md](batch-mode.md). `canonry_run_get` returns the run's `dispatchModes`, `providerBatches` (a batch-pending run stays `running`) and per-provider `usage` with estimated cost.

The built-in Aero agent consumes the same MCP-derived local tool registry, then may apply an agent profile. The `ads-operator` profile is intentionally narrower than the full MCP catalog and adds one Aero-only context-packing helper, `canonry_ads_operator_context`, that bundles existing public reads for long-session efficiency. It is not an MCP tool because it introduces no new public capability; agents that need the same data outside Aero should call the existing project overview, ads, doctor, and memory tools directly.

Five ads tools call the provider live and spend on the operator's ad account:
`canonry_ads_account`, `canonry_ads_geo_search`, `canonry_ads_conversion_pixels`,
`canonry_ads_conversion_event_settings`, and `canonry_ads_live_delivery`. They
are read tools and stay in a `--read-only` catalog, but the server refuses them
to a credential that was never granted ads authority — a key carrying only
`read`, or one scoped to something unrelated, gets `403`. The default `*` key
and the ads-operator key below both satisfy the gate.

For an external ads operator, default to a project-scoped key with exactly
`read`, `ads.write`, and `ads.activate`. The auth layer confines a key whose
only write grants are ads scopes to that project's `/ads/*` mutations; unrelated project writes
remain forbidden. Do not hand an unscoped key to an external operator. Prefer
the `ads-operator` Aero profile when operating inside
Canonry because its visible tool catalog is narrower as well. All lifecycle
creates are paused and all updates require the entity already be paused. Direct
activation and archive tools are absent. A human uses a different `ads.approve`
credential through the API or CLI to issue a short-lived, single-use grant for
the exact tree, advertiser account, and executor key; grant creation and revoke are not MCP tools.
The operator can only execute that already-approved grant. The ads toolkit lists
unresolved receipts through an opaque keyset cursor, routes
`campaign_tree_activate` to bodyless exact-executor
resume, and reconciles other supported checkpointed provider IDs only by
verifying live state on the receipt-bound account. Neither recovery path retries
an ambiguous mutation or binds an uncheckpointed create by mutable-field
similarity. Fresh pending generic receipts cannot be manually claimed, and
inconclusive generic inspections back off before a five-attempt quarantine.
Click campaigns bill for clicks and their ad groups must use click billing;
Canonry rejects a parent/child bidding mismatch before any mutation. Naming
provider-issued conversion event-setting IDs is a separate, optional
optimization choice, not a requirement of click billing.
Complete the live-provider and
production-graduation checks in the
[CLI operator reference](../skills/canonry/references/canonry-cli.md#guarded-operator-release-gates)
before enabling spend.

## Progressive Tool Discovery

`canonry-mcp` defaults to a **core tier**. Loading a toolkit registers its available tools and sends `notifications/tools/list_changed`.

For shared query assignments and measured results, see [Query control and AI visibility](query-visibility.md). The setup toolkit provides workspace, preview, and commit tools. Monitoring provides `canonry_visibility_report`. Its optional `marketKey` narrows a project, group, or property report to exact saved market assignments, including metrics, competitors and answer details. Omit it to read the full selected scope. Each population carries `comparison`, the change versus the previous eligible whole-project sweep when both are complete and comparable; it is absent when that sweep cannot be read. Preview requires write access but starts no provider calls.

Core tier (always loaded):

- `canonry_help` — compact intent route, approval boundaries, and analyst playbooks to read; use `includeCatalog: true` for toolkit details and `playbook` for a playbook's full text
- `canonry_load_toolkit` — register a toolkit's tools for the rest of the session
- `canonry_projects_list`, `canonry_project_get`
- `canonry_project_overview` — composite read for "how is project X doing?"; its `whatChanged` is the dashboard's "What changed" (lost mentions and lost citations in the latest check, one per query, and runs in progress)
- `canonry_search` — composite text search across snapshots and insights
- `canonry_doctor` — run health checks (Google/GA auth, redirect URI, scopes, providers); filter by check id or wildcard
- `canonry_settings_get`
- `canonry_apply_config`, `canonry_run_trigger`, `canonry_run_cancel`
- `canonry_agent_webhook_attach`
- `canonry_feedback` — send a struggle, bug, or improvement about Canonry itself to the Canonry team (canonry.ai); credentials are redacted, and the install id is attached only while telemetry is enabled

For project connections, call `canonry_help({intent:"connect"})`. On a
write-capable connection, Search Console and GA4 can start Google consent in
the operator's browser and select a property afterward. Bing uses the key
saved in Canonry Settings. Cloud Run uses the service account saved for the
same project and log target, or returns a private setup link in `dashboardUrl`.
New sources connected this way collect logs from connection time. An approved
historical import can set `startFromNow: false`. Recheck the saved connection
after completing any browser step.
Hosted OAuth grants for read access or research do not include connection
setup. An administrator can use a write-authorized MCP API key for setup.

Toolkits (loaded on demand):

| Toolkit | What's in it | When to load |
| --- | --- | --- |
| `monitoring` | sentiment settings/summary/evidence/compare/backfill preview/jobs, administrator configure/backfill submit, runs list/latest/get, the next manual sweep preview (`canonry_run_preview`: planned answers and provider holds, no spending), project history, timeline, snapshots list/diff, insights list/get, health latest/history, content targets/sources/gaps, content dismissal list/dismiss/restore, `canonry_organic_evidence` (GSC + GA4 + server AI evidence ladder), Agent Readiness audit scans, scores, pages, findings and link-graph reads (`canonry_agent_readiness_*`) | Investigating regressions, comparing runs, reviewing insights/health, checking Agent Readiness, surfacing content opportunities, generating client-facing reports |
| `setup` | project export/upsert, first-run setup status (`canonry_project_setup`), sitemap Target discovery, measurement setup/overview, draft get + paginated Targets/assignments/groups, guarded draft actions, query sets/templates, measurement-plan get/history/compile/diff/publish/deactivate, revision-pinned measurement report, queries list/add/remove/replace/generate, legacy keyword aliases, competitors list/add/remove plus `canonry_competitors_aliases_set` (curated answer-text names) and the answer-derived auto-alias tools (`canonry_competitors_auto_aliases_detect`, `_apply`, `canonry_competitors_aliases_block`, `_unblock`), schedule get/list/set/delete plus `canonry_schedule_preview` (the next occurrence of proposed timing), answer-engine provider connections (`canonry_provider_settings_get`, `canonry_provider_settings_update`, `canonry_provider_disconnect`, `canonry_provider_test`, `canonry_providers_reload`), notification event names, telemetry status, insight dismiss, backlinks domains | Onboarding a project, discovering and publishing its Target measurement plan, reviewing stored Target evidence, editing queries/competitors/schedules, reviewing, testing or disconnecting a provider connection, reviewing notification capability, and checking safe setup state |
| `gsc` | `canonry_gsc_connect`, `canonry_gsc_properties`, `canonry_gsc_set_property`, Google connection status, performance, inspections, coverage and sitemaps | Connecting Search Console and reviewing search and indexing evidence |
| `bing` | `canonry_bing_connect`, `canonry_bing_status`, `canonry_bing_sites`, `canonry_bing_set_site`, coverage and search data | Connecting Bing Webmaster Tools and reviewing evidence for the selected site |
| `ga` | GA status, native-channel/lead/search-demand measurement analysis (leads also split by AI engine with lead rates), GA4's Search Console landing-page report (Google organic clicks, impressions, CTR, position and active users per landing page), traffic (social and creator platforms ranked by conversions per 1,000 sessions), coverage, AI/social referral history, social/attribution trends, session history | Traffic, referral, attribution data from Google Analytics 4 |
| `gbp` | Google Business Profile location discovery, selection, and local AEO evidence | Reviewing connected Business Profile locations and local search visibility |
| `ads` | OpenAI ads connection/live account status, integrity review, geo target search, conversion pixels/event settings, lifecycle-ready snapshots with upstream timestamps, paid rollups, summary, sync, durable receipts, unresolved-receipt listing, provider-state reconciliation, exact-executor activation recovery, image upload, paused create/update/pause operations, and execution of an exact human approval grant. No approval creation, direct activation, or archive. | Planning, reviewing, recovering ambiguous receipts, preparing ChatGPT ads, or executing a separately approved launch |
| `google-ads` | connected status, customer discovery, stored conversion-action and effective-goal snapshots, and bounded read-only sync | Discovering Ads customer options or reviewing conversion evidence |
| `gtm` | account, container, and workspace discovery, sanitized live/draft graphs, and bounded read-only sync | Discovering GTM resource options or reviewing tag-graph evidence |
| `conversion-tracking` | declared contracts and stored cross-provider integrity assessments with no live provider call | Checking whether stored Google Ads and GTM evidence agrees with a contract |
| `traffic` | Complete 7/14/30/90-day stored totals and breakdowns (`canonry_traffic_analytics`), referral burst assessment (raw counts, candidate evidence, separate adjusted estimate, coverage limits), list sources, source detail (24h totals + latest run), windowed crawler/AI-referral events, stored AI visitor journeys, Cloud Run / WordPress / Vercel connect, sync, async backfill for Cloud Run/Vercel (replaces hourly rollups in a `--days` window with current classifier output; WordPress requires a retention-aware repair) | Confirming server-log evidence of crawler hits or AI-referral sessions (e.g. GPTBot, ChatGPT-User), reviewing candidate AI-referral bursts before quoting server-side AI referral totals, wiring up / syncing a Cloud Run, WordPress, or Vercel traffic source, or one-shot reclassifying supported historical logs after a classifier change |
| `agent` | Aero memory list/set/forget, agent clear, agent webhook detach | Reading or writing project-scoped Aero notes, clearing a stuck conversation, removing an agent webhook |
| `discovery` | **Find queries:** start/inspect ICP discovery sessions, harvest candidate seeds, and optionally promote approved findings into tracking. **Research queries:** start one run with `canonry_research_run_start` or reviewed destinations with `canonry_research_batch_start`. Read results with `canonry_research_runs_list` and `canonry_research_run_get`. Research never adds tracked queries. | Expanding or auditing a project's tracked-query basket, or researching specific queries, models, and locations without changing tracking. |

The `canonry_project_export` MCP tool always returns notification webhook URLs in redacted form. It has no secret opt-in input.

Loading a toolkit is idempotent and persists for the rest of the session; there is no unload. `canonry_load_toolkit` returns `{ status: 'loaded' \| 'already-loaded' \| 'empty', name, tools }`. The server coalesces enable/disable changes into one `notifications/tools/list_changed` when a toolkit is first loaded, before the response. Legacy clients receive it directly. Modern clients receive it through `subscriptions/listen`; the SDK's `ClientOptions.listChanged` opens that subscription automatically. Clients without a subscription can call `tools/list` after loading to refresh their catalog.

#### Wait for the response before pipelining

`canonry_load_toolkit` runs the enable side effect synchronously inside the call's handler, but the newly registered tools only become callable after the response is returned to the client. Always await the response before issuing a `tools/call` for a tool that the toolkit just enabled. Pipelining the two requests on the same connection (sending `tools/call` for `canonry_insights_list` immediately after `canonry_load_toolkit` without awaiting the load response) can race the registration and produce `Tool ... disabled`. Sequenced clients (Claude Desktop, Cursor, Codex) already wait by default; only batch test harnesses or custom clients risk this.

### Eager mode

Use `--eager` or `CANONRY_MCP_EAGER=1` to register the available stdio catalog at startup.

```json
{
  "mcpServers": {
    "canonry": { "command": "canonry-mcp", "args": ["--eager"] }
  }
}
```

`--eager` and `--read-only` compose: `canonry-mcp --eager --read-only` registers every read tool eagerly.

### Read-only scope and toolkits

`--read-only` filters out write tools before the catalog is built, so toolkits with no read tools appear as `empty` from `canonry_load_toolkit`. Mixed toolkits load with whatever survives the filter — the `agent` toolkit, for example, drops its writes (`canonry_memory_set`, `canonry_memory_forget`, `canonry_agent_clear`, `canonry_agent_webhook_detach`) and exposes only `canonry_memory_list` under read-only scope.

### Read-only API keys (auto-detection)

The same startup probe preserves explicit narrow scopes such as `research.run`
and filters the catalog to matching capabilities, not general writes.

A read-only API key (`canonry key create --read-only`, scopes `['read']`) is rejected by the API on every write HTTP method (`403 FORBIDDEN`). To avoid advertising tools that would 403 at call time, `canonry-mcp` probes `GET /keys/self` at startup and, when its configured key is read-only, **auto-restricts the catalog to read tools** — exactly as if `--read-only` had been passed — and prints a one-line notice on stderr. The probe is best-effort: if the API is unreachable or the server predates the endpoint, the adapter keeps the requested scope. A read-only key can only ever narrow the catalog, never widen it; passing `--read-only` explicitly skips the probe.

## Safety Rules

MCP uses stdio, so any normal stdout write breaks the protocol. Code under `packages/canonry/src/mcp/` must not use `console.log`, `process.stdout.write`, CLI dispatch, telemetry, logger imports, DB imports, route imports, or job-runner imports. Tool handlers call `createApiClient()` only.

Tool input schemas are Zod schemas tied to `packages/contracts` and exposed as JSON Schema for MCP clients. Ordinary tool results retain their legacy JSON text and also provide MCP `structuredContent`: object responses stay objects, top-level arrays are wrapped as `{ "items": [...] }`, and scalars as `{ "value": ... }`. Canonry API/client errors and Zod input-validation errors return MCP tool results with `isError: true` and the same structured `{ "error": { "code", "message", "details" } }` envelope in both text and `structuredContent` (`VALIDATION_ERROR` for bad input, with `details.issues` listing the per-field problems). Malformed JSON-RPC and unknown tools remain MCP protocol errors.


Native Aero uses the same authorized registry, starting with core tools and
loading toolkits on demand. `aero_inspect_view` composes existing visibility
report or Agent Readiness API reads; external agents use those public reads directly.
The native prompt remains an `excluded-protocol` SSE operation: external agents
call Canonry tools directly rather than recursively delegate to Aero. Native
view context and execution limits are available through REST and `agent ask`.
Native Aero can preview answer-derived competitor aliases
(`canonry_competitors_auto_aliases_detect`) but cannot apply them: applying
restates stored history, so `canonry_competitors_auto_aliases_apply` is not in
its catalog, and `canonry_project_upsert` / `canonry_apply_config` refuse an
Aero call that would change the project's `competitorAutoAliases` mode.

### Aero conversation history

The `agent` toolkit includes `canonry_agent_conversations_list`, `_get`, `_new`,
`_resume`, and `_delete`. These mirror `agent conversations` CLI commands and
`/projects/:name/agent/conversations` routes. Supply a UUID `id` when creating;
reuse it for retries. List returns `nextOffset` for archive pagination. All calls
require full instance-administrator authority; a read-only or project-scoped key
cannot read private conversations. New/resume preserve the prior conversation.
Delete removes its transcript and compaction notes, retaining shared project
notes. Native Aero can read history but cannot invoke conversation mutations.

### Monthly class comparisons

`canonry_visibility_compare` adds `mention-rate-branded`, `cited-rate-branded`,
`mention-rate-non-brand`, and `cited-rate-non-brand`. Each metric carries its
class, numerator, denominator, Wilson interval, and noise verdict. Missing
classification returns `classification-unavailable`; it never pools the classes.
`excludedUnknown` counts observations missing that metric's independent signal.

Advanced portfolios accept `scope` (`project`, `group`, `market`, `property`),
`scopeKey`, optional `marketKey`, `provider`, and `location`. Property keys are
Target stable keys. Market selection intersects exact frozen assignment edges.
Shared executions count once per class. Material plan changes are excluded;
display-only comparable revisions retain continuity. Schema-v1 class metrics
are unavailable because that history has no frozen class assignments.

Without `scope`/`marketKey`, responses keep the four original metrics and
their project basket (`provider` and `location` narrow it case-insensitively,
for Simple and Advanced alike). Advanced class metrics then use the separate
`classComparison` frame, including its model-continuity exclusions and monthly
run counts. A `scope` or `marketKey` answers entirely from the frozen frame at
the top level, and is refused when either month holds runs whose plan cannot
be reconstructed. On frozen frames, answers with incomplete source capture
leave every citation figure and are counted in `excludedUnknown`. All reads use
stored evidence.
The CLI exposes the same selectors as `--scope`, `--scope-key`, `--market-key`,
`--provider`, and `--location`, and `--format json` returns the same response.

### Monthly report readiness

`canonry_doctor` accepts `reportMonth: "YYYY-MM"` with `project` and optional
`checks: ["report.*"]`. The equivalent CLI is
`canonry doctor --project example --report-month 2026-09 --check 'report.*' --format json`.
The project doctor API accepts `?reportMonth=2026-09&check=report.*`.
Omitting the month retains the previous closed month through UTC day 3, alongside
the current month. Future months are rejected.

The checks read stored sweeps, snapshot model continuity, daily GA/GSC totals,
and stored server AI-referral rollups beside GA AI referral rows
(`report.ai-referral-bursts`). They return explicit unknown coverage where
absent daily rows could mean either zero activity or missing collection.
Pending reporting dates and dates before connection are separate.
`notificationPolicy: "silent"` leaves these advisories visible in doctor without
sending client health alerts. The checks never run a sweep, sync data, create
schedules or call providers.

### Content-target dismissals

`canonry_content_dismissals` reads the project's `{ dismissals }` envelope.
`canonry_content_dismiss` saves one addressed recommendation using `project`,
`targetRef`, and optional `addressedUrl` and `note`; `canonry_content_restore`
removes it. All three are in `monitoring`. Dismiss and restore require write
scope and explicit approval. Their CLI equivalents are `content dismissals`,
`content dismiss`, and `content restore`. REST restore returns HTTP 204;
CLI and MCP return `{ targetRef, restored: true }`.

### Traffic analytics

`canonry_traffic_analytics` reads all stored traffic rollups in a selected
7/14/30/90-day window (default 30), with equal-length prior totals and separate
verification and arrival-class counts. `activity` is null without a
non-archived traffic source. Zero counts mean no matching stored events;
they do not certify source sync or measurement coverage. `coverageStart` is
the earliest project observation, or null. `priorWindowComplete` tests whether
that date reaches the prior window's start. When false, headline, arrival-class,
and operator `deltaPct` values are null. Even true does not prove continuous
collection or the same source coverage across both windows.

### AI referral assessment

`canonry_traffic_referral_assessment` is a read-only traffic tool backed by
`GET /projects/:name/traffic/referral-assessment` and
`canonry traffic referral-assessment`. Supply `project`, `startDate`, and
`endDate` (inclusive UTC dates, at most 366 days). Optional `sourceId`,
`burstThreshold` (default 100), `ratioThreshold` (default 3), and `limit`
(default 100, maximum 500) match the API. The shared strict schema rejects
unsupported Property, Target and market filters instead of silently broadening them.

Threshold-qualified groups (one source, product, normalized path and UTC hour
each) are candidate bursts, not confirmed automation. The adjusted estimate
remains separate from raw totals. Evidence is capped
independently from totals. The default threshold is an uncalibrated review
trigger. An observed server/GA quotient, rounded to 2 decimals, can be shown
when GA is positive, but comparable coverage and GA timezone remain unknown. GA
reads `observed-zero` only when the window lies inside the latest GA sync window
and that sync stored no AI row for it. Otherwise, including after a
`ga sync --only traffic|social` that left earlier AI rows in that window, absent
GA rows are `missing`.
The silent `report.ai-referral-bursts` doctor diagnostic carries these limits in
its details, counts `candidateGroups`, and warns only when candidate bursts
exist; it never claims a verified 3x warning.

### Sentiment

Load `monitoring` for `canonry_sentiment_settings`, `canonry_sentiment`,
`canonry_sentiment_evidence`, `canonry_sentiment_compare`,
`canonry_sentiment_backfill_preview`, `canonry_sentiment_jobs`, and
`canonry_sentiment_job`. Reads use stored data and never call TypeSafe. The response
keeps judged/selected assessment denominators, rated and eligible answers with the
server's `ratedAnswerRate` (each answer once, admitted or not), exclusions, nullable
rates, per-query and location summaries, and comparison refusal reasons. Select
`queryClass` explicitly; branded and non-brand have separate denominators. An absent
intended subject is excluded, never unfavorable. Use `queryId` for a specific frozen
query, and `executionNodeKey` for one Advanced execution node of it. Summary query
rows are compact and paged: `queryLimit` rows (default 25), then pass
`queryPage.nextCursor` as `queryCursor`. Per-engine assessments and per-location
scores are opt-in with `include: ["assessments", "locations"]`, or come by default
when `queryId` names one query; Advanced rows are per `executionNodeKey`. The jobs
tool returns job summaries with an `attemptCount`; `canonry_sentiment_job` pages
attempt receipts (`attemptLimit`, `attemptCursor`). Summary/evidence can select an
exact saved run group with a `runIds` array, mutually exclusive with `runId`.
Evidence takes an `outcome` array (for example `["mixed", "unfavorable"]`) that keeps
only those stored outcomes without changing how answers were scored; the page echoes
it as `selection.outcome`. Branded summaries carry `criticizedProperties` (empty with
fewer than two Properties): `total`, and `keys`, the first five property breakdown
keys, most criticized first, ranked on the server. Read one Property's criticism with
`scope: "property"`, its key as `scopeKey`, and that `outcome`. Preserve every
selection field, `outcome` included, and the resolved
`evaluationDefinitionId` when following an evidence cursor. Output schemas are
tolerant readers: a field a newer server adds is dropped, and a new state or outcome
reads as a string, so an older adapter never rejects a newer server's response.

`canonry_sentiment_configure` and `canonry_sentiment_backfill` are write tools for
install administrators. Viewer, delegated viewer, read-only and project-scoped
credentials cannot authorize them. Configuring a project takes explicit `enabled`;
credentials stay in local install configuration. Both
install and project switches default off. Enabling applies to future completions and
needs a ready install; switching a project off works even while the install is off.
While either switch is off, reads keep operational states but withhold verdicts,
quotations and outcome counts.

For historical work, preview explicit `runIds` (or `runId`) or a bounded `from`/`to`
range with a required `queryClass` (`branded` or `non-brand`; preview and submit each
class you need), inspect the returned selection and `skipped` reasons (including
`excluded-branded` / `excluded-non-brand` for the other class and
`legacy-missing-language` for Advanced sweeps saved before language was
recorded), then submit its exact `previewToken` and an explicit `idempotencyKey`.
Submission can disclose source answer text to TypeSafe and incur usage; unchanged
retries return one job receipt. Read the job to inspect progress, safe attempt
errors, unknown usage and cancellation epochs. Native Aero reads the seven
stored-data tools after loading `monitoring`; configure and backfill submit stay
with the operator.

`canonry_traffic_samples` reads a stored sampled tail with 30-day retention in the
traffic toolkit. It exposes no IP hashes and makes no provider call. `kind: all`
excludes unknown requests; select `unknown` explicitly. `sourceId`, inclusive ISO
`since`/`until`, literal `path` prefix, `limit` (1 to 500), and `offset` filter and
page stored samples. Sample rows are not visits. A browser agent's (Google-Agent,
Claude-Agent) AI user fetch sample carries `requestKind` (`page`, `action` or
`resource`); unless it is likely fake, only a `page` sample was counted as an AI
user fetch. Project/source scope only, for Simple and Advanced projects. Viewers
and embeds are denied.

`canonry_traffic_agent_journeys` lists stored user-triggered agent request
sequences; `canonry_traffic_agent_journey` reads a sequence's ordered requests.
Both are stored reads in the traffic toolkit. Preserve `since`, `until`,
`sourceId`, `agentId`, `verificationStatus`, and `targetKey` when opening a
detail; `limit` and `offset` page the result. IP/UA correlation is inferred,
not a confirmed user task; requests without an IP stay unlinked. Operator
verification is separate from correlation. Responses carry source limitations
(including what a browser agent's journey leaves out: it keeps page loads,
actions and failed requests), retention and cap evidence. Advanced Property attribution uses the current
plan's URL coverage, with its revision; market, model, query class and task
intent remain unavailable. Viewers and embeds are denied; API read keys retain
their project boundary. No provider calls or writes.

`canonry_traffic_unrecognized_agents` lists self-identified bots and agents that no
classifier rule names yet, in the traffic toolkit: summed by the name in their user
agent, busiest first, with hits, first and last seen hours, an example user agent
and path, and sources. Browsers, generic HTTP tools, static files and writes are left
out. `sourceId`, inclusive `since`/`until` (default the last 30 days) and `limit`
(1 to 500) filter. Stored rows only, no provider call. Viewers and embeds are denied.

`canonry_journeys_summary`, `canonry_journeys_list` and `canonry_journey_get` read
stored AI visitor journeys in the traffic toolkit: visitors with an AI-referred visit,
followed from their first one, their later visits and entries, and one visitor's
requests (`canonry_journey_get` pages visits with `limit` and `offset`).
Visitor keys are hashes, never IPs; `keyBasis: ua` keys (sources without an IP)
can merge people on the same device and browser version. Stored reads only, no
provider call. Viewers and embeds are denied.

`canonry_ga_acquisition` is a read tool in the GA toolkit for stored sessions by
date, channel, source/medium, host and normalized page. It accepts the API window,
date and exact filters, `pathPrefix`, comma-separated `groupBy`, and paging. MCP
limits pages to 500 rows. `totalSessions` is the full filtered total. Never calls
Google and never claims Property, Target, market, or current-property attribution.

`canonry_project_update` updates named fields through PATCH. It preserves omitted fields, merges measurement one level, and accepts `expectedConfigRevision` for atomic conflict detection. `canonry_project_upsert` retains its full PUT behavior.

### Competitor change previews

`canonry_competitors_change_preview` is a setup read tool for an explicit add,
remove, replacement domain list, or curated alias change. It reports the latest
stored landscape before and after, including mention counts, tracked competitor
basis, query class, exact run IDs and percentage-point change. Advanced projects
use all-market non-brand scope; Simple projects without a usable brand pool
queries. These changes restate all stored periods. The result estimates one
point in time and is not the overview card's separate instrument.

The preview POST keeps existing authorization: a write-capable key is required
even though it stores nothing. Read-only keys can use the detection GET through
`canonry_competitors_auto_aliases_detect`, which also reports impact. The add and
remove tools return the resulting competitor list. Ordinary writes make no
implicit preview request. An add in apply mode reports pending alias detection,
which can move the result again. Block/unblock, market pins, project identity
edits, apply and discovery promotion are outside this preview surface.

Competitor previews also report the shared bulk-add limit, new or recently added
count, and whether acknowledgement is required. Measured writes above five
domains in 24 hours require `acknowledgeBulkAdd: true`; apply and discovery
promote are outside this guard. Aero cannot supply this acknowledgement.

Agent Readiness audit scans (`canonry_agent_readiness_run`) accept `includeGeo` and `includeAgentSkills`. Agent integration checks default on; set `includeAgentSkills: false` to disable them. Geographic checks default off. Both participate in scan identity; differing selections cannot reuse an active scan. Geographic checks suit businesses serving specific places. These checks run inside the instance without a browser.


### Preview schedule timing

`canonry_schedule_preview` accepts `{ project, timing: { preset, timezone } }` (or `cron` / `recurrence` instead of `preset`). It returns the next occurrence without saving or enabling a schedule and without provider usage. Read credentials may preview their authorized projects. The equivalent CLI is `canonry schedule preview <project> --preset daily@9 --timezone America/New_York --format json`; saving remains a separate write.
