Developer guide: 16. AI and agents

The MCP server, agent runs and records, and the AI routes.

Embed
Preview of the card
<a href="https://lucidace.com/help/developer-guide-ai-and-agents"><img src="https://lucidace.com/help/_api/public/orgs/af34862a-c837-4478-8335-0505efe40459/spaces/2f4b888b-c4e6-488b-81bd-6e838fb12d2e/pages/cbae71fd-761b-4264-a76b-b635047c78d3/social-card.svg?v=3e7ae33eec8b" alt="Developer guide: 16. AI and agents" width="600" height="315"></a>

16. AI and agents

16.1 MCP: the hosted endpoint

$LUCIDA_API/mcp speaks the Model Context Protocol over streamable HTTP (JSON-RPC 2.0 in POST bodies, answers as server-sent events). It gives an AI client the same reads as the REST API plus write tools that need confirmation.

Auth: a personal account key (Authorization: Bearer lc_pat_...) only. Every project key (lc_sk_..., lc_pk_..., or a personal key bound to one project) is refused with 401 problem+json saying an account key is required. The project comes from ?project_id=<id> or the X-Lucida-Project header; without either the endpoint answers 400. A bad or refused key is 401 problem+json with WWW-Authenticate: Bearer realm="lucida", resource_metadata="<host>/.well-known/oauth-protected-resource", the same header the REST API sends. The key's own scopes always apply. Rate limited: 429 with Retry-After.

URL parameters:

Parameter

Effect

project_id

the project

readonly=1

hide the write tools

features=query,flag

only these tool families: query, cohort, person, replay, experiment, insight, web, draft, flag

tools=get_trends,get_funnel

only these tools, by exact name

Handshake (every request needs Accept: application/json, text/event-stream; tested):

U="$LUCIDA_API/mcp?project_id=$PROJECT_ID&readonly=1"
H='Accept: application/json, text/event-stream'

# 1. initialize (the endpoint is stateless: no session id is issued)
curl -sS -X POST "$U" -H "Authorization: Bearer $LUCIDA_ACCOUNT_KEY" -H "Content-Type: application/json" -H "$H" -d '{
  "jsonrpc":"2.0","id":1,"method":"initialize",
  "params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"my-agent","version":"1"}}}'
# event: message
# data: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"tools":{"listChanged":true},...},"protocolVersion":"2025-06-18","serverInfo":{"name":"lucida","version":"0.1.0"}}}
mcp() { curl -sS -X POST "$U" -H "Authorization: Bearer $LUCIDA_ACCOUNT_KEY" -H "Content-Type: application/json" -H "$H" -d "$1" | sed -n 's/^data: //p'; }

# 2. initialized notification (answer 202, no body)
mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}'
# 3. list tools, then call one
mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq '.result.tools | length'
mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_trends","arguments":{"events":["$pageview"],"from":"2026-11-01T00:00:00Z","to":"2026-11-10T00:00:00Z"}}}' | jq -r '.result.content[0].text'

The endpoint keeps no session between requests: every POST stands alone, so initialize and notifications/initialized are optional and you can call tools/list or tools/call directly. tools/list lists only the tools the account key's own scopes allow (it reads key_scopes from GET /v1/me), so a read-only key sees no write tools. Tool results are JSON text in result.content[0].text (an evidence object with tool, rows, links, data or the query ir); result.isError is true on failure. A validation error from a query tool names the tool argument to change, not the REST field behind it: get_trends: invalid arguments: argument `from`: must be before to rather than date_range.from. The tools that build a query this way (query_events, get_trends, get_funnel, get_retention, get_paths) map date_range.from/to to from/to, series to events (or event or events), series.math to math, start to start_event, and keep breakdown, interval, periods, steps and return_event. Query tools also set structuredContent and a chart view ui://lucida/chart for hosts that render it.

Tool sets seen with a full-scope account key: 238 tools without readonly=1, and one fewer than the 140 first counted (139) with it, because readonly=1 now also hides test_destination; every other read tool reports readOnlyHint: true. test_destination calls the vendor, so it reports readOnlyHint: false and openWorldHint: true. Count tools/list yourself rather than relying on these numbers. Read families (names):

Family

Tools

Query

query_events, run_lql, run_insight, get_trends, get_funnel, get_retention, get_paths, insight_actors, search_docs, search_taxonomy, list_definitions

Dashboards and insights

list_insights, get_insight, list_dashboards, get_dashboard, list_alerts, list_annotations, list_reports, get_report

People

list_persons, get_person, person_timeline, person_identity, list_cohorts, get_cohort, cohort_members, list_groups, get_group, group_timeline

Replay and heatmaps

find_replays, get_recording, summarize_session, list_playlists, get_playlist, playlist_recordings, list_heatmaps, get_heatmap, heatmap_points, heatmap_elements, friction_clusters, what_to_watch, list_scanners, search_observations, get_observation, scanner_status

Flags and experiments

list_flags, get_flag, evaluate_flags, flag_status, flag_usage, flag_blast_radius, flag_dependents, flag_evaluation_reasons, flag_activity, list_stale_flags, list_experiments, get_experiment, analyze_experiment, experiment_power

Web and revenue

web_overview, web_stats, web_digest, goal_candidates, marketing_diagnose, identity_fragmentation, bot_traffic, get_revenue, get_mrr, revenue_breakdown, get_deferred_revenue, list_conversion_goals

Data and pipeline

list_destinations, get_destination, destination_health, destination_runs, destination_dlq, list_export_schedules, list_export_runs, list_transformations, data_quality_health, list_ingestion_warnings, list_catalog_tables, list_endpoints, run_endpoint, list_metrics, describe_metric, run_metric

Access and guides

list_roles, list_project_members, get_access_settings, list_access_rules, get_hidden_data, list_guides, get_guide, get_guide_results, list_early_access, list_workflows

Write tools (hidden by readonly=1) include create_flag, update_flag, toggle_flag, update_flag_rollout, delete_flag, bulk_update_flags, create_insight, update_insight, add_insight_to_dashboard, create_dashboard_draft, create_cohort, update_cohort, create_alert, create_annotation, create_experiment, propose_experiment, update_experiment, experiment_lifecycle, ship_experiment, create_playlist, create_scanner, scan_recordings, request_scan, delete_replays, create_destination, update_destination, create_export_schedule, start_backfill, create_transformation, create_guide, publish_guide, update_event_definition, merge_events, merge_properties, set_person_properties, test_destination, create_workflow, claim_report, set_report_state, run_scout, create_endpoint, add_endpoint_version, create_metric, update_metric, create_usage_metric, update_usage_metric, delete_usage_metric, add_knowledge_text, add_knowledge_url, update_knowledge_source, propose_relationship, propose_table_certification. All of them go through the propose and confirmation_token flow below, and readonly=1 hides every one.

Confirmation tokens. Every write tool is a proposal first. The first call returns data.mutated: false, a summary, a confirmation_token and expires_at (10 minutes) and changes nothing. Show it to the user, then call the same tool with the same arguments plus confirmation_token. A token works once; reuse is isError: true with invalid or expired confirmation token. Tested with create_flag:

mcp '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"create_flag","arguments":{"key":"mcp-demo-flag","name":"MCP demo"}}}' \
  | jq -r '.result.content[0].text | fromjson | .data | {mutated,summary,confirmation_token}'
mcp '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"create_flag","arguments":{"key":"mcp-demo-flag","name":"MCP demo","confirmation_token":"<token>"}}}'

OAuth discovery (for clients that sign in instead of using a key): GET /.well-known/oauth-protected-resource (resource: <host>/v1, authorization_servers, scopes_supported) and GET /.well-known/oauth-authorization-server (authorization_endpoint /oauth/authorize, token_endpoint /v1/oauth/token, registration_endpoint /v1/oauth/register for dynamic client registration, device_authorization_endpoint /v1/oauth/device_authorization, revocation_endpoint /v1/oauth/revoke; grants authorization_code, refresh_token, device_code, jwt-bearer; PKCE S256). Every 401 carries a WWW-Authenticate header that points to the protected-resource document.

Client setup:

claude mcp add --transport http lucida "$LUCIDA_API/mcp?project_id=$PROJECT_ID&readonly=1" --header "Authorization: Bearer $LUCIDA_ACCOUNT_KEY"
lucida mcp add cursor --url "$LUCIDA_API/mcp" --readonly     # also: claude-code, vscode, windsurf, zed, codex, claude-desktop, claude-code-plugin
lucida mcp tools; lucida mcp exec get_trends --args '{"events":["$pageview"]}'   # local stdio, no HTTP client needed

More in MCP server.

16.2 AI routes

Method and path

Scope

Purpose

GET, PUT {p}/ai/share-settings

settings:read / admin

{full_results}: show every query result in a shared AI conversation even to viewers who could not run it (default false)

GET, PUT /v1/orgs/{org_id}/ai/settings

session only

organization AI provider and budget (keys cannot reach it)

GET, PUT {p}/replays/{session_id}/ai

read / write

AI summary of a replay

GET {p}/web/ai-traffic, web/ai-citations, web/ai-visibility

insight:read

how AI crawlers and AI search treat your site (section 14)

/v1/oauth/*, GET /v1/me/oauth-apps

session

OAuth clients and device flow for AI tools

When no AI provider is configured, AI narrative routes answer 503 with type .../ai-provider-required (connect one first: AI providers).

The AI providers a project may use (bring your own key) are configured in the app: AI providers.

16.3 Agent analytics: your own AI agent as a product

For agents and chatbots you ship to users. Send conversation events; Lucida computes outcomes, rephrases, rage prompts, topics and retention. Text is not collected unless you opt in (captureText). Events (POST $LUCIDA_CAPTURE/v1/batch):

Event

Properties

$ai_conversation_started

$ai_conversation_id (required), $ai_agent_name, $ai_agent_version, $ai_topic, $ai_use_case, $ai_trace_id (32 hex)

$ai_message

$ai_conversation_id, $ai_role (user or assistant), $ai_message_index, $ai_text_length; user messages also $ai_text_hash, $ai_sentiment (-1, 0, 1); $ai_text only with text capture

$ai_feedback

$ai_feedback_kind (thumbs, rating, comment), $ai_feedback_value (thumbs 1 or -1, rating 1 to 5)

$ai_conversation_ended, $ai_outcome

$ai_outcome: resolved, unresolved, escalated, abandoned, error; $ai_resolution

$ai_trace_id is the documented join key to Watchtower: put the W3C trace id of the agent run on $ai_conversation_started. Conversation rows then carry trace_id, a Watchtower deep link on the detail route, and cost_usd (the sum of the trace's Watchtower run costs, null until the watchtower connector's llm_runs stream has synced them).

Read (insight:read; all take from, to RFC 3339 and agent):

Route

Returns

GET {p}/agent-analytics/overview

conversations, users, adoption_pct, avg_user_turns, outcomes[], resolved_pct, unresolved_pct, abandoned_pct, rage_pct, feedback, by_day[], agents[]

GET {p}/agent-analytics/conversations

outcome, topic, rage, unresolved, feedback, limit, cursor; rows with conversation_id, outcome, topic, user_turns

GET {p}/agent-analytics/conversations/{conversation_id}

transcript (text only if captured and pii:read)

GET {p}/agent-analytics/feedback

kind, limit, cursor

GET {p}/agent-analytics/retention

period, periods, lookback_days (1 to 365): agent users against others

GET {p}/agent-analytics/topics, POST .../topics/run (insight:write)

topic clusters; run the labelling job now (needs an AI provider)

Tokens, latency, cost and traces of LLM calls belong to Watchtower; Lucida does not chart them. In the query language, an event step is {"type":"agent_conversation","status":"resolved","agent":"support-bot"} (status started, message, ended, resolved, unresolved, escalated, abandoned, rage, positive_feedback, negative_feedback).

16.4 Agent records and agent activity

Report what your own automation did, so it can be charted like any event. Both need insight:write, answer 202, and take agent_kind of scout or agent.

lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/agent-activity" -d '{
  "agent_kind":"agent","agent_id":"nightly-audit","agent_name":"Nightly audit","run_id":"<uuid>",
  "trigger":"schedule","status":"ok","signals":2,"steps":5,"duration_ms":1200}'
# {"uuid":"..."}   becomes a $lc_agent_run event; a run_id that is a UUID makes a retry dedupe

lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/agent-records" -d '{
  "agent_kind":"agent","agent_id":"nightly-audit","agent_name":"Nightly audit","run_id":"r-1",
  "records":[{"page":"/pricing","severity":2,"note":"confusing tiers"}]}'
# {"uuids":["..."]}  one $lc_agent_record event per record; fields appear as record_<name>

agent-activity fields: agent_id, agent_name (1 to 200 chars), trigger (schedule or manual), status (ok, error, budget, skipped), run_id, signals, steps, duration_ms, at. agent-records: 1 to 50 records per call, each a flat object of at most 20 fields; field names [a-z][a-z0-9_]* (40 chars), values a string (1000 chars), number or boolean.

16.5 Recommendations and support

Recommendation placements (/recs/*: settings, items, items/feed, placements, build, recommendations?placement=&item_id=&distinct_id=) belong with flags and experiments in the earlier part of this guide. Strategies are popular, trending, viewed_with, bought_with, recently_viewed.

Support: GET /v1/support/identity is a session-only route for the in-app chat widget; keys cannot call it. For human help, the in-app chat and the docs at /help are the channels. Programmatic agents should use search_docs over MCP.

16.6 Recipes for AI agents

Each recipe is an ordered list of calls. Section numbers refer to this guide; the setup and event sections come before section 13. Run every call with the account key unless it says capture.

1. Instrument a new SaaS app from zero

  1. POST /v1/orgs/$ORG_ID/projects with {"name":"acme.com"}; keep project.id, the public key (PK) and the send-only secret key (SK) from keys[] (kind public/secret; the secret value is shown once, so store it now). Mint broader secret keys with POST {p}/keys and explicit scopes only when you need them.

  2. Browser: npm i @lucida-analytics/browser, use createClient(PK, { apiHost: $LUCIDA_CAPTURE }) from @lucida-analytics/browser/core (no autocapture); server: @lucida-analytics/node with SK (15.6).

  3. Send one $pageview with $host, $pathname, $referrer, $session_id and a browser User-Agent; send signed_up and purchase from the server with uuids.

  4. GET {p}/events?limit=5 and GET {p}/web/realtime until both show data.

  5. POST {p}/web/goals for /signup (14.2); PUT {p}/web/settings with referrer_exclusions for your checkout domain (14.5).

  6. POST {p}/traffic-exclusions for staging hosts; lucida doctor --site https://acme.com to check the snippet and CSP.

2. Launch a flag-gated experiment and read the result

  1. POST {p}/metrics for the success metric; POST {p}/flags (multivariate) and read it with POST $LUCIDA_CAPTURE/v1/flags.

  2. POST {p}/experiments with variants and the metric; POST {p}/experiments/{id}/start.

  3. Find the people hurt by a variant: POST {p}/replays/search with "experiment":{"key":"<flag key>","variant":"test"},"min_frustration":1 and a date_range.

  4. GET {p}/experiments/{id}/results until srm is clean and the primary metric is decided; lucida experiments check <id> in CI.

  5. POST {p}/experiments/{id}/stop, then ship or roll back with the flag rollout route. Or the same through MCP propose_experiment, experiment_lifecycle, ship_experiment (16.1).

3. Build a growth dashboard

  1. GET {p}/web/breakdown?dimension=channel and dimension=page to see what exists (14.1).

  2. POST {p}/query for each chart; POST {p}/insights to save it (name, query).

  3. POST {p}/dashboards, then POST {p}/dashboards/{id}/tiles with {"insight_id":...} per insight.

  4. POST {p}/dashboards/{id}/shares with expires_in_days and give the url to the reader; keep the token private.

  5. POST {p}/insights/{id}/alerts/simulate, then POST {p}/insights/{id}/alerts to watch the key number.

4. Wire a webhook to a Slack-style receiver

  1. Deploy the receiver from 15.2 on a public https URL; set LUCIDA_WEBHOOK_SECRET after step 2.

  2. POST {p}/webhooks with the URL and events:["flag.changed","alert.fired"]; store the returned secret at once.

  3. POST {p}/webhooks/{id}/test; read GET {p}/webhooks/{id}/deliveries until status is delivered (a 405 or 401 shows in last_status).

  4. Toggle a flag (POST {p}/flags/{id}/toggle) and confirm a flag.changed delivery arrives; dedupe on the envelope id.

5. Migrate from PostHog

  1. export POSTHOG_PERSONAL_API_KEY=phx_..., export LC_SECRET_KEY=$SK.

  2. lucida import posthog --project <ph id> --dry-run --since 2025-01-01 --report plan.json; read what will not map.

  3. lucida import posthog --project <ph id> --only groups,cohorts,actions,flags,experiments,insights,dashboards.

  4. lucida import posthog --project <ph id> --only persons,events --since 2025-01-01 --checkpoint ph.ckpt (resumable).

  5. Install the Lucida SDK (15.6); replay history cannot be moved, new recordings start with the SDK. Verify with lucida flags list and lucida events list.

6. Find why users drop off a page and watch the evidence

  1. GET {p}/web/breakdown?dimension=exit_page to pick the page (14.1).

  2. GET {p}/heatmaps?url=/pricing&type=click and type=scroll, GET {p}/heatmaps/elements?url=/pricing for the elements people hit (13.9).

  3. POST {p}/replays/search with "url_visited":"/pricing","min_frustration":1,"order_by":"frustration"; for each id GET {p}/replays/{id}/transcript (13.3).

  4. Save the set: POST {p}/replay-playlists; add notes with POST {p}/replays/{id}/comments.

  5. Share: POST {p}/replay-playlists/{id}/shares. Optionally POST {p}/vision/scanners to keep asking the same question automatically (14.7).

7. Connect an ad platform and see paid performance

  1. GET {p}/connectors/catalog and pick the entry; read its config_schema (15.1).

  2. POST {p}/connectors with config and credentials; a 422 check failure means fix the credentials.

  3. POST {p}/connectors/{id}/test, then POST .../sync only on an account you own; GET .../runs for the result.

  4. GET {p}/web/ad-spend/report?goal_id=<goal> and GET {p}/web/attribution?goal_id=<goal>&models=linear,last_touch (14.3).

  5. No platform connector? POST {p}/web/ad-spend/import with a CSV (date,spend,channel,campaign).

8. Give an AI assistant read-only access to analytics

  1. Mint an account key limited to read scopes in the app (keys cannot create account keys).

  2. claude mcp add --transport http lucida "$LUCIDA_API/mcp?project_id=$PROJECT_ID&readonly=1" --header "Authorization: Bearer $KEY".

  3. The assistant runs tools/list, then get_trends, web_overview, find_replays, get_recording (16.1).

  4. For a change, it calls a write tool, shows the summary and token to you, and only calls again with confirmation_token after you approve.

9. Track your own AI agent's quality

  1. In the agent's server code send the events in 16.3 ($ai_conversation_started, $ai_message, $ai_feedback, $ai_conversation_ended with an $ai_outcome).

  2. GET {p}/agent-analytics/overview and .../conversations?unresolved=true to find failures.

  3. Report automation runs with POST {p}/agent-activity (16.4) and chart $lc_agent_run with POST {p}/query.

10. Prove a replay as evidence

  1. PUT {p}/replays/{id}/hold with {"hold":true} so it is never deleted.

  2. POST {p}/replays/{id}/evidence and save the bundle JSON.

  3. GET {p}/replay-evidence/key, then lucida replay verify bundle.json --public-key <key>.

Updated