Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): serialize comma-separated array query params as CSV (#63243)

Catalin Irimie215f3e4b2270
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index fd857cea275c..6272c441f748 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -57,6 +57,13 @@ interface OpenApiParam {
* codegen widens these into z.union([z.string(), z.record(...)]).
*/
'x-accepts-stringified-json'?: boolean
+ /**
+ * OpenAPI serialization hints. drf-spectacular emits `style: form` +
+ * `explode: false` for django-filter comma-separated filters (BaseInFilter),
+ * which expect `?type=a,b` on the wire.
+ */
+ style?: string
+ explode?: boolean
}
interface OpenApiSchema {
@@ -229,6 +236,32 @@ function resolveSchema(spec: OpenApiSpec, schemaOrRef: OpenApiSchema | { $ref: s
return schemaOrRef as OpenApiSchema
}
+const CSV_SCALAR_ITEM_TYPES = new Set(['string', 'number', 'integer', 'boolean'])
+
+/**
+ * django-filter comma-separated filters (BaseInFilter) are emitted by
+ * drf-spectacular as array query params with `style: form` + `explode: false`,
+ * meaning `?type=a,b` on the wire. ApiClient.request() JSON-stringifies arrays
+ * for json.loads()-style backends, which DRF would read as one literal value
+ * (`type IN ('["a","b"]')`) and silently match nothing — so the handler must
+ * comma-join these before they reach the client. Only scalar-item arrays
+ * qualify; object/$ref-item arrays stay on the JSON path.
+ */
+function isCommaSeparatedQueryParam(p: OpenApiParam): boolean {
+ if (p.explode !== false || (p.style ?? 'form') !== 'form' || p['x-accepts-stringified-json']) {
+ return false
+ }
+ if (p.schema?.type !== 'array' || !p.schema.items) {
+ return false
+ }
+ const items = p.schema.items
+ if ('$ref' in items && items.$ref) {
+ return false
+ }
+ const itemType = (items as OpenApiSchema).type
+ return typeof itemType === 'string' && CSV_SCALAR_ITEM_TYPES.has(itemType)
+}
+
/**
* Flatten body schema properties across the three composition keywords that
* can hide fields from a naive ``schema.properties`` read:
@@ -417,6 +450,12 @@ interface SchemaComposition {
schemaExpr: string
pathParamNames: string[]
queryParamNames: string[]
+ /**
+ * Query params that must be comma-joined on the wire (OpenAPI
+ * `explode: false`, i.e. django-filter comma-separated filters) instead of
+ * JSON-stringified by ApiClient.request().
+ */
+ csvQueryParamNames: Set<string>
bodyFieldNames: string[]
/**
* Body fields that only appear in some variants of a union (anyOf/oneOf) body schema.
@@ -442,6 +481,7 @@ function composeToolSchema(
const schemaParts: string[] = []
const pathParamNames: string[] = []
const queryParamNames: string[] = []
+ const csvQueryParamNames = new Set<string>()
const bodyFieldNames: string[] = []
const variantSpecificBodyFieldNames = new Set<string>()
/**
@@ -515,6 +555,13 @@ function composeToolSchema(
}
for (const p of usefulQueryParams) {
queryParamNames.push(p.name)
+ // param_overrides with input_schema / schema_ref / cast replace or
+ // reshape the param type, so the array-join can't be assumed.
+ const override = config.param_overrides?.[p.name]
+ const schemaReplaced = !!(override && (override.input_schema || override.schema_ref || override.cast))
+ if (!schemaReplaced && isCommaSeparatedQueryParam(p)) {
+ csvQueryParamNames.add(p.name)
+ }
if (!p.required) {
optionalParamNames.add(p.name)
}
@@ -740,6 +787,7 @@ function composeToolSchema(
schemaExpr,
pathParamNames,
queryParamNames,
+ csvQueryParamNames,
bodyFieldNames,
variantSpecificBodyFieldNames,
renamedFields,
@@ -979,7 +1027,17 @@ function generateToolCode(
}
if (hasQuery) {
const queryAssignments = composition.queryParamNames
- .map((qn) => ` ${qn}: params.${qn},`)
+ .map((qn) => {
+ // explode: false params are comma-joined here because
+ // ApiClient.request() JSON-stringifies raw arrays (the
+ // json.loads()-style contract), which DRF CSV filters can't parse.
+ // Callers may pass either the array shape or a single string, so
+ // only join when it's actually an array; an empty array is omitted.
+ if (composition.csvQueryParamNames.has(qn)) {
+ return ` ${qn}: Array.isArray(params.${qn}) ? params.${qn}.join(',') || undefined : params.${qn},`
+ }
+ return ` ${qn}: params.${qn},`
+ })
.join('\n')
handlerBody += ` query: {\n${queryAssignments}\n },\n`
}
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index fe229ebbc461..ce328149fe3f 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -253,10 +253,10 @@ const llmaEvaluationList = (): ToolBase<typeof LlmaEvaluationListSchema, Schemas
path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluations/`,
query: {
enabled: params.enabled,
- id__in: params.id__in,
+ id__in: Array.isArray(params.id__in) ? params.id__in.join(',') || undefined : params.id__in,
limit: params.limit,
offset: params.offset,
- order_by: params.order_by,
+ order_by: Array.isArray(params.order_by) ? params.order_by.join(',') || undefined : params.order_by,
search: params.search,
},
})
@@ -1245,10 +1245,10 @@ const llmaTaggerList = (): ToolBase<typeof LlmaTaggerListSchema, WithPostHogUrl<
path: `/api/projects/${encodeURIComponent(String(projectId))}/taggers/`,
query: {
enabled: params.enabled,
- id__in: params.id__in,
+ id__in: Array.isArray(params.id__in) ? params.id__in.join(',') || undefined : params.id__in,
limit: params.limit,
offset: params.offset,
- order_by: params.order_by,
+ order_by: Array.isArray(params.order_by) ? params.order_by.join(',') || undefined : params.order_by,
search: params.search,
},
})
diff --git a/services/mcp/src/tools/generated/cdp_functions.ts b/services/mcp/src/tools/generated/cdp_functions.ts
index aaeed9b07e0f..9341de807e4b 100644
--- a/services/mcp/src/tools/generated/cdp_functions.ts
+++ b/services/mcp/src/tools/generated/cdp_functions.ts
@@ -163,7 +163,7 @@ const cdpFunctionsList = (): ToolBase<
id: params.id,
limit: params.limit,
offset: params.offset,
- type: params.type,
+ type: Array.isArray(params.type) ? params.type.join(',') || undefined : params.type,
updated_at: params.updated_at,
},
})
diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.ts
index f152ec6e0d82..5067178e96f6 100644
--- a/services/mcp/src/tools/generated/platform_features.ts
+++ b/services/mcp/src/tools/generated/platform_features.ts
@@ -221,7 +221,7 @@ const changeRequestsList = (): ToolBase<typeof ChangeRequestsListSchema, Schemas
requester: params.requester,
resource_id: params.resource_id,
resource_type: params.resource_type,
- state: params.state,
+ state: Array.isArray(params.state) ? params.state.join(',') || undefined : params.state,
},
})
return result
diff --git a/services/mcp/tests/unit/csv-query-params.test.ts b/services/mcp/tests/unit/csv-query-params.test.ts
new file mode 100644
index 000000000000..d8b6aa65938f
--- /dev/null
+++ b/services/mcp/tests/unit/csv-query-params.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { ApiClient } from '@/api/client'
+import { GENERATED_TOOLS as CDP_TOOLS } from '@/tools/generated/cdp_functions'
+import { GENERATED_TOOLS as LOGS_TOOLS } from '@/tools/generated/logs'
+import type { Context } from '@/tools/types'
+
+// Regression coverage for DRF comma-separated query filters (OpenAPI
+// `style: form` + `explode: false`, e.g. hog_functions `type`). The shared
+// ApiClient JSON-stringifies arrays for logs-style `json.loads()` params, so
+// CSV params must be comma-joined in the generated handlers before they reach
+// the client — otherwise DRF runs `type IN ('["..."]')` and silently matches
+// nothing.
+
+interface RequestArgs {
+ method: string
+ path: string
+ query?: Record<string, unknown>
+}
+
+function createMockContext(): { context: Context; request: ReturnType<typeof vi.fn> } {
+ const request = vi.fn().mockResolvedValue({ count: 0, results: [] })
+ const context = {
+ api: {
+ request,
+ getProjectBaseUrl: vi.fn().mockReturnValue('https://us.posthog.com/project/1'),
+ },
+ stateManager: {
+ getProjectId: vi.fn().mockResolvedValue('1'),
+ getOrgID: vi.fn(),
+ getRegion: vi.fn().mockResolvedValue('us'),
+ },
+ env: { POSTHOG_BASE_URL: 'https://us.posthog.com' },
+ sessionManager: {},
+ cache: {},
+ getDistinctId: async () => 'test',
+ } as unknown as Context
+
+ return { context, request }
+}
+
+describe('comma-separated (explode: false) query params in generated handlers', () => {
+ it('cdp-functions-list joins type values with commas', async () => {
+ const { context, request } = createMockContext()
+ const tool = CDP_TOOLS['cdp-functions-list']!()
+
+ await tool.handler(context, { type: ['internal_destination', 'transformation'] })
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call.query?.type).toBe('internal_destination,transformation')
+ })
+
+ it('cdp-functions-list omits type when the array is empty', async () => {
+ const { context, request } = createMockContext()
+ const tool = CDP_TOOLS['cdp-functions-list']!()
+
+ await tool.handler(context, { type: [] })
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call.query?.type).toBeUndefined()
+ })
+
+ it('cdp-functions-list passes a single string type through unchanged', async () => {
+ const { context, request } = createMockContext()
+ const tool = CDP_TOOLS['cdp-functions-list']!()
+
+ // Callers (and the integration suite) may pass a bare string instead of
+ // an array — it must not hit Array.prototype.join.
+ await tool.handler(context, { type: 'destination' } as never)
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call.query?.type).toBe('destination')
+ })
+
+ it('logs-attribute-values-list keeps JSON-style array params as arrays', async () => {
+ const { context, request } = createMockContext()
+ const tool = LOGS_TOOLS['logs-attribute-values-list']!()
+
+ // The logs backend reads these with json.loads(), so the handler must
+ // NOT comma-join them — the client JSON-stringifies them on the wire.
+ await tool.handler(context, { key: 'level', serviceNames: ['api', 'web'] })
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call.query?.serviceNames).toEqual(['api', 'web'])
+ })
+})
+
+describe('ApiClient.request query serialization', () => {
+ async function requestUrl(query: Record<string, unknown>): Promise<string> {
+ const mockFetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))
+ vi.stubGlobal('fetch', mockFetch)
+ const client = new ApiClient({ apiToken: 'token', baseUrl: 'https://example.com' })
+ await client.request({ method: 'GET', path: '/api/test/', query })
+ return mockFetch.mock.calls[0]![0] as string
+ }
+
+ it('passes pre-joined CSV strings through verbatim', async () => {
+ const url = await requestUrl({ type: 'internal_destination,transformation' })
+ expect(url).toBe('https://example.com/api/test/?type=internal_destination%2Ctransformation')
+ })
+
+ it('JSON-stringifies arrays and objects for json.loads()-style backends', async () => {
+ const url = await requestUrl({ serviceNames: ['api'], dateRange: { date_from: '-7d' } })
+ const params = new URL(url).searchParams
+ expect(params.get('serviceNames')).toBe('["api"]')
+ expect(params.get('dateRange')).toBe('{"date_from":"-7d"}')
+ })
+})
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 3cebccde72ff..e337664f802b 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -394,6 +394,107 @@ describe('generateToolCode without input_schema', () => {
expect(result.toolInputsImports).toEqual([])
})
+ it('comma-joins explode:false array query params (DRF comma-separated filters)', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ }
+ const resolved = makeResolved({
+ operation: {
+ operationId: 'things_list',
+ parameters: [
+ {
+ in: 'query',
+ name: 'type',
+ style: 'form',
+ explode: false,
+ schema: { type: 'array', items: { type: 'string' } },
+ },
+ ],
+ },
+ })
+
+ const result = generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.code).toContain(
+ "type: Array.isArray(params.type) ? params.type.join(',') || undefined : params.type,"
+ )
+ })
+
+ it('forwards array query params without explode:false untouched (json.loads()-style backends)', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ }
+ const resolved = makeResolved({
+ operation: {
+ operationId: 'things_list',
+ parameters: [
+ {
+ in: 'query',
+ name: 'serviceNames',
+ schema: { type: 'array', items: { type: 'string' } },
+ },
+ ],
+ },
+ })
+
+ const result = generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.code).toContain('serviceNames: params.serviceNames,')
+ expect(result.code).not.toContain('serviceNames.join')
+ })
+
+ it('keeps explode:false params with object items on the JSON path', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ }
+ const resolved = makeResolved({
+ operation: {
+ operationId: 'things_list',
+ parameters: [
+ {
+ in: 'query',
+ name: 'filters',
+ style: 'form',
+ explode: false,
+ schema: { type: 'array', items: { $ref: '#/components/schemas/Filter' } },
+ },
+ ],
+ },
+ })
+
+ const result = generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.code).toContain('filters: params.filters,')
+ expect(result.code).not.toContain('filters.join')
+ })
+
it('collects toolInputsImports from param_overrides', () => {
const config: ToolConfig = {
operation: 'things_create',