All connectors

PostHog

Official

PostHog

Connect PostHog so your agents can answer product questions from your analytics: how many people signed up this week, which pages they visit, what a customer did before contacting support, or which feature flags are rolled out and to whom. They can browse your projects, recent events and persons, open your saved insights, and run PostHog SQL (HogQL) queries for counts and trends.

Access is read-only: agents cannot capture events, change feature flags or edit insights. They see only what your personal API key and your PostHog role allow, and decrypted remote config payloads stay hidden. PostHog Cloud in the US and in the EU is supported; self-hosted PostHog is not yet.

Queries count against PostHog's rate limits and your project's hourly query budget, so agents favor a few targeted queries over large exports.

Connect your PostHog account.

Setup instructions

Connect PostHog

  1. Open Settings → User → Personal API keys in US Cloud or EU Cloud, then create a key.
  2. Select the organizations to share. Grant Read, with no Write, for Insight, Query, Person, Feature flag, Organization and Project.
  3. Copy the phx_ key. In Houston, choose the matching Cloud region, paste Personal API key and save.

Official API key guide.

Advanced

A key restricted to Projects cannot list organizations or projects. Supply project IDs yourself; they appear after /project/ in the URL and in project settings. Organization admins may need to permit personal keys.

If access fails, check the region, expiry and missing read scopes. The key always uses your own account's permissions. Self-hosted PostHog is unsupported.

Files

  • connector.luau
    -- PostHog Cloud REST and query API, read-only with a personal API key. Arguments and results keep PostHog's native field names.
    type Options = {[string]: any}
    type List = {path: string, query: {[string]: string | {string}}, fields: {string}, fixed: string?, about: string}
    
    local API = "https://" .. config.region
    -- Houston ends a call after 30 s and the sandbox has no clock, so each call splits 27 s across its requests:
    -- {headers, body} milliseconds. PostHog runs a query for at most 10 s, after up to 30 s in a queue when the project
    -- already runs 3. PostHog honors limit up to the 1,000-row cap, so a list's second page is rare and gets less.
    local QUERY_TIME = table.freeze({20000, 7000})
    local PAGE_TIMES = table.freeze({table.freeze({15000, 5000}), table.freeze({5000, 2000})})
    local MAX_BYTES = 4 * 1024 * 1024
    local DEFAULT_LIMIT, MAX_LIMIT, MAX_ROWS, MAX_HOGQL = 100, 1000, 1000, 32 * 1024
    local NULL = json.decode("null")
    local BOOLEAN = table.freeze({"true", "false"})
    local REFRESH = table.freeze({"force_cache", "blocking"})
    local INSIGHT_KINDS = table.freeze({"TRENDS", "FUNNELS", "RETENTION", "PATHS", "STICKINESS", "LIFECYCLE", "SQL", "JSON", "BI", "JOURNEYS"})
    local FLAG_TYPES = table.freeze({"boolean", "multivariant", "experiment", "remote_config"})
    local USER_FIELDS = table.freeze({"id", "first_name", "last_name", "email"})
    local INSIGHT_FIELDS = table.freeze({"id", "short_id", "name", "derived_name", "description", "query", "result", "columns", "types", "hasMore", "timezone",
    	"last_refresh", "is_cached", "query_status", "saved", "favorited", "tags", "created_at", "created_by", "last_modified_at"})
    -- PostHog decrypts remote config payloads for personal API keys; they often hold secrets, so they never leave Houston.
    local REDACTED = "(encrypted)"
    
    -- List rows keep these fields: lists drop project tokens, autocapture DOM elements and the dashboards, permissions
    -- and usage details that make PostHog's rows large.
    local lists: {[string]: List} = {
    	listOrganizations = {path = "/api/organizations/", query = {},
    		fields = {"id", "name", "slug", "created_at", "membership_level", "member_count"},
    		about = "Organizations the key can read: `{id, name, slug, created_at, membership_level, member_count}`. Needs organization:read and a key not limited to projects."},
    	listProjects = {path = "/api/organizations/{organization}/projects/", query = {search = "text"},
    		fields = {"id", "uuid", "organization", "project_id", "name", "timezone", "is_demo", "ingested_event", "tags"},
    		about = "Projects of one organization (opts.organization: an organization id, default \"@current\", the one last opened in PostHog): `{id, name, organization, timezone, is_demo, ingested_event, tags, ...}`. search matches names. Needs project:read and a key not limited to projects."},
    	listEvents = {path = "/api/projects/{project}/events/",
    		query = {event = "text", after = "text", before = "text", distinct_id = "text", person_id = "text", properties = "filters", include_person = BOOLEAN},
    		fields = {"id", "distinct_id", "event", "timestamp", "properties", "person"},
    		about = "Events, newest first: `{id, distinct_id, event, timestamp, properties, person?}`. Without after, only the last 24 hours. after and before take ISO 8601 times; event is an event name such as `$pageview`; person_id is a person uuid; include_person = true adds `person = {distinct_ids, properties, is_identified}`. Needs query:read. Prefer query for counts and aggregates."},
    	listPersons = {path = "/api/projects/{project}/persons/", query = {search = "text", distinct_id = "text", email = "text", properties = "filters"},
    		fields = {"id", "uuid", "name", "distinct_ids", "properties", "created_at", "last_seen_at"},
    		about = "Persons, newest first: `{id, uuid, name, distinct_ids, properties, created_at, last_seen_at}`. search matches email, name, person id or distinct id; email and distinct_id match exactly. Needs person:read."},
    	listInsights = {path = "/api/projects/{project}/insights/", fixed = "basic=true",
    		query = {search = "text", saved = BOOLEAN, insight = INSIGHT_KINDS},
    		fields = {"id", "short_id", "name", "derived_name", "description", "query", "saved", "favorited", "tags", "created_at", "created_by", "last_modified_at", "last_refresh", "last_viewed_at"},
    		about = "Insights without their results: `{id, short_id, name, derived_name, description, query, saved, favorited, tags, created_at, created_by, last_modified_at, last_refresh, last_viewed_at}`. search matches names, descriptions and tags; saved = true keeps saved insights; insight: " .. table.concat(INSIGHT_KINDS, ", ") .. ". Needs insight:read."},
    	listFeatureFlags = {path = "/api/projects/{project}/feature_flags/", query = {search = "text", key = "text", active = {"true", "false", "STALE"}, type = FLAG_TYPES},
    		fields = {"id", "key", "name", "active", "archived", "status", "filters", "ensure_experience_continuity", "evaluation_runtime", "is_remote_configuration",
    			"has_encrypted_payloads", "tags", "experiment_set", "version", "created_at", "created_by", "updated_at", "last_called_at"},
    		about = "Feature flags, archived ones excluded: `{id, key, name (its description), active, status, filters = {groups, multivariate, payloads}, evaluation_runtime, tags, created_by, last_called_at, ...}`. filters.groups are the release conditions with rollout_percentage. Encrypted payloads read \"" .. REDACTED .. "\". search matches keys and names; key matches exactly; active: true, false or \"STALE\"; type: " .. table.concat(FLAG_TYPES, ", ") .. ". Needs feature_flag:read."},
    }
    
    local function finite(value: any): boolean
    	return type(value) == "number" and value == value and math.abs(value) < 2 ^ 53
    end
    
    local function options(value: any, operation: string): Options
    	assert(value == nil or type(value) == "table", operation .. " options must be a table")
    	return table.clone((value or {}) :: Options)
    end
    
    local function noneLeft(args: Options, operation: string)
    	local unknown = next(args)
    	assert(unknown == nil, operation .. " received an unknown option " .. string.sub(tostring(unknown), 1, 64))
    end
    
    local function choice(value: any, field: string, values: {string}): string
    	if type(value) == "boolean" then value = tostring(value) end
    	assert(type(value) == "string" and table.find(values, value), field .. " must be one of " .. table.concat(values, ", "))
    	return value
    end
    
    -- A positive integer id given as a number or a string of digits, or nil.
    local function numeric(value: any): string?
    	local id = if finite(value) and value % 1 == 0 then string.format("%d", value) elseif type(value) == "string" then value else ""
    	return if #id <= 15 and string.match(id, "^[1-9]%d*$") then id else nil
    end
    
    -- A project is its numeric id, or "@current" for the project last opened in PostHog.
    local function projectId(value: any): string
    	local id = if value == "@current" then "@current" else numeric(value)
    	assert(id, "project must be a PostHog project id, such as 12345, or \"@current\"")
    	return id
    end
    
    local function organizationId(value: any): string
    	assert(value == "@current" or (type(value) == "string" and string.match(string.lower(value), "^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$")),
    		"organization must be a PostHog organization uuid or \"@current\"")
    	return value
    end
    
    local function queryValue(value: any, field: string, kind: string | {string}): string
    	if type(kind) == "table" then return choice(value, field, kind) end
    	if kind == "filters" then
    		assert(type(value) == "table" and #value > 0 and next(value, #value) == nil, field .. " must be a nonempty array of PostHog property filters")
    		return url.encode(json.encode(value))
    	end
    	local text = if finite(value) then tostring(value) else value
    	assert(type(text) == "string" and string.find(text, "%S") and #text <= 1000, field .. " must be a nonempty string of at most 1000 bytes")
    	return url.encode(text)
    end
    
    local function errorCode(err: any): any
    	return if type(err) == "table" then err.code else nil
    end
    
    local function fail(operation: string, status: number?, retryable: boolean, message: string): never
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = status, retryable = retryable, message = message})
    end
    
    -- PostHog errors are {type, code, detail, attr}.
    local function failure(operation: string, response: HttpResponse, bodyTime: number): never
    	local status = response.statusCode
    	local message = "PostHog HTTP " .. tostring(status)
    	if status >= 300 and status < 400 then
    		response.body:close()
    		message ..= ": unexpected redirect"
    	else
    		local read, prefix = pcall(function(): any return await(response.body:readPrefix(32 * 1024), bodyTime) end)
    		if not read and errorCode(prefix) == "cancelled" then error(prefix, 0) end
    		local ok, body = pcall(json.decode, if read then prefix else "")
    		if ok and type(body) == "table" then
    			if type(body.code) == "string" then message ..= " " .. string.sub(body.code, 1, 64) end
    			if type(body.attr) == "string" then message ..= " (" .. string.sub(body.attr, 1, 64) .. ")" end
    			if type(body.detail) == "string" then message ..= ": " .. string.sub(string.gsub(body.detail, "%s+", " "), 1, 500) end
    		end
    	end
    	if status == 401 then
    		message ..= " (check the personal API key and the connection's cloud region; keys can expire or be revoked)"
    	elseif status == 403 then
    		message ..= " (the key may lack this function's read scope, or access to this organization or project)"
    	end
    	local retry = response.headers["retry-after"]
    	if status == 429 and retry and retry[1] then
    		local value = string.sub(retry[1], 1, 32)
    		message ..= "; retry after " .. value .. (if string.match(value, "^%d+$") then "s" else "")
    	end
    	return fail(operation, status, status == 429 or status >= 500, message)
    end
    
    -- Returns a successful response's body, read within budget bytes and times = {headers, body} milliseconds.
    local function fetch(operation: string, request: HttpRequest, times: {number}, budget: number, tooMuch: string): string
    	local headersTime, bodyTime = times[1], times[2]
    	request.timeoutMs = headersTime
    	local sent, response = pcall(function(): any return await(http.request(request)) end)
    	if not sent then
    		if errorCode(response) ~= "timeout" then error(response, 0) end
    		fail(operation, nil, true, "PostHog did not answer within " .. tostring(headersTime // 1000) .. " s; retry")
    	end
    	if response.statusCode < 200 or response.statusCode >= 300 then failure(operation, response, bodyTime) end
    	local read, raw = pcall(function(): any return await(response.body:readAll(budget), bodyTime) end)
    	if not read then
    		local code = errorCode(raw)
    		if code == "limit_exceeded" then
    			fail(operation, response.statusCode, false, "PostHog returned more than " .. tostring(MAX_BYTES // 1048576) .. " MiB, more than one call can hold; " .. tooMuch)
    		elseif code == "timeout" then
    			fail(operation, response.statusCode, true, "PostHog did not finish sending its answer within " .. tostring(bodyTime // 1000) .. " s; retry")
    		elseif code == "cancelled" then
    			error(raw, 0)
    		end
    		local detail = if type(raw) == "table" and type(raw.message) == "string" then raw.message else tostring(raw)
    		fail(operation, response.statusCode, true, "PostHog response failed: " .. string.sub(detail, 1, 300))
    	end
    	return raw
    end
    
    local function object(operation: string, raw: string): any
    	local ok, value = false, nil
    	if string.match(raw, "^%s*{") then ok, value = pcall(json.decode, raw) end
    	if not ok or type(value) ~= "table" then fail(operation, 200, false, "PostHog returned an unexpected response") end
    	return value
    end
    
    local function pick(value: any, fields: {string}): any
    	if type(value) ~= "table" then return value end
    	local kept: Options = {}
    	for _, field in fields do kept[field] = value[field] end
    	return kept
    end
    
    local function row(value: any, fields: {string}): any
    	local kept = pick(value, fields)
    	if type(kept) ~= "table" then return kept end
    	if kept.created_by ~= nil then kept.created_by = pick(kept.created_by, USER_FIELDS) end
    	local filters = kept.filters
    	if kept.has_encrypted_payloads == true and type(filters) == "table" and type(filters.payloads) == "table" then
    		for key in filters.payloads do filters.payloads[key] = REDACTED end
    	end
    	return kept
    end
    
    -- The query of a next link to path, keeping only the list's own options and offset and restoring its fixed one; nil
    -- when it is not such a link. PostHog's links repeat the request's options with offset, or before for events.
    local function cursor(link: any, spec: List, path: string): {string}?
    	local linked, query
    	if type(link) == "string" and #link <= 8192 then linked, query = string.match(link, "^[^?#%s]-(/api/[^?#%s]*)%?([^#%s]+)$") end
    	if linked ~= path or query == nil then return nil end
    	local parts: {string} = {}
    	for part in string.gmatch(query, "[^&]+") do
    		local name = string.match(part, "^([%w_]+)=")
    		if name == "offset" then
    			if not string.match(part, "^offset=%d+$") then return nil end
    			table.insert(parts, part)
    		elseif name and spec.query[name] then
    			table.insert(parts, part)
    		elseif name ~= "limit" and not (spec.fixed and part == spec.fixed) then
    			return nil
    		end
    	end
    	if spec.fixed then table.insert(parts, spec.fixed :: string) end
    	return parts
    end
    
    -- One page of size rows: PostHog's object with a results array, and the bytes it took.
    local function page(name: string, path: string, query: {string}, size: number, times: {number}, budget: number): (any, number)
    	local parts = table.clone(query)
    	table.insert(parts, "limit=" .. tostring(size))
    	local raw = fetch(name, {method = "GET", url = API .. path .. "?" .. table.concat(parts, "&"), headers = {Accept = {"application/json"}}},
    		times, budget, "pass a lower limit")
    	local value = object(name, raw)
    	if type(value.results) ~= "table" then fail(name, 200, false, "PostHog returned an unexpected response") end
    	return value, #raw
    end
    
    local function list(name: string, spec: List, project: any, input: any): any
    	local args = options(input, name)
    	local path = spec.path
    	if string.find(path, "{project}", 1, true) then
    		path = string.gsub(path, "{project}", projectId(project))
    	elseif string.find(path, "{organization}", 1, true) then
    		path = string.gsub(path, "{organization}", organizationId(if args.organization == nil then "@current" else args.organization))
    		args.organization = nil
    	end
    	local limit = DEFAULT_LIMIT
    	if args.limit ~= nil then
    		limit = args.limit
    		assert(finite(limit) and limit % 1 == 0 and limit >= 1 and limit <= MAX_LIMIT, "limit must be an integer from 1 to " .. tostring(MAX_LIMIT))
    	end
    	args.limit = nil
    	local query: {string} = {}
    	if args.next ~= nil then
    		local parts = cursor(args.next, spec, path)
    		assert(parts, "next must be the next link of an earlier " .. name .. " page of the same project or organization")
    		args.next = nil
    		assert(next(args) == nil, name .. " takes only limit with next, which keeps the other options")
    		query = parts
    	else
    		for field, kind in spec.query do
    			if args[field] ~= nil then table.insert(query, field .. "=" .. queryValue(args[field], field, kind)) end
    			args[field] = nil
    		end
    		noneLeft(args, name)
    		if spec.fixed then table.insert(query, spec.fixed :: string) end
    		table.sort(query)
    	end
    	local results: {any} = json.decode("[]")
    	local count, link = nil, NULL
    	local function add(value: any)
    		for _, item in value.results do table.insert(results, row(item, spec.fields)) end
    		if count == nil and finite(value.count) then count = value.count end
    		link = if type(value.next) == "string" then value.next else NULL
    	end
    	local first, used = page(name, path, query, limit, PAGE_TIMES[1], MAX_BYTES)
    	add(first)
    	-- A short first page continues once with the time and bytes left. When that fails, the first page comes back
    	-- with its next link, so a retry does not repeat it.
    	local parts = if link ~= NULL and #results < limit and used < MAX_BYTES then cursor(link, spec, path) else nil
    	if parts then
    		local ok, more = pcall(page, name, path, parts, limit - #results, PAGE_TIMES[2], MAX_BYTES - used)
    		if ok then
    			add(more)
    		elseif errorCode(more) == "cancelled" then
    			error(more, 0)
    		end
    	end
    	return {results = results, next = link, count = count}
    end
    
    local function getInsight(project: any, id: any, input: any): any
    	local args = options(input, "getInsight")
    	local insight = numeric(id) or (if type(id) == "string" and string.match(id, "^%w%w%w%w%w%w%w%w$") then id else nil)
    	assert(insight, "id must be an insight's numeric id or 8-character short_id")
    	local query = ""
    	if args.refresh ~= nil then query = "?refresh=" .. choice(args.refresh, "refresh", REFRESH) end
    	args.refresh = nil
    	noneLeft(args, "getInsight")
    	return row(object("getInsight", fetch("getInsight", {method = "GET", url = API .. "/api/projects/" .. projectId(project) .. "/insights/" .. insight .. "/" .. query,
    		headers = {Accept = {"application/json"}}}, QUERY_TIME, MAX_BYTES, "the insight's results are too large; run a narrower query instead")), INSIGHT_FIELDS)
    end
    
    local function runQuery(project: any, hogql: any, input: any): any
    	local args = options(input, "query")
    	local path = "/api/projects/" .. projectId(project) .. "/query/"
    	assert(type(hogql) == "string" and string.find(hogql, "%S") and #hogql <= MAX_HOGQL, "hogql must be a nonempty HogQL query of at most " .. tostring(MAX_HOGQL // 1024) .. " KiB")
    	local values = args.values
    	if values ~= nil then
    		assert(type(values) == "table", "values must be an object of placeholder values")
    		for key in values do assert(type(key) == "string", "values must be an object of placeholder values") end
    	end
    	local label = args.name
    	assert(label == nil or (type(label) == "string" and (utf8.len(label) or 129) <= 128), "name must be a string of at most 128 characters")
    	args.values, args.name = nil, nil
    	noneLeft(args, "query")
    	local body = json.encode({query = {kind = "HogQLQuery", query = hogql, values = values}, refresh = "blocking", name = label or "houston"})
    	local value = object("query", fetch("query", {method = "POST", url = API .. path,
    		headers = {Accept = {"application/json"}, ["Content-Type"] = {"application/json"}}, body = body},
    		QUERY_TIME, MAX_BYTES, "add a lower LIMIT or select fewer columns"))
    	local rows = value.results
    	if type(rows) ~= "table" then
    		if type(value.query_status) == "table" then fail("query", 200, true, "PostHog is still running the query; retry") end
    		fail("query", 200, false, "PostHog returned an unexpected response")
    	end
    	local truncated = #rows > MAX_ROWS
    	if truncated then
    		local kept: {any} = json.decode("[]")
    		for index = 1, MAX_ROWS do kept[index] = rows[index] end
    		rows = kept
    	end
    	return {columns = value.columns, types = value.types, results = rows, hasMore = value.hasMore, truncated = truncated}
    end
    
    local functions: {[string]: any} = {getInsight = getInsight, query = runQuery}
    for name, spec in lists do
    	if string.find(spec.path, "{project}", 1, true) then
    		functions[name] = function(project: any, opts: Options?): any return list(name, spec, project, opts) end
    	else
    		functions[name] = function(opts: Options?): any return list(name, spec, nil, opts) end
    	end
    end
    
    function functions.help(): string
    	local sections = {"PostHog (" .. string.sub(API, 9) .. "): read-only access to the organizations, projects, events, persons, insights and feature flags this personal API key can read, and HogQL queries. Credentials stay on Houston. Calls return completed values; do not wrap them in await(). Results keep PostHog's field names. Invalid input and unknown options fail before any request.",
    		"project is a numeric project id (from listProjects, or the number after /project/ in PostHog's address) or \"@current\", the project last opened in PostHog.",
    		"Lists take opts.limit (default " .. tostring(DEFAULT_LIMIT) .. ", at most " .. tostring(MAX_LIMIT) .. " rows) and return `{results, next, count?}`; a call follows PostHog's pages until it has limit rows, making at most " .. tostring(#PAGE_TIMES) .. " requests; when the second fails, the first page comes back with its next link. While next is not null, pass `{next = page.next, limit?}` to continue (for listProjects, with the same organization): next keeps the other options, and a link from another list, project or organization is refused. Rows are compact; created_by is `{id, first_name, last_name, email}`.",
    		"Errors carry the HTTP status, PostHog's code and detail. HTTP 403 usually means the key lacks the function's read scope, or is limited to other projects; keys limited to projects cannot list organizations or projects. HTTP 429 and 5xx are retryable. PostHog allows a personal API key 240 analytics requests a minute and 1,200 an hour (events, persons, insights), and queries draw on the project's hourly read budget (HTTP 429 api_queries_budget_exceeded): make few calls with filters rather than many. Each call reads at most " .. tostring(MAX_BYTES // 1048576) .. " MiB in all and gives PostHog " .. tostring((QUERY_TIME[1] + QUERY_TIME[2]) // 1000) .. " s in all; a call that runs out of time fails as retryable."}
    	local names: {string} = {}
    	for name in lists do table.insert(names, name) end
    	table.sort(names)
    	for _, name in names do
    		local spec = lists[name]
    		local signature = if string.find(spec.path, "{project}", 1, true) then "(project, opts?)" else "(opts?)"
    		local fields: {string} = {}
    		for field in spec.query do table.insert(fields, field) end
    		if name == "listProjects" then table.insert(fields, "organization") end
    		table.sort(fields)
    		table.insert(fields, "limit")
    		table.insert(fields, "next")
    		table.insert(sections, "## " .. name .. signature .. "\n\nGET " .. spec.path .. ". " .. spec.about .. " opts: " .. table.concat(fields, ", ") .. ".")
    	end
    	table.insert(sections, "## getInsight(project, id, opts?)\n\nGET /api/projects/{project}/insights/{id}/. One insight by numeric id or 8-character short_id (the code in its PostHog address): `{id, short_id, name, derived_name, description, query, result, columns, types, hasMore, timezone, last_refresh, is_cached, query_status, saved, favorited, tags, created_at, created_by, last_modified_at}`; result holds the calculated data. opts.refresh: \"force_cache\" (default, never calculates; result is null when nothing is cached) or \"blocking\" (calculates unless fresh results exist, drawing on the read budget). Needs insight:read.")
    	table.insert(sections, "## query(project, hogql, opts?)\n\nPOST /api/projects/{project}/query/ with kind HogQLQuery: one HogQL (PostHog SQL) SELECT, run synchronously. Returns `{columns, types, results, hasMore, truncated}`: results is an array of rows, each an array in columns order. PostHog returns 100 rows unless the query has its own LIMIT; this connector keeps at most " .. tostring(MAX_ROWS) .. " rows (truncated = true when it cut more). opts.values maps `{placeholder}` names in the query to values, for example `query(p, \"select count() from events where event = {name}\", {values = {name = \"$pageview\"}})`; opts.name labels the query in PostHog's query_log (default \"houston\"). Tables include events (event, timestamp, distinct_id, properties.$browser, person.properties.email), persons, sessions and groups. Always filter on timestamp and aggregate in SQL; this is for analysis, not exports, and OFFSET is refused for API keys: page on timestamp instead. Queries run for at most 10 s. Needs query:read.")
    	table.insert(sections, [[## Example
    
    Here posthog is the configured PostHog connection.
    
    ```lua
    local projects = posthog.listProjects()
    if not projects.results[1] then return "no projects" end
    local project = projects.results[1].id
    local daily = posthog.query(project, "select toDate(timestamp) as day, count() as pageviews from events where event = '$pageview' and timestamp > now() - interval 7 day group by day order by day")
    -- daily.columns == {"day", "pageviews"}; daily.results[1] == {"2026-10-24", 1234}
    local flags = posthog.listFeatureFlags(project, {active = true, limit = 50})
    local events = posthog.listEvents(project, {event = "$pageview", after = "2026-10-29T00:00:00Z", limit = 200})
    if type(events.next) == "string" then
    	local more = posthog.listEvents(project, {next = events.next, limit = 200})
    end
    ```
    
    Reference: https://posthog.com/docs/api and https://posthog.com/docs/sql]])
    	return table.concat(sections, "\n\n")
    end
    
    return functions
    
  • houston.json
    {
      "schema_version": 2,
      "name": "PostHog",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "config": {
        "region": {
          "type": "string",
          "label": "Cloud region",
          "description": "Where your PostHog organization is hosted: the address you use to open PostHog.",
          "default": "us.posthog.com",
          "options": [
            {
              "label": "US Cloud (us.posthog.com)",
              "value": "us.posthog.com"
            },
            {
              "label": "EU Cloud (eu.posthog.com)",
              "value": "eu.posthog.com"
            }
          ]
        }
      },
      "auth": {
        "token": {
          "type": "manual",
          "label": "Personal API key",
          "config": {
            "token": {
              "type": "secret",
              "label": "Personal API key",
              "description": "A PostHog personal API key with read scopes, starting with phx_.",
              "required": true
            }
          }
        }
      },
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "{{config.region}}"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/api/organizations/",
              "/api/organizations/{organization_id}/projects/",
              "/api/projects/{project_id}/events/",
              "/api/projects/{project_id}/feature_flags/",
              "/api/projects/{project_id}/insights/",
              "/api/projects/{project_id}/insights/{id}/",
              "/api/projects/{project_id}/persons/"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        },
        {
          "match": {
            "protocol": "http",
            "host": [
              "{{config.region}}"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/api/projects/{project_id}/query/"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Read PostHog events, persons, insights and feature flags, and run SQL queries on your product analytics.
    ---
    
    # PostHog
    
    Connect PostHog so your agents can answer product questions from your analytics:
    how many people signed up this week, which pages they visit, what a customer did
    before contacting support, or which feature flags are rolled out and to whom.
    They can browse your projects, recent events and persons, open your saved
    insights, and run PostHog SQL (HogQL) queries for counts and trends.
    
    Access is read-only: agents cannot capture events, change feature flags or edit
    insights. They see only what your personal API key and your PostHog role allow,
    and decrypted remote config payloads stay hidden. PostHog Cloud in the US and in
    the EU is supported; self-hosted PostHog is not yet.
    
    Queries count against PostHog's rate limits and your project's hourly query
    budget, so agents favor a few targeted queries over large exports.
    
    [Connect your PostHog account](SETUP.md).
    
  • SETUP.md
    # Connect PostHog
    
    1. Open **Settings → User → Personal API keys** in
       [US Cloud](https://us.posthog.com/settings/user-api-keys) or
       [EU Cloud](https://eu.posthog.com/settings/user-api-keys), then create a key.
    2. Select the organizations to share. Grant **Read**, with no Write, for
       **Insight**, **Query**, **Person**, **Feature flag**, **Organization** and **Project**.
    3. Copy the `phx_` key. In Houston, choose the matching **Cloud region**, paste
       **Personal API key** and save.
    
    [Official API key guide](https://posthog.com/docs/api/personal-api-keys).
    
    ## Advanced
    
    A key restricted to **Projects** cannot list organizations or projects. Supply
    project IDs yourself; they appear after `/project/` in the URL and in project
    settings. Organization admins may need to permit personal keys.
    
    If access fails, check the region, expiry and missing read scopes. The key always
    uses your own account's permissions. Self-hosted PostHog is unsupported.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = { token = "synthetic-method-secret" },
      				config = {},
      				endpoint = { "GET", "https://us.posthog.com/api/organizations/" },
      				expected = "Bearer synthetic-method-secret",
      				header = "Authorization",
      				method = "token",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {}, config = {region = "eu.posthog.com"}, auth_method = "token", auth_config = {token = "phx_fixture-private-key"}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		raise = nil
      		urls = {}
      		http = {request = function(req)
      			calls += 1
      			table.insert(urls, req.url)
      			assert(req.headers.Authorization == nil, "credentials must remain in the proxy")
      			if raise then error(raise, 0) end
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(posthog)
      		local function upstream(code, body, headers, call, expected, absent)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(call)
      			assert(not ok, "the call should have failed")
      			for _, text in expected do
      				assert(string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end
      			assert(calls == before + 1, "a failed request was repeated")
      		end
      		local function events() posthog.listEvents(12345) end
      		local function query() posthog.query(12345, "select 1") end
      		local function insight() posthog.getInsight(12345, 7) end
      
      		status, payload = 200, '{"count":0,"next":null,"previous":null,"results":[]}'
      		posthog.listOrganizations()
      		assert(urls[#urls] == "https://eu.posthog.com/api/organizations/?limit=100", urls[#urls])
      		status, payload = 200, '{"columns":[],"types":[],"results":[],"hasMore":false}'
      		query()
      		assert(urls[#urls] == "https://eu.posthog.com/api/projects/12345/query/", urls[#urls])
      
      		upstream(401, '{"type":"authentication_error","code":"authentication_failed","detail":"Personal API key found in request Authorization header is invalid.","attr":null}', {}, events,
      			{"PostHog HTTP 401 authentication_failed: Personal API key found", "check the personal API key", "cloud region", '"retryable":false', '"upstream_status":401'})
      		upstream(403, '{"type":"authentication_error","code":"permission_denied","detail":"API key missing required scope \'query:read\'","attr":null}', {}, query,
      			{"HTTP 403 permission_denied: API key missing required scope 'query:read'", "read scope", '"retryable":false'})
      		upstream(403, '{"type":"authentication_error","code":"permission_denied","detail":"API keys with scoped projects are only supported on project-based endpoints.","attr":null}', {},
      			function() posthog.listProjects() end, {"scoped projects", "access to this organization or project"})
      		upstream(404, '{"type":"invalid_request","code":"not_found","detail":"Not found.","attr":null}', {}, insight, {"HTTP 404 not_found: Not found."}, "read scope")
      		upstream(400, '{"type":"validation_error","code":"invalid_input","detail":"Unable to resolve field: nope","attr":"query"}', {}, query,
      			{"HTTP 400 invalid_input (query): Unable to resolve field: nope", '"retryable":false'})
      		upstream(400, '{"type":"validation_error","code":"invalid_input","detail":"' .. string.rep("x", 1000) .. '"}', {}, query,
      			{"invalid_input: " .. string.rep("x", 500)}, string.rep("x", 501))
      		upstream(400, '{"type":"validation_error","code":"invalid_input","detail":"' .. string.rep("x", 5000) .. '"}', {}, query,
      			{"invalid_input: " .. string.rep("x", 500)}, string.rep("x", 501))
      		upstream(400, '{"type":"validation_error","code":"invalid_input","detail":"' .. string.rep("x", 40000) .. '"}', {}, query, {"PostHog HTTP 400"}, "xxx")
      		upstream(429, '{"type":"throttled_error","code":"api_queries_budget_exceeded","detail":"Hourly read budget exhausted."}', {["retry-after"] = {"120"}}, query,
      			{"HTTP 429 api_queries_budget_exceeded", "retry after 120s", '"retryable":true'})
      		upstream(429, '{"type":"throttled_error","code":"throttled","detail":"Request was throttled."}', {["retry-after"] = {"Fri, 30 Oct 2026 07:00:00 GMT"}}, events,
      			{"retry after Fri, 30 Oct 2026 07:00:00 GMT", '"retryable":true'}, "GMTs")
      		upstream(502, "<html>Bad gateway</html>", {}, events, {"PostHog HTTP 502", '"retryable":true'}, "html")
      		upstream(302, "", {location = {"https://eu.posthog.com/login"}}, events, {"HTTP 302: unexpected redirect"}, "login")
      		upstream(200, "<html>Maintenance</html>", {}, events, {"unexpected response", '"retryable":false'})
      		upstream(200, "[]", {}, insight, {"unexpected response"})
      		upstream(200, '{"next":null,"results":null}', {}, events, {"unexpected response"})
      		upstream(200, '{"query_status":{"id":"q1","complete":false}}', {}, query, {"still running the query", '"retryable":true'})
      		upstream(200, '{"columns":[]}', {}, query, {"unexpected response", '"retryable":false'})
      		upstream(200, '{"results":[' .. string.rep('"x",', 4 * 1024 * 1024 // 4) .. '"x"]}', {}, query, {"more than 4 MiB", "lower LIMIT", '"retryable":false'})
      
      		local before = calls
      		raise = {code = "timeout", message = "operation timed out"}
      		local ok, err = pcall(events)
      		assert(not ok and string.find(tostring(err), "did not answer within 15 s", 1, true) and string.find(tostring(err), '"retryable":true', 1, true), tostring(err))
      		raise = {code = "cancelled", message = "cancelled"}
      		ok, err = pcall(events)
      		assert(not ok and not string.find(tostring(err), "PostHog", 1, true), "cancellation must pass through unchanged: " .. tostring(err))
      		assert(calls == before + 2, "a failed request was repeated")
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		-- TestPostHogReadOnlyRoutes
      		do
      			do
      				local _, err = m.resolve(nil, nil, nil, "token")
      				if err == nil then
      					m.fail("accepted missing personal API key")
      				end
      			end
      			do
      				local _, err = m.resolve(
      					nil,
      					{ region = "posthog.example.com" },
      					{ token = "phx_fixture" },
      					"token"
      				)
      				if err == nil then
      					m.fail("accepted a host outside the cloud regions")
      				end
      			end
      			for region, other in
      				{ ["us.posthog.com"] = "eu.posthog.com", ["eu.posthog.com"] = "us.posthog.com" }
      			do
      				local r, err = m.resolve(nil, { region = region }, { token = "phx_fixture" }, "token")
      				assert(not err, tostring(err))
      				local host = "https://" .. region
      				local project = host .. "/api/projects/12345"
      				m.routes(r, "Bearer phx_fixture", true, {
      					"GET " .. host .. "/api/organizations/?limit=100",
      					"GET " .. host .. "/api/organizations/@current/projects/?limit=100",
      					"GET "
      						.. host
      						.. "/api/organizations/0188430e-316e-0000-51a6-fd646548690e/projects/?limit=100&offset=100",
      					"GET " .. project .. "/events/?event=%24pageview&limit=100",
      					"GET " .. project .. "/persons/?search=ana&limit=100",
      					"GET " .. project .. "/insights/?basic=true&limit=100",
      					"GET " .. project .. "/insights/AaVQ8Ijw/?refresh=blocking",
      					"GET " .. project .. "/feature_flags/?active=true&limit=50",
      					"GET " .. host .. "/api/projects/@current/events/?limit=1",
      					"POST " .. project .. "/query/",
      				})
      				m.routes(r, "Bearer phx_fixture", false, {
      					"POST " .. project .. "/insights/",
      					"PATCH " .. project .. "/insights/1/",
      					"DELETE " .. project .. "/persons/1/",
      					"POST " .. project .. "/feature_flags/",
      					"PATCH " .. project .. "/feature_flags/1/",
      					"GET " .. project .. "/feature_flags/1/",
      					"GET " .. project .. "/query/abc/",
      					"DELETE " .. project .. "/query/abc/",
      					"GET " .. project .. "/query/",
      					"POST " .. project .. "/events/",
      					"GET " .. project .. "/events/018f/",
      					"GET " .. project .. "/persons/1/",
      					"GET " .. host .. "/api/projects/",
      					"GET " .. project .. "/",
      					"GET " .. host .. "/api/users/@me/",
      					"GET " .. host .. "/api/personal_api_keys/",
      					"POST " .. host .. "/api/organizations/",
      					"GET " .. project .. "/events",
      					"GET " .. project .. "/insights/%2e%2e/",
      					"GET " .. host .. "/api/environments/12345/events/",
      					"POST https://us.i.posthog.com/i/v0/e/",
      					"POST https://eu.i.posthog.com/batch/",
      					"POST https://us.i.posthog.com/flags/",
      					"GET https://app.posthog.com/api/projects/12345/events/",
      					"GET https://us.posthog.com.example.com/api/organizations/",
      					"GET http://us.posthog.com:8080/api/organizations/",
      					"GET https://" .. other .. "/api/organizations/",
      					"POST https://" .. other .. "/api/projects/12345/query/",
      				})
      			end
      		end
      	end,
      }
      
    • reads.luau
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "phx_fixture-private-key"}},
      	configure = function()
      		requests = {}
      		payloads = {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.headers.Authorization == nil, "credentials must remain in the proxy")
      			assert(req.headers.Accept[1] == "application/json")
      			assert(req.timeoutMs == 15000 or req.timeoutMs == 5000 or req.timeoutMs == 20000, "requests must bound the wait for headers")
      			if req.method == "GET" then
      				assert(req.body == nil, "PostHog reads must be bodiless GETs")
      			else
      				assert(req.method == "POST" and req.headers["Content-Type"][1] == "application/json", "only queries are posted")
      			end
      			local payload = table.remove(payloads, 1)
      			assert(payload, "unexpected request " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(posthog)
      		local API = "https://us.posthog.com/api"
      		local P = API .. "/projects/12345"
      		local ORG = "0188430e-316e-0000-51a6-fd646548690e"
      		local NULL = json.decode("null")
      		local function urls(from)
      			local out = {}
      			for index = from, #requests do table.insert(out, requests[index].url) end
      			return table.concat(out, " ")
      		end
      		local function last() return requests[#requests].url end
      		local function rejected(fn, expected)
      			local before = #requests
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(#requests == before, "invalid input reached PostHog")
      		end
      
      		local names = {}
      		for name, fn in posthog do
      			assert(type(fn) == "function")
      			table.insert(names, name)
      		end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getInsight,listEvents,listFeatureFlags,listInsights,listOrganizations,listPersons,listProjects,query", table.concat(names, ","))
      		assert(#requests == 0, "initialization reached PostHog")
      
      		payloads = {'{"count":1,"next":null,"previous":null,"results":[{"id":"' .. ORG .. '","name":"Acme","slug":"acme","created_at":"2024-01-02T00:00:00Z","membership_level":8,"member_count":3,"teams":[{"api_token":"phc_public"}],"customer_id":"cus_1"}]}'}
      		local orgs = posthog.listOrganizations()
      		assert(last() == API .. "/organizations/?limit=100", last())
      		assert(orgs.count == 1 and orgs.next == NULL and orgs.results[1].name == "Acme" and orgs.results[1].membership_level == 8)
      		assert(orgs.results[1].teams == nil and orgs.results[1].customer_id == nil, "organization rows must stay compact")
      
      		payloads = {'{"count":2,"next":null,"previous":null,"results":[{"id":12345,"uuid":"u1","organization":"' .. ORG .. '","project_id":12345,"api_token":"phc_public","name":"Web","timezone":"UTC","is_demo":false,"ingested_event":true,"tags":[],"access_control":false}]}'}
      		local projects = posthog.listProjects()
      		assert(last() == API .. "/organizations/@current/projects/?limit=100", last())
      		assert(projects.results[1].id == 12345 and projects.results[1].api_token == nil and json.encode(projects.results[1].tags) == "[]")
      		payloads = {'{"count":0,"next":null,"previous":null,"results":[]}'}
      		local none = posthog.listProjects({organization = ORG, search = "web app", limit = 5})
      		assert(last() == API .. "/organizations/" .. ORG .. "/projects/?search=web%20app&limit=5", last())
      		assert(json.encode(none.results) == "[]" and none.count == 0)
      		payloads = {'{"count":0,"next":null,"previous":null,"results":[]}'}
      		posthog.listProjects({organization = ORG, next = "https://us.posthog.com/api/organizations/" .. ORG .. "/projects/?limit=5&offset=5&search=web%20app"})
      		assert(last() == API .. "/organizations/" .. ORG .. "/projects/?offset=5&search=web%20app&limit=100", last())
      
      		-- A call follows PostHog's next links until it has limit rows, asking each page only for the rest.
      		local event = '{"id":"018f-a","distinct_id":"d1","event":"$pageview","timestamp":"2026-10-29T10:00:00Z","properties":{"$browser":"Firefox"},"elements":[{"tag_name":"a"}],"elements_chain":"a:nth-child(1)"}'
      		payloads = {'{"next":"https://us.posthog.com/api/projects/12345/events/?event=%24pageview&limit=1&before=2026-10-29T10%3A00%3A00Z","results":[' .. event .. ']}',
      			'{"next":"https://us.posthog.com/api/projects/12345/events/?event=%24pageview&limit=1&before=2026-10-29T09%3A00%3A00Z","results":[' .. event .. ']}'}
      		local before = #requests + 1
      		local filters = {{key = "$browser", value = "Firefox", operator = "exact", type = "event"}}
      		local events = posthog.listEvents(12345, {event = "$pageview", after = "2026-10-29T00:00:00Z", before = "2026-10-30T00:00:00Z", distinct_id = "d1",
      			person_id = "0190-person", properties = filters, include_person = true, limit = 2})
      		assert(urls(before) == P .. "/events/?after=2026-10-29T00%3A00%3A00Z&before=2026-10-30T00%3A00%3A00Z&distinct_id=d1&event=%24pageview&include_person=true"
      			.. "&person_id=0190-person&properties=" .. url.encode(json.encode(filters)) .. "&limit=2 "
      			.. P .. "/events/?event=%24pageview&before=2026-10-29T10%3A00%3A00Z&limit=1", urls(before))
      		assert(#events.results == 2 and events.results[1].properties["$browser"] == "Firefox" and events.results[1].elements == nil and events.results[1].elements_chain == nil)
      		assert(events.count == nil and events.next == "https://us.posthog.com/api/projects/12345/events/?event=%24pageview&limit=1&before=2026-10-29T09%3A00%3A00Z", tostring(events.next))
      		payloads = {'{"next":null,"results":[]}'}
      		local rest = posthog.listEvents("12345", {next = events.next, limit = 50})
      		assert(last() == P .. "/events/?event=%24pageview&before=2026-10-29T09%3A00%3A00Z&limit=50", last())
      		assert(json.encode(rest.results) == "[]" and rest.next == NULL)
      		assert(requests[before].timeoutMs == 15000 and requests[before + 1].timeoutMs == 5000, "a second page must get the rest of the call's time")
      		-- A call stops after two pages and hands back the link to the next one.
      		local link = '"https://us.posthog.com/api/projects/@current/events/?offset=1"'
      		payloads = {}
      		for _ = 1, 2 do table.insert(payloads, '{"next":' .. link .. ',"results":[' .. event .. ']}') end
      		before = #requests + 1
      		local capped = posthog.listEvents("@current", {limit = 1000})
      		assert(#requests - before + 1 == 2 and #capped.results == 2 and capped.next == "https://us.posthog.com/api/projects/@current/events/?offset=1")
      		assert(requests[before].url == API .. "/projects/@current/events/?limit=1000" and last() == API .. "/projects/@current/events/?offset=1&limit=999", last())
      		-- When the second page fails, the first comes back with the link to the second.
      		payloads = {'{"next":' .. link .. ',"results":[' .. event .. ']}', "<html>Bad gateway</html>"}
      		before = #requests + 1
      		local partial = posthog.listEvents("@current", {limit = 10})
      		assert(#requests - before + 1 == 2 and #partial.results == 1 and partial.next == "https://us.posthog.com/api/projects/@current/events/?offset=1")
      		-- A link to another path is handed back, never followed.
      		payloads = {'{"next":"https://us.posthog.com/api/projects/999/events/?offset=1","results":[' .. event .. ']}'}
      		before = #requests + 1
      		assert(posthog.listEvents(12345, {limit = 10}).next == "https://us.posthog.com/api/projects/999/events/?offset=1" and #requests == before)
      
      		payloads = {'{"count":1,"next":"https://us.posthog.com/api/projects/12345/persons/?limit=1&offset=1","previous":null,"results":[{"id":"0190-person","uuid":"0190-person","name":"[email protected]","distinct_ids":["d1"],"properties":{"email":"[email protected]"},"created_at":"2026-01-01T00:00:00Z","last_seen_at":null,"is_identified":true}]}'}
      		local persons = posthog.listPersons(12345, {search = "ana", email = "[email protected]", distinct_id = "d1", properties = {{key = "plan", value = "pro", type = "person"}}, limit = 1})
      		assert(last() == P .. "/persons/?distinct_id=d1&email=ana%40example.com&properties=" .. url.encode(json.encode({{key = "plan", value = "pro", type = "person"}})) .. "&search=ana&limit=1", last())
      		assert(persons.results[1].distinct_ids[1] == "d1" and persons.results[1].last_seen_at == NULL and persons.results[1].is_identified == nil)
      		assert(persons.next == "https://us.posthog.com/api/projects/12345/persons/?limit=1&offset=1" and persons.count == 1)
      		payloads = {'{"count":1,"next":null,"previous":"/api/projects/12345/persons/?limit=1","results":[]}'}
      		assert(json.encode(posthog.listPersons(12345, {next = "/api/projects/12345/persons/?offset=1"}).results) == "[]")
      		assert(last() == P .. "/persons/?offset=1&limit=100", last())
      
      		payloads = {'{"count":1,"next":null,"previous":null,"results":[{"id":7,"short_id":"AaVQ8Ijw","name":"Signups","derived_name":null,"query":{"kind":"InsightVizNode"},"saved":true,"favorited":false,"tags":[],"created_by":{"id":1,"uuid":"u","first_name":"Ana","last_name":"Lee","email":"[email protected]","hedgehog_config":{}},"dashboards":[1],"dashboard_tiles":[{"id":2}],"user_access_level":"editor"}]}'}
      		local insights = posthog.listInsights(12345, {search = "signup", saved = true, insight = "TRENDS"})
      		assert(last() == P .. "/insights/?basic=true&insight=TRENDS&saved=true&search=signup&limit=100", last())
      		local insight = insights.results[1]
      		assert(insight.short_id == "AaVQ8Ijw" and insight.derived_name == NULL and insight.dashboards == nil and insight.user_access_level == nil)
      		assert(insight.created_by.email == "[email protected]" and insight.created_by.hedgehog_config == nil and insight.created_by.uuid == nil)
      		payloads = {'{"count":0,"next":null,"previous":null,"results":[]}'}
      		assert(json.encode(posthog.listInsights(12345).results) == "[]" and last() == P .. "/insights/?basic=true&limit=100")
      		payloads = {'{"count":0,"next":null,"previous":null,"results":[]}'}
      		posthog.listInsights(12345, {next = "https://us.posthog.com/api/projects/12345/insights/?basic=true&limit=100&offset=100&search=signup"})
      		assert(last() == P .. "/insights/?offset=100&search=signup&basic=true&limit=100", last())
      
      		payloads = {'{"id":7,"short_id":"AaVQ8Ijw","name":"Signups","result":[{"data":[1,2,3]}],"last_refresh":"2026-10-29T00:00:00Z","dashboards":[1],"user_access_level":"editor","created_by":{"id":1,"email":"[email protected]","hedgehog_config":{}}}'}
      		local full = posthog.getInsight(12345, 7)
      		assert(last() == P .. "/insights/7/" and requests[#requests].timeoutMs == 20000 and full.result[1].data[3] == 3, last())
      		assert(full.dashboards == nil and full.last_refresh == "2026-10-29T00:00:00Z" and full.created_by.email == "[email protected]" and full.created_by.hedgehog_config == nil, "insights must stay compact")
      		payloads = {'{"id":7,"short_id":"AaVQ8Ijw","result":null}'}
      		assert(posthog.getInsight("@current", "AaVQ8Ijw", {refresh = "blocking"}).result == NULL)
      		assert(last() == API .. "/projects/@current/insights/AaVQ8Ijw/?refresh=blocking", last())
      
      		payloads = {'{"count":2,"next":null,"previous":null,"results":['
      			.. '{"id":3,"key":"new-nav","name":"New navigation","active":true,"status":"ACTIVE","filters":{"groups":[{"properties":[],"rollout_percentage":50}],"payloads":{"true":"{\\"color\\":\\"blue\\"}"}},"has_encrypted_payloads":false,"created_by":null,"surveys":{},"usage_dashboard":9,"can_edit":true},'
      			.. '{"id":4,"key":"stripe-config","name":"Remote config","active":true,"filters":{"groups":[],"payloads":{"true":"sk_live_secret"}},"has_encrypted_payloads":true,"is_remote_configuration":true}]}'}
      		local flags = posthog.listFeatureFlags(12345, {active = true, search = "nav", key = "new-nav", type = "boolean", limit = 50})
      		assert(last() == P .. "/feature_flags/?active=true&key=new-nav&search=nav&type=boolean&limit=50", last())
      		assert(flags.results[1].filters.groups[1].rollout_percentage == 50 and flags.results[1].filters.payloads["true"] == '{"color":"blue"}')
      		assert(flags.results[1].created_by == NULL and flags.results[1].surveys == nil and flags.results[1].usage_dashboard == nil and flags.results[1].can_edit == nil)
      		assert(flags.results[2].filters.payloads["true"] == "(encrypted)", "decrypted remote config payloads must be redacted")
      		payloads = {'{"count":0,"next":null,"previous":null,"results":[]}'}
      		assert(json.encode(posthog.listFeatureFlags(12345, {active = "STALE"}).results) == "[]" and last() == P .. "/feature_flags/?active=STALE&limit=100")
      
      		payloads = {'{"columns":["day","pageviews"],"types":[["day","Date"],["pageviews","UInt64"]],"results":[["2026-10-28",10],["2026-10-29",12]],"hasMore":false,"hogql":"SELECT ...","clickhouse":"SELECT ...","timings":[{"k":"x","t":1}],"is_cached":false}'}
      		local sql = "select toDate(timestamp) as day, count() as pageviews from events where event = {name} group by day"
      		local result = posthog.query(12345, sql, {values = {name = "$pageview"}, name = "daily pageviews"})
      		local request = requests[#requests]
      		assert(request.method == "POST" and request.url == P .. "/query/", request.url)
      		local body = json.decode(request.body)
      		assert(body.query.kind == "HogQLQuery" and body.query.query == sql and body.query.values.name == "$pageview")
      		assert(body.refresh == "blocking" and body.name == "daily pageviews" and body.client_query_id == nil)
      		assert(result.columns[2] == "pageviews" and result.types[1][2] == "Date" and result.results[2][2] == 12 and result.hasMore == false and result.truncated == false)
      		assert(result.hogql == nil and result.clickhouse == nil and result.timings == nil, "query results must stay compact")
      		local rows = {}
      		for index = 1, 1001 do rows[index] = {index} end
      		payloads = {json.encode({columns = {"n"}, types = {{"n", "Int64"}}, results = rows, hasMore = true})}
      		local big = posthog.query("12345", "select number as n from numbers(1001)")
      		assert(json.decode(requests[#requests].body).name == "houston" and json.decode(requests[#requests].body).query.values == nil)
      		assert(#big.results == 1000 and big.results[1000][1] == 1000 and big.truncated == true and big.hasMore == true)
      		payloads = {'{"columns":["n"],"types":[["n","Int64"]],"results":[],"hasMore":false}'}
      		local empty = posthog.query(12345, "select 1 where 0")
      		assert(json.encode(empty.results) == "[]" and empty.truncated == false)
      
      		rejected(function() posthog.listEvents() end, "project must be")
      		rejected(function() posthog.listEvents(0) end, "project must be")
      		rejected(function() posthog.listEvents(12.5) end, "project must be")
      		rejected(function() posthog.listEvents("12345/../1") end, "project must be")
      		rejected(function() posthog.listEvents("current") end, "project must be")
      		rejected(function() posthog.listEvents(12345, "next") end, "must be a table")
      		rejected(function() posthog.listEvents(12345, {limit = 0}) end, "1 to 1000")
      		rejected(function() posthog.listEvents(12345, {limit = 1001}) end, "1 to 1000")
      		rejected(function() posthog.listEvents(12345, {limit = 2.5}) end, "1 to 1000")
      		rejected(function() posthog.listEvents(12345, {select = {"*"}}) end, "unknown option select")
      		rejected(function() posthog.listEvents(12345, {event = ""}) end, "nonempty string")
      		rejected(function() posthog.listEvents(12345, {event = string.rep("x", 1001)}) end, "nonempty string")
      		rejected(function() posthog.listEvents(12345, {properties = {}}) end, "property filters")
      		rejected(function() posthog.listEvents(12345, {properties = {key = "plan"}}) end, "property filters")
      		rejected(function() posthog.listEvents(12345, {include_person = "yes"}) end, "include_person must be one of true, false")
      		rejected(function() posthog.listEvents(12345, {next = "https://us.posthog.com/api/projects/12345/events/"}) end, "next link")
      		rejected(function() posthog.listEvents(12345, {next = "https://us.posthog.com/projects/12345/events?offset=1"}) end, "next link")
      		rejected(function() posthog.listEvents(12345, {next = events.next, event = "$pageview"}) end, "takes only limit with next")
      		rejected(function() posthog.listInsights(12345, {next = "/api/?refresh=force_blocking"}) end, "next link")
      		rejected(function() posthog.listEvents(999, {next = events.next}) end, "same project")
      		rejected(function() posthog.listPersons(12345, {next = events.next}) end, "next link")
      		rejected(function() posthog.listProjects({next = "https://us.posthog.com/api/organizations/" .. ORG .. "/projects/?offset=5"}) end, "same project or organization")
      		rejected(function() posthog.query(12345, "select 1", {name = string.rep("x", 129)}) end, "128 characters")
      		rejected(function() posthog.listInsights(12345, {next = "/api/projects/12345/insights/?basic=false&offset=100"}) end, "next link")
      		rejected(function() posthog.listEvents(12345, {next = "/api/projects/12345/events/?select=%5B%22*%22%5D"}) end, "next link")
      		rejected(function() posthog.listEvents(12345, {next = "/api/projects/12345/persons/?search=ana"}) end, "next link")
      		rejected(function() posthog.listPersons(12345, {next = "/api/projects/12345/persons/?offset=1x"}) end, "next link")
      		rejected(function() posthog.listPersons(12345, {next = "/api/projects/12345/persons/?format=csv&offset=100"}) end, "next link")
      		rejected(function() posthog.listProjects({organization = "acme"}) end, "organization uuid")
      		rejected(function() posthog.listOrganizations({organization = ORG}) end, "unknown option organization")
      		rejected(function() posthog.listInsights(12345, {insight = "trends"}) end, "insight must be one of")
      		rejected(function() posthog.listInsights(12345, {favorited = true}) end, "unknown option favorited")
      		rejected(function() posthog.listFeatureFlags(12345, {active = "stale"}) end, "active must be one of")
      		rejected(function() posthog.getInsight(12345) end, "short_id")
      		rejected(function() posthog.getInsight(12345, "AaVQ8Ij/") end, "short_id")
      		rejected(function() posthog.getInsight(12345, "AaVQ8Ijw1") end, "short_id")
      		rejected(function() posthog.getInsight(12345, 7, {refresh = "force_blocking"}) end, "refresh must be one of force_cache, blocking")
      		rejected(function() posthog.getInsight(12345, 7, {include_dashboards = true}) end, "unknown option include_dashboards")
      		rejected(function() posthog.query(12345, "  ") end, "nonempty HogQL")
      		rejected(function() posthog.query(12345, string.rep("x", 32 * 1024 + 1)) end, "nonempty HogQL")
      		rejected(function() posthog.query(12345, {kind = "HogQLQuery"}) end, "nonempty HogQL")
      		rejected(function() posthog.query(12345, "select 1", {values = {"x"}}) end, "placeholder values")
      		rejected(function() posthog.query(12345, "select 1", {refresh = "force_async"}) end, "unknown option refresh")
      		rejected(function() posthog.query("abc", "select 1") end, "project must be")
      	end,
      }