Developer guide: 16. AI and agents
The MCP server, agent runs and records, and the AI routes.
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 |
|---|---|
| the project |
| hide the write tools |
| only these tool families: |
| 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 |
|
Dashboards and insights |
|
People |
|
Replay and heatmaps |
|
Flags and experiments |
|
Web and revenue |
|
Data and pipeline |
|
Access and guides |
|
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 neededMore in MCP server.
16.2 AI routes
Method and path | Scope | Purpose |
|---|---|---|
|
|
|
| session only | organization AI provider and budget (keys cannot reach it) |
| read / write | AI summary of a replay |
|
| how AI crawlers and AI search treat your site (section 14) |
| 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_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 |
|---|---|
|
|
|
|
| transcript (text only if captured and |
|
|
|
|
| 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
POST /v1/orgs/$ORG_ID/projectswith{"name":"acme.com"}; keepproject.id, the public key (PK) and the send-only secret key (SK) fromkeys[](kindpublic/secret; the secretvalueis shown once, so store it now). Mint broader secret keys withPOST {p}/keysand explicit scopes only when you need them.Browser:
npm i @lucida-analytics/browser, usecreateClient(PK, { apiHost: $LUCIDA_CAPTURE })from@lucida-analytics/browser/core(no autocapture); server:@lucida-analytics/nodewithSK(15.6).Send one
$pageviewwith$host,$pathname,$referrer,$session_idand a browser User-Agent; sendsigned_upandpurchasefrom the server withuuids.GET {p}/events?limit=5andGET {p}/web/realtimeuntil both show data.POST {p}/web/goalsfor/signup(14.2);PUT {p}/web/settingswithreferrer_exclusionsfor your checkout domain (14.5).POST {p}/traffic-exclusionsfor staging hosts;lucida doctor --site https://acme.comto check the snippet and CSP.
2. Launch a flag-gated experiment and read the result
POST {p}/metricsfor the success metric;POST {p}/flags(multivariate) and read it withPOST $LUCIDA_CAPTURE/v1/flags.POST {p}/experimentswith variants and the metric;POST {p}/experiments/{id}/start.Find the people hurt by a variant:
POST {p}/replays/searchwith"experiment":{"key":"<flag key>","variant":"test"},"min_frustration":1and adate_range.GET {p}/experiments/{id}/resultsuntilsrmis clean and the primary metric is decided;lucida experiments check <id>in CI.POST {p}/experiments/{id}/stop, then ship or roll back with the flag rollout route. Or the same through MCPpropose_experiment,experiment_lifecycle,ship_experiment(16.1).
3. Build a growth dashboard
GET {p}/web/breakdown?dimension=channelanddimension=pageto see what exists (14.1).POST {p}/queryfor each chart;POST {p}/insightsto save it (name,query).POST {p}/dashboards, thenPOST {p}/dashboards/{id}/tileswith{"insight_id":...}per insight.POST {p}/dashboards/{id}/shareswithexpires_in_daysand give theurlto the reader; keep thetokenprivate.POST {p}/insights/{id}/alerts/simulate, thenPOST {p}/insights/{id}/alertsto watch the key number.
4. Wire a webhook to a Slack-style receiver
Deploy the receiver from 15.2 on a public https URL; set
LUCIDA_WEBHOOK_SECRETafter step 2.POST {p}/webhookswith the URL andevents:["flag.changed","alert.fired"]; store the returnedsecretat once.POST {p}/webhooks/{id}/test; readGET {p}/webhooks/{id}/deliveriesuntilstatusisdelivered(a 405 or 401 shows inlast_status).Toggle a flag (
POST {p}/flags/{id}/toggle) and confirm aflag.changeddelivery arrives; dedupe on the envelopeid.
5. Migrate from PostHog
export POSTHOG_PERSONAL_API_KEY=phx_...,export LC_SECRET_KEY=$SK.lucida import posthog --project <ph id> --dry-run --since 2025-01-01 --report plan.json; read what will not map.lucida import posthog --project <ph id> --only groups,cohorts,actions,flags,experiments,insights,dashboards.lucida import posthog --project <ph id> --only persons,events --since 2025-01-01 --checkpoint ph.ckpt(resumable).Install the Lucida SDK (15.6); replay history cannot be moved, new recordings start with the SDK. Verify with
lucida flags listandlucida events list.
6. Find why users drop off a page and watch the evidence
GET {p}/web/breakdown?dimension=exit_pageto pick the page (14.1).GET {p}/heatmaps?url=/pricing&type=clickandtype=scroll,GET {p}/heatmaps/elements?url=/pricingfor the elements people hit (13.9).POST {p}/replays/searchwith"url_visited":"/pricing","min_frustration":1,"order_by":"frustration"; for each idGET {p}/replays/{id}/transcript(13.3).Save the set:
POST {p}/replay-playlists; add notes withPOST {p}/replays/{id}/comments.Share:
POST {p}/replay-playlists/{id}/shares. OptionallyPOST {p}/vision/scannersto keep asking the same question automatically (14.7).
7. Connect an ad platform and see paid performance
GET {p}/connectors/catalogand pick the entry; read itsconfig_schema(15.1).POST {p}/connectorswithconfigandcredentials; a422check failure means fix the credentials.POST {p}/connectors/{id}/test, thenPOST .../synconly on an account you own;GET .../runsfor the result.GET {p}/web/ad-spend/report?goal_id=<goal>andGET {p}/web/attribution?goal_id=<goal>&models=linear,last_touch(14.3).No platform connector?
POST {p}/web/ad-spend/importwith a CSV (date,spend,channel,campaign).
8. Give an AI assistant read-only access to analytics
Mint an account key limited to read scopes in the app (keys cannot create account keys).
claude mcp add --transport http lucida "$LUCIDA_API/mcp?project_id=$PROJECT_ID&readonly=1" --header "Authorization: Bearer $KEY".The assistant runs
tools/list, thenget_trends,web_overview,find_replays,get_recording(16.1).For a change, it calls a write tool, shows the
summaryand token to you, and only calls again withconfirmation_tokenafter you approve.
9. Track your own AI agent's quality
In the agent's server code send the events in 16.3 (
$ai_conversation_started,$ai_message,$ai_feedback,$ai_conversation_endedwith an$ai_outcome).GET {p}/agent-analytics/overviewand.../conversations?unresolved=trueto find failures.Report automation runs with
POST {p}/agent-activity(16.4) and chart$lc_agent_runwithPOST {p}/query.
10. Prove a replay as evidence
PUT {p}/replays/{id}/holdwith{"hold":true}so it is never deleted.POST {p}/replays/{id}/evidenceand save the bundle JSON.GET {p}/replay-evidence/key, thenlucida replay verify bundle.json --public-key <key>.