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(surveys): return 400 instead of 500 for stringified params (#89353)

posthog[bot]1856ac3594ad
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index d7741225f740..8327fcaccd87 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -1031,6 +1031,24 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
return value
+ def validate_targeting_flag_filters(self, value):
+ if value is None:
+ return value
+
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("targeting_flag_filters must be an object")
+
+ return value
+
+ def validate_form_content(self, value):
+ if value is None:
+ return value
+
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("form_content must be an object")
+
+ return value
+
def _resolve_base_language(self) -> str:
"""Resolve the survey's base language from incoming data, falling back to the instance, then 'en'."""
initial_data = getattr(self, "initial_data", None)
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index bfe32c4fee70..8b66a5c4a310 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -1523,6 +1523,24 @@ class TestSurvey(APIBaseTest):
"attr": None,
}
+ @parameterized.expand(
+ [
+ ("targeting_flag_filters", '{"groups": []}'),
+ ("form_content", '{"type": "doc"}'),
+ ]
+ )
+ def test_structured_param_as_json_string_returns_400_not_500(self, field, value):
+ # Some MCP clients send a structured param as a JSON-encoded string when its
+ # generated schema is empty. The server must name the bad field, not raise a 500.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={"name": "survey with bad param", "type": "popover", field: value},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == field
+
def test_updating_survey_with_targeting_creates_or_updates_targeting_flag(self):
survey_with_targeting = self.client.post(
f"/api/projects/{self.team.id}/surveys/",
diff --git a/services/mcp/src/lib/tool-error-hints.ts b/services/mcp/src/lib/tool-error-hints.ts
index aaca4050b782..8195e544f476 100644
--- a/services/mcp/src/lib/tool-error-hints.ts
+++ b/services/mcp/src/lib/tool-error-hints.ts
@@ -39,6 +39,31 @@ const LOGS_QUERY_URL_FRAGMENTS = [
'/logs/sparkline/',
]
+/**
+ * The survey create/update endpoint returns a 5xx when a structured parameter
+ * arrives as a JSON-encoded string instead of an object or array. Some MCP
+ * clients stringify args whose generated schema is empty. The server then reads
+ * a member of the string and fails. The recovery is to send the parameter as a
+ * real JSON value.
+ */
+const SURVEY_WRITE_RECOVERY_HINT = [
+ 'This survey write failed server-side. The most common cause is a structured parameter sent as a JSON-encoded string instead of a real object or array — not a bug in the survey itself.',
+ '',
+ 'Check `targeting_flag_filters`, `conditions`, `appearance`, `questions`, and `form_content`. Each must be a JSON object or array, not a string.',
+ '',
+ 'Wrong: `targeting_flag_filters: "{\\"groups\\": []}"`.',
+ 'Right: `targeting_flag_filters: { "groups": [] }`.',
+ '',
+ 'Fix the value that is a string, then retry once.',
+].join('\n')
+
+/**
+ * Matches the survey create and update paths (`/surveys/` and `/surveys/{id}/`)
+ * but not the sub-action paths (`/surveys/{id}/stats/`, `/launch/`, `/stop/`),
+ * whose 5xx failures are query problems, not input problems.
+ */
+const SURVEY_WRITE_URL_RE = /\/surveys\/(?:[^/]+\/)?$/
+
interface RecoveryHintInput {
/** The failed request URL (from `PostHogApiError.url`), if the error was an HTTP failure. */
url?: string | undefined
@@ -62,5 +87,8 @@ export function getToolRecoveryHint({ url, status }: RecoveryHintInput): string
if (url && LOGS_QUERY_URL_FRAGMENTS.some((fragment) => url.includes(fragment))) {
return LOGS_QUERY_RECOVERY_HINT
}
+ if (url && SURVEY_WRITE_URL_RE.test(url)) {
+ return SURVEY_WRITE_RECOVERY_HINT
+ }
return undefined
}
diff --git a/services/mcp/tests/unit/tool-error-hints.test.ts b/services/mcp/tests/unit/tool-error-hints.test.ts
index 17f79f07a2aa..75826b174a36 100644
--- a/services/mcp/tests/unit/tool-error-hints.test.ts
+++ b/services/mcp/tests/unit/tool-error-hints.test.ts
@@ -42,6 +42,23 @@ describe('getToolRecoveryHint', () => {
it('fires when status is unknown but the URL is a logs query endpoint', () => {
expect(getToolRecoveryHint({ url: LOGS_QUERY_URL })).not.toBeUndefined()
})
+
+ it.each([
+ 'https://us.posthog.com/api/projects/2/surveys/',
+ 'https://us.posthog.com/api/projects/2/surveys/018f-abc/',
+ ])('returns the structured-param hint for a 5xx on the survey write endpoint %s', (url: string) => {
+ const hint = getToolRecoveryHint({ url, status: 500 })
+
+ expect(hint).not.toBeUndefined()
+ expect(hint).toContain('JSON-encoded string')
+ expect(hint).toContain('targeting_flag_filters')
+ })
+
+ it('does not fire for a survey sub-action endpoint — its 5xx is a query problem', () => {
+ expect(
+ getToolRecoveryHint({ url: 'https://us.posthog.com/api/projects/2/surveys/018f-abc/stats/', status: 500 })
+ ).toBeUndefined()
+ })
})
describe('handleToolError recovery hints', () => {