Tools
This is a reference catalogue. Tools cannot be configured or run from this page.
Get-agent-runs
CLARIFY_MCP_GET_AGENT_RUNSList an agent's runs, executions, invocations, and past run history, or fetch one run with its full transcript. Use this tool for any question about what an agent has done, when it ran, or how often it has fired. ## When to use this tool - "List runs for this agent" / "show me the agent's runs" - "Agent history" / "past runs" / "recent runs" / "last run" - "How many times has this agent run" / "count runs for an agent" - Debugging why an agent behaved a certain way: fetch the run to see the messages, tool calls, and responses that happened - The user provides an agent id and asks "show me what it did" ## Not the same as get-workflow-runs Agents and workflows both have runs but they live in different tables. Use this tool (not `get-workflow-runs`) whenever the subject is an agent or an agent id. Passing an agent id to `get-workflow-runs` silently returns nothing. ## How it works - Without `run_id`: returns a paginated list of recent runs for the agent - With `run_id`: returns the full run including its message transcript - A "run" is the chat session an agent produced when one of its triggers fired — user and assistant messages, tool calls, results, and errors ## Pagination - When the user asks for "more" runs / next page / older runs, call this tool again with the same agent_id and a larger `offset` ## Reading status and credits Each run reports a **Status** (e.g. "In progress", "Completed", "Failed") — use it, not credits, to judge whether a run has finished. **Credits Used** is a running cost total, not a progress indicator: a response that incurs AI cost adds at least 1 credit, so `0` credits means no such response has completed — the run may be not started, still generating its first response, or have failed before producing one. Never infer completion or a run's cost from the credit number alone; read Status for progress, and use the Created time to gauge how long a run has been running. ## Read the transcript before describing a run Whenever the user asks what a specific run did, or to summarize or explain one, call this tool with that run's `run_id` first. The list mode returns only counts and credits, never the messages, so describing a run from the list alone means inventing its content. Only the `run_id` transcript shows what happened. When the user reports that an agent isn't working as expected, proactively fetch the most recent run transcript before suggesting changes. Compare what happened in the run against the agent's instructions to diagnose the root cause. After diagnosing, explain what you found with specifics from the transcript. Suggest targeted fixes via `create-or-update-agent`, then offer to rerun.
Get-agents
CLARIFY_MCP_GET_AGENTSList agents visible to the current user, or fetch a single agent by ID. ## When to use this tool - When the user asks to see their agents or list available agents - When you need to look up an agent's instructions or configuration - When the user asks about a specific agent by name or ID ## How it works - Without agentId: returns all visible agents with description only - With agentId: returns the full agent details including complete instructions and configured triggers
Get-artifact-component-doc
CLARIFY_MCP_GET_ARTIFACT_COMPONENT_DOCGet the full prop contract for one or more Clarify design-system components available to artifacts — each component's summary, a usage snippet, and every prop with its type and allowed values. ## When to use this tool The create-or-update-artifact tool lists the available `@clarify/ui/*` components with a one-line summary each. Call this before using components you are unsure about to get their exact props and allowed values, and call it when an existing artifact fails to render against a component so you can repair it against the current contract. ## How it works Pass one or more `specifiers` exactly as listed (e.g. `@clarify/ui/button`) — batch everything you need in a single call. Returns each component's documentation as markdown. Props are extracted from the component source, so the values are always current. ## Runtime dependency versions The artifact runtime pins `framer-motion` (v12.40.0), `react` (v19.2.8), `react-dom` (v19.2.8), `recharts` (v3.8.1). See the create-or-update-artifact tool for which of these your artifact JSX may import directly; the rest run internally (e.g. `react-dom` powers the scaffold's mount call). `@clarify/ui/*` itself is not independently versioned — it tracks this package.
Get-artifact-source
CLARIFY_MCP_GET_ARTIFACT_SOURCERead the current source of an existing artifact — the JSX of its applied version, plus its name and description. ## When to use this tool Use this before updating an artifact so you patch its real current source rather than rewriting it from memory. It is the read half of the artifact edit loop: read the source here, apply your fix, then pass the full revised content to `create-or-update-artifact` with the same `artifact_id` to save a new version. It is especially useful when recovering from a render or query error reported to you for an artifact you did not author in this conversation. ## Upgrade while you're here The saved source may predate the current authoring guidance — an older artifact can hand-roll something a `@clarify/ui/*` component or hook now covers, or use query and chart code that has since improved. While you have the source open to make the requested change, compare it against the current component catalog and the query and chart guidance in `create-or-update-artifact`, and fold any clear upgrade into the same new version: swap a hand-rolled pattern for the component that now covers it, and bring stale query or chart code up to the current guidance. Change only what is a clear improvement — leave the rest of the source untouched. Then tell the user in plain terms that you upgraded it, without the build details, e.g. "I also updated the UI to the latest version for more features." ## Returns The applied version's JSX source (a React component named `ArtifactContents`), the artifact's name, and its description. Fails if the artifact does not exist or has no applied version yet.
Get-calendar-events
CLARIFY_MCP_GET_CALENDAR_EVENTSList the current user's calendar events in a time range. ## When to use this tool - To answer "what's on my calendar today/tomorrow/next week" - To find a specific upcoming meeting by title or topic - To gather context (attendees, conferencing link) before drafting an email or creating a follow-up event ## How it works Reads from Clarify's synced calendar data: no live API call to Google or Microsoft. Filters meetings the current user attends in the given time range. ## Returns A list of events with both `event_id` (Nylas calendar event ID, used by the write tools) and `_id` (Clarify meeting ID, used by other meeting tools). When more events match than `limit`, the response notes the truncation. ## Important notes - Time range is required. Be reasonable: a 7-day window is a good default. - The optional `query` filter does case-insensitive substring matching on title and description.
Get-campaign-recipients
CLARIFY_MCP_GET_CAMPAIGN_RECIPIENTSList the individual people enrolled in a campaign, with their per-person engagement — who opened, who clicked, who replied, and when. ## When to use this tool - Answer "who clicked", "who opened", "who replied", "who hasn't responded" - Build a follow-up or retarget audience from the people who engaged with a campaign - Check where a specific person is in a campaign, or why their run stopped Use `get-campaigns` instead when you need campaign-level totals and rates rather than the people behind them. Get the `campaign_id` from that tool first. 📖 **For campaign rules and examples**: Use read-context with context: "campaign-docs" ## Returns One entry per recipient: person name, email, person ID, delivery status, opened/clicked/replied flags, and the timestamp of their most recent open, click, and reply. ## Pagination - When the user asks for "more" results, use the EXACT same inputs and only change the offset parameter - The tool will tell you the next offset value to use ## Examples <example> { "campaign_id": "0195f2c1-...", "event": ["clicked"] } </example> <example> { "campaign_id": "0195f2c1-...", "status": "completed", "limit": 25 } </example>
Get-campaigns
CLARIFY_MCP_GET_CAMPAIGNSList campaigns in the workspace, or fetch a single campaign by ID with full details. ## When to use this tool - Without campaign_id: discover existing campaigns, search by name, get campaign IDs - With campaign_id: read a campaign's full email content, inspect subjects/bodies/timing, check performance metrics, get details before duplicating with `create-campaign` 📖 **For comprehensive campaign rules and examples**: Use `read-context` with context: "campaign-docs" ## Returns **List mode** (no campaign_id): - Campaign name, ID, description, status, email step count, target list, created/updated info **Detail mode** (with campaign_id): - Full campaign details including all email steps with subjects, bodies (HTML with variables), and timing - Campaign-level performance: open rate, click-through rate, response rate, bounce rate - Per-email-step engagement: sent, opened, clicked, replied, bounced counts All engagement here is aggregate counts only. To find out *which people* opened, clicked, or replied — and when — use `get-campaign-recipients`. ## Pagination (list mode only) - When user asks for "more" results, use the EXACT same search inputs and only change the offset parameter - The tool will tell you the next offset value to use ## Duplicating a campaign To duplicate a campaign, call this tool with campaign_id first, then pass the returned email steps and settings to `create-campaign` with a new name like "Copy of <original>". Copy the `list_id` so the duplicate targets the same audience. Do NOT copy from_name. Let the new campaign use the current user's sender identity. If the original sender differs from the current user, also remove the original sender's personal sign-off from email bodies.
Get-current-user
CLARIFY_MCP_GET_CURRENT_USERGet information about the current authenticated user, including their timezone. ## When to use this tool Use this to understand who "me", "my", and "I" refer to in user queries. ## Important notes When interpreting relative dates (e.g., "last 2 weeks", "yesterday"): - Calculate dates in the user's timezone returned by this tool - Convert to UTC and ISO format for database queries
Get-lists
CLARIFY_MCP_GET_LISTSGet list metadata (saved views) for an entity type, or fetch a single list by ID. Only dynamic lists (membership driven by a SQL query) are returned. Legacy static and default lists are filtered out. ## When to use this tool - Without list_id: discover existing lists, search by name or description, or filter by creator or owner - With list_id: fetch full details for a specific list Supports case-insensitive substring search and filtering by creator (created_by) or owner (owner_id) when no list_id is provided. ## Returns - List name (title) - Description - SQL query - Layout (table, board) - Owner and creator (user name, email, and user ID) - Last edited (when a person last changed the list's query or layout, and who — or "No edits recorded"). This does not track title, emoji, or description edits. ## Pagination - When user asks for "more" results, use the EXACT same search inputs and only change the offset parameter - The tool will tell you the next offset value to use (e.g., "Call this tool again with offset=25 to continue")
Get-records
CLARIFY_MCP_GET_RECORDSRetrieve detailed information about specific records by their IDs. This tool provides comprehensive context about records, including relationships, AI summaries, and other details. Use this tool when you need to: - Understand the current state of specific records before answering questions or taking actions - Read meeting recording transcripts with full speaker attribution - Read email content, subject, body, and participants - Get rich context about records found via query-data Typical workflow: Use query-data to find record IDs, then pass them here for full details. Meeting-specific guidance: - For meeting: returns metadata, summary (AI-generated), notes (user-written), and associated recordings. If summary is null, check notes before concluding no content exists - For meeting_recording: returns the full transcript with speaker names and timestamps - When the user asks for exact quotes, verbatim wording, or "what exactly was said", fetch the meeting_recording transcript via get-records. The meeting summary is paraphrased and does not preserve the original words.
Get-schema
CLARIFY_MCP_GET_SCHEMAGet the schema for Clarify entities. ## When to use this tool Use the read format when working with SQL queries and the query-data tool. Use the write format when creating or updating records with the create-or-update-records tool. Pass the specific entities you need. Read defaults to the CRM database, and omitting entities returns every CRM entity, a large result that is re-sent on every later turn, so only omit it when you genuinely need the whole model. For lead columns (funding stage, employee range, industries, location), request the tam_company or tam_person entities to get the schema for the find-leads tool. The analytics event log schema comes with the query-analytics tool directly, so you do not need this tool for it. ## Databases Clarify has three databases: - CRM database (company, person, deal, meeting, user, task): your workspace data. Use with the query-data tool. Read returns these by default. - Leads database (tam_company, tam_person): prospecting data for finding new leads. Request these entities explicitly. Use with the find-leads tool. - Analytics database (ClickHouse, single `analytics.event` table): historical event log of every CRM change: point-in-time and change-history questions. Its schema comes with the query-analytics tool. ## Formats - read: schema for reading data via SQL queries with the query-data tool, or lead columns for the find-leads tool. Returns all columns, types (including JSONB structure), relationships, join tables, and custom fields. Defaults to CRM entities. - write: writable fields for the create-or-update-records tool. Returns fields that can be set when creating or updating records.
Get-workflow-runs
CLARIFY_MCP_GET_WORKFLOW_RUNSGet execution runs for a workflow. Returns run history with status and timing. ## When to use - Check if a workflow is executing correctly - Review recent run history - Count failures or investigate patterns ## Returns - Run ID, status, start/end times, duration - Record that triggered the run (if applicable) - To get full details of a specific run, use the get-records tool with entity "workflow-run" and the run ID ## Pagination - When the user asks for "more" results, use the same inputs and only change the offset
Get-workflows
CLARIFY_MCP_GET_WORKFLOWSGet and search workflows in the workspace, or fetch a single workflow with its full configuration. When called without `workflow_id`, returns metadata for matching workflows (supports case-insensitive substring search and enabled/disabled filtering). When called with `workflow_id`, returns the full configuration for that one workflow (trigger with input and filters, every action block) and ignores the other inputs. ## When to use this tool - Find a workflow by name to get its ID - Discover existing workflows in the workspace - Get the workflow ID before calling `get-workflow-runs` or `create-or-update-workflow` - Confirm a workflow's trigger filters match what the user asked for (pass `workflow_id`) - Inspect a specific block's input or filters before editing it (pass `workflow_id`) - Walk the full block order (trigger → blocks → exits) to debug a misconfigured workflow (pass `workflow_id`) ## Returns Without `workflow_id` (list mode), for each workflow: - Workflow ID - Name and description - Status (active/draft) - Trigger plugin ID - Number of action blocks - Created and updated timestamps With `workflow_id` (single mode): - Workflow ID, name, description, status (active/draft), and timestamps - Trigger: plugin ID, input, filters - Each block: ID, plugin ID, input, filters, prev/next links ## Pagination When the user asks for "more" results, use the same inputs and only change the offset
Query-analytics
CLARIFY_MCP_QUERY_ANALYTICSExecute read-only ClickHouse SQL against the analytics event log. ## When to use this tool Use `query-analytics` for **historical / point-in-time** questions about CRM records: anything that requires looking at the sequence of changes over time, not just the current state. Examples: - "What was the sequence of stage changes for this deal?" - "How long did this deal sit in 'In progress'?" - "What was the total amount of all deals in each stage on a specific date?" - "How many deals were created per day last week?" - "Who last edited this record, and when?" ## When NOT to use this tool For **current state** questions ("which deals are open?", "what's this company's domain?"), use the `query-data` tool: it queries PostgreSQL directly and is faster for live values. Only fall back to `query-analytics` when you need history. ## How it works - The query runs against ClickHouse, not PostgreSQL. Use ClickHouse SQL syntax (`JSONExtractString`, `toDate`, `argMax`, etc.). - When the user hasn't asked for a specific time frame, scope the query to the last 30 days with `AND timestamp >= now() - INTERVAL 30 DAY` to keep it fast and the results relevant. - Statements are read-only: INSERT / UPDATE / DELETE / DDL are rejected by ClickHouse. - Results are capped to the `maxResultRows` parameter (default 1024). Rows beyond the cap are dropped server-side, even if your SQL omits a `LIMIT`. # Analytics database (ClickHouse) Historical event log of every change to the CRM. **Read-only.** Query it to answer point-in-time and change-history questions like: - "What was the sequence of events that led to the current stage of this deal?" - "How long did this deal sit in the 'In progress' stage?" - "How many deals were created per day last week?" ## The `analytics.event` table (ClickHouse) Read-only SQL runs against ClickHouse, not PostgreSQL — use ClickHouse syntax (`JSONExtractString`, `toDate`, `argMax`, etc.). Every CRM record lives in ONE append-only CDC event log, `analytics.event` — NOT a table of current records; every create/update/delete is its own row. There is no `deal` / `company` / `person` table (`FROM deal` fails with "Unknown table expression identifier"). Always query `FROM analytics.event` and pick the entity with `WHERE entity_type = '<type>'`. Schema is inspired by PostHog: one wide event table with a JSON-stringified `properties` payload plus a structured `actor` column. Hot keys are promoted to materialized columns (below); everything else is read from `properties` with `JSONExtract*`. Every event carries a FULL snapshot of the record's fields in `properties` — create, update, and delete alike. An update is not a delta: it repeats every field the record has, not just the ones that changed. So the single latest event per entity already holds every current field, and you never need to stitch fields together across events. (The one exception: fields marked sensitive are omitted from `properties` entirely.) - `_id` (String) — Event id - `workspace_slug` (String) — Workspace (tenant) slug - `entity_type` (String) — Subject type: `deal`, `company`, `person`, `meeting`, `message`, or `c_<slug>` for a custom object - `entity_id` (String) — Subject record id - `type` (String) — Event type: `clarify:create` | `clarify:update` | `clarify:delete` (full enum below) - `timestamp` (DateTime64(6,'UTC')) — Event time; use `toDate(timestamp)` for day grouping - `properties` (String/JSON) — A full snapshot of the record's fields at event time (every field, not just the changed ones); read with `JSONExtractString/Float/Bool(properties, '<field>')` - `diff` (String/JSON) — On update events, the field-level changes this event applied: a JSON array of `{op, path, val, oldVal}` (`path` locates the field, `oldVal` → `val` is the transition). Empty (`''`) on create and no-op events. Use it to detect WHEN a field changed — see "Detecting when a field changed" - `actor` (Tuple) — `actor._id`, `actor.anonymous_id`, `actor.entity`, `actor.source_id` (all String, native paths — no `JSONExtract` needed); usable in `GROUP BY` / `ORDER BY` - `m_stage` (String) — Materialized `JSONExtractString(properties,'stage')`; empty if absent - `m_amount` (Float64) — Materialized `JSONExtractFloat(properties,'amount')`; `0` if absent - `m_close_date` (Nullable(Date)) — Materialized `toDateOrNull(properties.close_date)`; `NULL` if absent/unset. A native date — range-filter and group it directly (`m_close_date >= '2026-01-01'`, `toStartOfMonth(m_close_date)`) with no `toDate` wrapper ### Reading fields is ClickHouse, not PostgreSQL PostgreSQL JSONB operators `->` and `->>` do not exist in ClickHouse — `properties->>'description'` fails. Read fields with `JSONExtractString(properties, 'description')` (or `JSONExtractFloat` / `JSONExtractBool`). There is no `JSONExtractFloat64` — use `JSONExtractFloat`. If a query fails because a function does not exist, use the alternative ClickHouse suggests (e.g. `JSONExtractRaw`). ### Materialized columns Prefer the materialized columns `m_stage` / `m_amount` / `m_close_date` over `JSONExtract*(properties, 'stage'|'amount'|'close_date')` when the key matches — they are typed, indexed, and skip a JSON parse per row. They are populated from whatever `properties.stage` / `properties.amount` / `properties.close_date` carries on each row, regardless of `entity_type`, so they work for a custom object with those fields too. For `m_stage` / `m_amount`, empty / `0` means the event didn't carry the key. `m_close_date` instead uses `NULL` for an absent or unset close date (a date has no neutral sentinel), so test presence with `m_close_date IS NOT NULL`, not `!= ''`. `m_stage` (like every snapshot field) is the value the record held *when the event fired*, not a transition. Counting `m_stage = 'Won'` answers "records that were in Won while something happened to them" — an enrichment sweep, a note, or an owner change re-emits the unchanged stage — so it tracks activity, not outcomes. For "records that *entered* a stage", read `diff` instead (see "Detecting when a field changed"). ### Allowed `type` values - `CdcEventType` — `clarify:create`, `clarify:update`, `clarify:merge`, `clarify:delete`, `clarify:add-to-list`, `clarify:remove-from-list`, `clarify:set-relationship`, `clarify:unset-relationship`, `clarify:grant-access`, `clarify:update-access`, `clarify:revoke-access`, `clarify:meeting` ### Scope every query (this is what keeps it fast) The table is a `ReplacingMergeTree` ordered by `(workspace_slug, entity_type, entity_id, timestamp, _id)`. Filter from the left of that key so ClickHouse prunes the table: - Always make `workspace_slug = '<your workspace>'` the first `WHERE` condition — it is the leading sort-key column and prunes almost the whole table. Use the Workspace value from your context; if it isn't there, call the `get-current-user` tool to get it before querying. - Always filter by `entity_type` next; add `entity_id` too for single-record questions (that hits the sort-key prefix and reads a tiny slice). - Time-series / activity / trend queries must also carry a `timestamp` range (e.g. `timestamp >= now() - INTERVAL 90 DAY`) — both to scope the report and to bound the scan. Current-state reconstruction is the exception (below): it needs the full history per entity, so do NOT put a `timestamp` floor on it. - Filtering only by columns outside the sort key (`type`, `m_stage`, `m_amount`, `m_close_date`, or any `JSONExtract*` value) forces a full scan — pair them with the sort-key columns above. - Name the columns you need — avoid `SELECT *`. It returns the wide `data` payload and computes the `properties` JSON alias for every row; list just the columns the report uses (`entity_id`, `timestamp`, `m_stage`, …). - Prefer `GROUP BY` on low-cardinality columns (`entity_type`, `m_stage`, `toDate(timestamp)`, `entity_id`), not on a freeform `JSONExtractString(properties, '<field>')` of a high-cardinality field (a note, description, or free text) — that forces a JSON parse per row and explodes the group count. - When you only need to eyeball a few recent rows, bound the read with `ORDER BY timestamp DESC LIMIT <n>` instead of scanning the whole slice. - Date literals: prefer relative helpers (`now() - INTERVAL 1 MONTH`, `toStartOfMonth(now())`, `today() - 7`) — you have no reliable wall clock, and a hardcoded boundary silently drifts. A bare `timestamp >= '2026-04-01T00:00:00Z'` rejects the ISO `T`/`Z`; use space-separated `'2026-04-01 00:00:00'`, `parseDateTime64BestEffort('2026-04-01T00:00:00Z')`, or `CAST('2026-04-01T00:00:00Z' AS DateTime64(6, 'UTC'))`. ### Good vs bad query shapes - Scope by the sort key, don't filter on a column alone: - Bad: `SELECT count() FROM analytics.event WHERE m_stage = 'Won'` — no `workspace_slug` / `entity_type`, so it scans every workspace. - Good: `... WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND m_stage = 'Won'`. - Name columns, don't `SELECT *`: - Bad: `SELECT * FROM analytics.event WHERE ...`. - Good: `SELECT entity_id, timestamp, m_stage FROM analytics.event WHERE ...`. - Bound a trend with a time range: - Bad: `SELECT toDate(timestamp) AS day, count() FROM ... GROUP BY day` with no `timestamp` floor — scans all history. - Good: add `AND timestamp >= now() - INTERVAL 90 DAY`. - Group low-cardinality, cap exploratory reads: - Bad: `... GROUP BY JSONExtractString(properties, 'notes')`, or reading raw rows with no `LIMIT`. - Good: `... GROUP BY m_stage`, or `ORDER BY timestamp DESC LIMIT 20` to peek at recent rows. ### Reconstruct current state from the log To report on CURRENT state, rebuild it from the event history: - Every event stores a full snapshot of the record, so reconstruct current field values with plain `argMax(<field>, timestamp)` grouped by `entity_id` — never a `JSONHas` / `<field> != ''` / `!= 0` presence guard, which resurrects a stale earlier value for a field that was later cleared or set back to 0. Read a JSON field with `argMax(JSONExtractString(properties,'<field>'), timestamp)`, or a materialized column directly with `argMax(m_stage, timestamp)`. - Drop deleted records: `HAVING argMax(type, timestamp) != 'clarify:delete'`. - Reconstruct in a CTE, then filter/aggregate over the CTE — filtering a mutable field inside the per-entity scan changes which event counts as "latest" and produces wrong totals. ```sql WITH deal_current AS ( SELECT entity_id, argMax(m_stage, timestamp) AS stage, argMax(m_amount, timestamp) AS amount FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' GROUP BY entity_id HAVING argMax(type, timestamp) != 'clarify:delete' ) SELECT stage, count() AS deals, sum(amount) AS pipeline FROM deal_current WHERE stage NOT IN ('Closed Won', 'Closed Lost') GROUP BY stage ``` ### Count stage transitions in a period A snapshot count (`m_stage = 'Won'`) can't answer "how many deals were won this quarter" — it counts deals *touched* while already won. Count the transition instead: the events where `stage` moved into a closed value, plus deals created directly in one. The `UNION` branch is required because `diff` is empty on create — it catches deals imported straight into a closed stage. ```sql -- Deals that ENTERED a closed stage inside the window. WITH closed AS ( SELECT entity_id, timestamp, m_stage AS stage_at_event FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND type = 'clarify:update' AND arrayExists(d -> JSONExtractString(d, 'path', 1) = 'stage' AND JSONExtractString(d, 'val') IN ('Won', 'Lost'), JSONExtractArrayRaw(diff)) UNION ALL -- diff is empty on create: catches deals imported directly into a closed stage SELECT entity_id, timestamp, m_stage FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND type = 'clarify:create' AND m_stage IN ('Won', 'Lost') ) SELECT countIf(final_stage = 'Won') AS deals_won, count() AS deals_closed, countIf(final_stage = 'Won') / nullIf(count(), 0) AS win_rate FROM (SELECT entity_id, argMax(stage_at_event, timestamp) AS final_stage FROM closed GROUP BY entity_id) ``` The outer `argMax` collapses each deal to its last transition in the window, so a deal that goes Won → Lost inside it counts once, as Lost. There is no delete guard here on purpose — a deal won in the window was won even if the record was later deleted; to drop since-deleted deals, reconstruct current state (above) and keep only the `entity_id`s that are still live. Matching on `val` works because `stage` is not sensitive; a sensitive field's `val` reads `'REDACTED'` (its `path` is kept), so for those match on `path` presence alone. For a "closed per month" trend, bucket by the event `timestamp` — that is when the transition actually happened. One data limitation to surface, not hide: on a batch-imported workspace every `clarify:create` lands on the import date, so deals that closed before they were imported collapse onto that date — the log has no real historical close date for them. `m_close_date` does not fill that gap: it is the *expected* close date (often in the future), right for a pipeline-by-expected-close forecast but wrong as a "when did we win" bucket. ### Detecting when a field changed A field being non-empty on an event does NOT mean it changed on that event — every event repeats all fields, so an edit to one field re-emits the rest unchanged. Use the `diff` column: on an update it lists exactly the fields that changed, so "did this field change on this event" is a plain row filter. Unlike comparing snapshots across events, this composes with a `timestamp` range and stays fast. A field changed on an event when `diff` holds an entry whose first `path` element is that field: `arrayExists(d -> JSONExtractString(d, 'path', 1) = 'stage', JSONExtractArrayRaw(diff))`. The matching entry also carries the transition — `oldVal` → `val` — so you can report "moved from X to Y" without reading other events. Caveats: `diff` is populated on `clarify:update` events only — it is empty on `clarify:create`, so if you also need the value set at creation (e.g. a deal's first stage), `UNION` in the create event. A change to a sensitive field shows `val`/`oldVal` as `'REDACTED'` but keeps its `path`, so the change is still detectable. Do NOT count a stage question off the snapshot: `m_stage != ''` counts every edit to a record that has a stage, and `m_stage = 'Won'` counts every edit to an already-won deal — neither is a stage change. Match on `diff` instead (see "Count stage transitions in a period"). ### Join across entities Every entity lives in the same `analytics.event` table, so a cross-entity report is CTEs joined on a foreign key stored in `properties`. Reconstruct each entity's current state in its own CTE (the pattern above), then join on the id — a deal's `company_id` links to the company's `entity_id`. Scope the looked-up CTE to only the ids the join needs: add `AND entity_id IN (SELECT <fk> FROM <driving_cte>)` to its `WHERE`. `entity_id` is a sort-key column, so this prunes reconstruction to a tiny slice instead of rebuilding every record of that entity type — the difference between a many-second and a sub-second query. ```sql WITH deal_current AS ( SELECT entity_id, argMax(JSONExtractString(properties,'company_id'), timestamp) AS company_id, argMax(m_amount, timestamp) AS amount FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' GROUP BY entity_id HAVING argMax(type, timestamp) != 'clarify:delete' ), company_current AS ( SELECT entity_id, argMax(JSONExtractString(properties,'name'), timestamp) AS name FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'company' AND entity_id IN (SELECT company_id FROM deal_current) GROUP BY entity_id HAVING argMax(type, timestamp) != 'clarify:delete' ) SELECT c.name AS company, sum(d.amount) AS pipeline FROM deal_current d JOIN company_current c ON c.entity_id = d.company_id GROUP BY c.name ORDER BY pipeline DESC ``` ### Common pitfalls - `FROM deal` / `FROM company` — no per-entity tables exist. Query `analytics.event` and filter `entity_type`. - Reconstruction returns stale values — you added a `JSONHas` / presence guard. Use plain `argMax` (see "Reconstruct current state from the log"). - Wrong totals when filtering a mutable field — you filtered it inside the per-entity scan. Reconstruct in a CTE first, then filter over the CTE. - Slow cross-entity join — the looked-up CTE rebuilt every record of its entity type. Add `AND entity_id IN (SELECT <fk> FROM <driving_cte>)` so it only reconstructs the records the join needs. - `JSONExtractFloat64` does not exist — use `JSONExtractFloat`. ### Time-in-stage Select the stage-transition events with the `diff` filter (see "Detecting when a field changed"), and `UNION` in each deal's `clarify:create` event so the first stage's clock starts at creation. Then, over that filtered set, take each transition's gap to the next with `leadInFrame(timestamp) OVER (PARTITION BY entity_id ORDER BY timestamp ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)` — that gap is how long the deal held the stage. The frame is required: `leadInFrame` defaults to a frame ending at the current row and would never see the next event. The latest transition has no next event, so its `leadInFrame` is the zero date — treat that as "still in this stage" (`now()`). Don't treat every `clarify:update` as a transition — every event repeats the current stage whether or not it changed. ## Examples <example> -- Deals created per day in the last 7 days SELECT toDate(timestamp) AS day, count() AS created FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND type = 'clarify:create' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY day ORDER BY day </example> <example> -- Stage changes for a single deal (only the events where the stage actually -- changed — a non-empty stage alone is not a change, since every event repeats -- all fields). `diff` lists the fields an update changed, so keep the events -- whose diff touched `stage`; the matching entry carries the old→new value. SELECT timestamp, m_stage AS stage, arrayFirst(d -> JSONExtractString(d, 'path', 1) = 'stage', JSONExtractArrayRaw(diff)) AS stage_change, JSONExtractString(stage_change, 'oldVal') AS from_stage, JSONExtractString(stage_change, 'val') AS to_stage, actor._id AS actor_id FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND entity_id = '<deal-id>' AND type = 'clarify:update' AND arrayExists(d -> JSONExtractString(d, 'path', 1) = 'stage', JSONExtractArrayRaw(diff)) ORDER BY timestamp </example> <example> -- Stage-change events per day across all deals. `diff` records the fields each -- update changed, so a stage change = an update whose diff touched `stage`. No -- window function and no boundary caveat: each event is self-contained, so the -- timestamp range is exact. SELECT toDate(timestamp) AS day, count() AS stage_changes FROM analytics.event WHERE workspace_slug = '<your workspace>' AND entity_type = 'deal' AND type = 'clarify:update' AND arrayExists(d -> JSONExtractString(d, 'path', 1) = 'stage', JSONExtractArrayRaw(diff)) AND timestamp >= now() - INTERVAL 90 DAY GROUP BY day ORDER BY day </example>
Read-context
CLARIFY_MCP_READ_CONTEXTRead Clarify product knowledge and documentation. Use this whenever you need to understand a feature, apply best practices, or reference detailed technical documentation. Available contexts: - field-docs: Field type guidelines, AI prompt writing instructions, available relationship data, and examples for creating or updating custom fields - calendar-docs: Guide for the calendar tools: timezone handling, timed vs all-day events, resolving participants by name via CRM lookup, participant rules (always include the user), choosing which connected account a create lands on (other writes follow the event owner), update-replaces-not-merges semantics, recurrence (RRULE), notify_participants defaults, and event-ID conventions. - campaign-docs: Complete guide to email campaigns including structure, variables, enrollment, exit conditions, and best practices - artifact-docs: The required data rules for authoring an artifact: which store its SQL runs on, how to prove a query, and how to size a result for the frame, plus what makes a dashboard, QBR, or sales document effective. Read before you write SQL for a dashboard, report, or artifact. - list-docs: How to write a list's defining SQL: title alias, showing to-one relationships, and column restrictions