: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(mcp): attribute ops by x-product only, drop scaffold URL fallback (#63474)
Julian Bez3ad428d112b2
diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.mdindex 7aab58182d50..b8ecc7bd168d 100644--- a/.agents/skills/implementing-mcp-tools/SKILL.md+++ b/.agents/skills/implementing-mcp-tools/SKILL.md@@ -11,9 +11,9 @@ Read the full guide at [docs/published/handbook/engineering/ai/implementing-mcp-```sh# 1. Scaffold a starter YAML with all operations disabled.-# --product discovers endpoints via x-product (priority 1) then-# URL substring match (fallback). ViewSets in products/<name>/backend/-# are auto-attributed via module path. ViewSets elsewhere need+# --product discovers endpoints via their x-product attribution.+# ViewSets in products/<name>/backend/ are auto-attributed via module+# path. ViewSets elsewhere need# @extend_schema(extensions={"x-product": "<product>"}).pnpm --filter=@posthog/mcp run scaffold-yaml -- --product your_product \--output ../../products/your_product/mcp/tools.yamldiff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex d00c6d33a560..f2078c0db21c 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -167,16 +167,16 @@ Product teams own their definitions and control which operations are exposed as**Workflow: scaffold, configure, generate.**1. **Scaffold** a starter YAML with all operations disabled.- `--product` discovers endpoints in two ways (same priority as frontend type generation):- 1. **`x-product`** — matches endpoints whose product attribution equals the product name.- ViewSets in `products/<name>/backend/` are auto-attributed via the module path.- ViewSets elsewhere (e.g. `posthog/api/`, `ee/`) need- `@extend_schema(extensions={"x-product": "<product>"})`.- 2. **URL substring fallback** — selects endpoints whose path contains `/<name>/`- (hyphens normalized to underscores).-- If your product's API routes use a different slug than the product folder name- (e.g. `workflows` product with `/hog_flows/` routes),+ `--product` discovers endpoints by their **`x-product`** attribution —+ it matches endpoints whose product attribution equals the product name.+ ViewSets in `products/<name>/backend/` are auto-attributed via the module path.+ ViewSets elsewhere (e.g. `posthog/api/`, `ee/`) need+ `@extend_schema(extensions={"x-product": "<product>"})`.+ There is deliberately no URL-based matching — paths are a lossy signal of+ ownership and used to pull endpoints into the wrong product's tool list.++ The same applies when your product's API routes use a different slug than+ the product folder name (e.g. `workflows` product with `/hog_flows/` routes):add `@extend_schema(extensions={"x-product": "workflows"})` to the ViewSet sothe scaffold can find them.diff --git a/ee/api/dashboard_collaborator.py b/ee/api/dashboard_collaborator.pyindex 678c7068aa90..b2f62f7189ec 100644--- a/ee/api/dashboard_collaborator.py+++ b/ee/api/dashboard_collaborator.py@@ -2,6 +2,7 @@ from typing import Any, castfrom django.db import IntegrityError+from drf_spectacular.utils import extend_schemafrom rest_framework import exceptions, mixins, serializers, viewsetsfrom rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Request@@ -87,6 +88,7 @@ class DashboardCollaboratorSerializer(serializers.ModelSerializer, UserPermissioraise serializers.ValidationError("User already is a collaborator.")+@extend_schema(extensions={"x-product": "dashboards"})class DashboardCollaboratorViewSet(TeamAndOrgViewSetMixin,mixins.ListModelMixin,diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex bf6248a864d6..38d3243749e4 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -1256,6 +1256,7 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:)+@extend_schema(extensions={"x-product": "cohorts"})@extend_schema_view(list=extend_schema(parameters=[diff --git a/posthog/api/documentation.py b/posthog/api/documentation.pyindex 21d3e2e24c52..4b9aa6780ed5 100644--- a/posthog/api/documentation.py+++ b/posthog/api/documentation.py@@ -1086,9 +1086,10 @@ def custom_postprocessing_hook(result, generator, request, public):# When present, NOTHING else is added — the dev intent wins. Use this to send# an endpoint to the core bucket from inside ``products/<X>/backend/`` (e.g.# ``extensions={"x-product": "core"}``).- # 2. ``@extend_schema(tags=[...])`` values matching a product folder — supported- # for legacy call sites; the explicit form above is preferred for new code.- # Non-folder tag values are dropped here (tags=[...] is for display, not routing).+ # 2. ``@extend_schema(tags=[...])`` values — supported for legacy call sites; the+ # explicit form above is preferred for new code. Non-folder values pass through+ # here; consumers ignore anything that doesn't match a product folder or+ # definition file (tags=[...] is for display, not routing).# 3. Module-path auto-attribution: ViewSet in ``products/<name>/backend/`` → ``<name>``.## The resulting list is read by ``generate-openapi-types.mjs`` anddiff --git a/posthog/api/health_issue.py b/posthog/api/health_issue.pyindex 5e2ec8ef611e..f6d92aa3f75c 100644--- a/posthog/api/health_issue.py+++ b/posthog/api/health_issue.py@@ -198,6 +198,7 @@ VALID_STATUSES = {choice.value for choice in HealthIssue.Status}VALID_SEVERITIES = {choice.value for choice in HealthIssue.Severity}+@extend_schema(extensions={"x-product": "health_issues"})@extend_schema_view(list=extend_schema(summary="List health issues",diff --git a/posthog/api/organization_integration.py b/posthog/api/organization_integration.pyindex 0863351b6332..7cfd6da301da 100644--- a/posthog/api/organization_integration.py+++ b/posthog/api/organization_integration.py@@ -42,6 +42,7 @@ class EnvironmentMappingUpdateSerializer(serializers.Serializer):development = serializers.IntegerField(required=False)+@extend_schema(extensions={"x-product": "integrations"})class OrganizationIntegrationViewSet(TeamAndOrgViewSetMixin,mixins.ListModelMixin,diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.pyindex a9bf6418fd08..b18eb7b91d97 100644--- a/posthog/api/proxy_record.py+++ b/posthog/api/proxy_record.py@@ -173,7 +173,7 @@ class DiagnosticReportSerializer(serializers.Serializer):checks = DiagnosticCheckResultSerializer(many=True, help_text="Per-check results in execution order.")-@extend_schema(tags=["reverse_proxy"])+@extend_schema(tags=["reverse_proxy"], extensions={"x-product": "proxy_records"})class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):scope_object = "organization"serializer_class = ProxyRecordSerializerdiff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 0d7292e9d8d0..a218ef710a59 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -9,39 +9,6 @@ feature: conversationsurl_prefix: /conversations/ticketsui_apps: {}tools:- conversations-append-message-create:- operation: conversations_append_message_create- enabled: false- conversations-cancel-partial-update:- operation: conversations_cancel_partial_update- enabled: false- conversations-create:- operation: conversations_create- enabled: false- conversations-destroy:- operation: conversations_destroy- enabled: false- conversations-list:- operation: conversations_list- enabled: false- conversations-queue-clear-create:- operation: conversations_queue_clear_create- enabled: false- conversations-queue-create:- operation: conversations_queue_create- enabled: false- conversations-queue-destroy:- operation: conversations_queue_destroy- enabled: false- conversations-queue-partial-update:- operation: conversations_queue_partial_update- enabled: false- conversations-queue-retrieve:- operation: conversations_queue_retrieve- enabled: false- conversations-retrieve:- operation: conversations_retrieve- enabled: falseconversations-tickets-bulk-update-status-create:operation: conversations_tickets_bulk_update_status_createenabled: falsediff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yamlindex 77b87a75b3a6..a28f2f721969 100644--- a/products/persons/mcp/tools.yaml+++ b/products/persons/mcp/tools.yaml@@ -9,9 +9,6 @@ feature: personsurl_prefix: /personsui_apps: {}tools:- cohorts-persons-retrieve:- operation: cohorts_persons_retrieve- enabled: falsepersons-activity-retrieve:operation: persons_activity_retrieveenabled: falsediff --git a/services/mcp/definitions/README.md b/services/mcp/definitions/README.mdindex 91670af2d608..369e65895620 100644--- a/services/mcp/definitions/README.md+++ b/services/mcp/definitions/README.md@@ -6,15 +6,16 @@ endpoints.## How it works-tool handlers and Zod validation schemas. Operations are discovered by matching URL paths-against product names (e.g., `error_tracking` matches all paths containing `/error_tracking/`),-same approach as the frontend type generator.+tool handlers and Zod validation schemas. Operations are discovered by their `x-product`+attribution in the OpenAPI spec — auto-derived from the ViewSet module path+(`products/<name>/backend/` → `<name>`) or declared explicitly via+`@extend_schema(extensions={"x-product": "<name>"})`.```textOpenAPI schema (Django)│▼- scaffold-yaml ← discovers operations by tag + URL path, writes YAML stubs+ scaffold-yaml ← discovers operations by x-product, writes YAML stubs│▼YAML definitions ← product teams enable tools, add scopes/annotations/descriptions@@ -38,12 +39,11 @@ Run the full pipeline: `hogli build:openapi`--output ../../products/your_product/mcp/tools.yaml```- `--product` is a **substring match** on URL paths:- it selects every endpoint whose path contains `/<name>/`+ `--product` matches endpoints by their **`x-product`** attribution(hyphens are normalized to underscores before matching).- The value doesn't have to be an exact product name —- any string that appears as a path segment will work- (e.g. `--product actions` matches `/api/projects/{project_id}/actions/`).+ ViewSets in `products/<name>/backend/` are attributed automatically;+ ViewSets elsewhere need `@extend_schema(extensions={"x-product": "<name>"})`.+ URL paths are never used for discovery.2. **Configure** — edit the YAML to enable the tools you want. Each enabled tool needs`scopes`, `annotations`, and ideally a `description`:diff --git a/services/mcp/definitions/data_warehouse.yaml b/services/mcp/definitions/data_warehouse.yamldeleted file mode 100644index c0e056bdd5fe..000000000000--- a/services/mcp/definitions/data_warehouse.yaml+++ /dev/null@@ -1,404 +0,0 @@-# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.-# The tool list and operation IDs are kept in sync automatically:-# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all-#-# To enable a tool, set enabled: true and add required scopes + annotations.-# All other fields (title, description, enrich_url, etc.) are yours to configure.-category: Data_warehouse-feature: data_warehouse-url_prefix: /data-warehouse-ui_apps: {}-tools:- data-modeling-jobs-list:- operation: data_modeling_jobs_list- enabled: false- data-modeling-jobs-recent-retrieve:- operation: data_modeling_jobs_recent_retrieve- enabled: false- data-modeling-jobs-retrieve:- operation: data_modeling_jobs_retrieve- enabled: false- data-modeling-jobs-running-retrieve:- operation: data_modeling_jobs_running_retrieve- enabled: false- data-warehouse-check-database-name-retrieve:- operation: data_warehouse_check_database_name_retrieve- enabled: false- data-warehouse-completed-activity-retrieve:- operation: data_warehouse_completed_activity_retrieve- enabled: false- data-warehouse-data-health-issues-retrieve:- operation: data_warehouse_data_health_issues_retrieve- enabled: false- data-warehouse-data-ops-dashboard-retrieve:- operation: data_warehouse_data_ops_dashboard_retrieve- enabled: false- data-warehouse-deprovision-create:- operation: data_warehouse_deprovision_create- enabled: false- data-warehouse-job-stats-retrieve:- operation: data_warehouse_job_stats_retrieve- enabled: false- data-warehouse-property-values-retrieve:- operation: data_warehouse_property_values_retrieve- enabled: false- data-warehouse-provision-create:- operation: data_warehouse_provision_create- enabled: false- data-warehouse-reset-password-create:- operation: data_warehouse_reset_password_create- enabled: false- data-warehouse-running-activity-retrieve:- operation: data_warehouse_running_activity_retrieve- enabled: false- data-warehouse-total-rows-stats-retrieve:- operation: data_warehouse_total_rows_stats_retrieve- enabled: false- data-warehouse-warehouse-status-retrieve:- operation: data_warehouse_warehouse_status_retrieve- enabled: false- external-data-schemas-cancel-create:- operation: external_data_schemas_cancel_create- enabled: false- external-data-schemas-create:- operation: external_data_schemas_create- enabled: false- external-data-schemas-delete-data-destroy:- operation: external_data_schemas_delete_data_destroy- enabled: false- external-data-schemas-destroy:- operation: external_data_schemas_destroy- enabled: false- external-data-schemas-incremental-fields-create:- operation: external_data_schemas_incremental_fields_create- enabled: false- external-data-schemas-list:- operation: external_data_schemas_list- enabled: false- external-data-schemas-partial-update:- operation: external_data_schemas_partial_update- enabled: false- external-data-schemas-reload-create:- operation: external_data_schemas_reload_create- enabled: false- external-data-schemas-resync-create:- operation: external_data_schemas_resync_create- enabled: false- external-data-schemas-retrieve:- operation: external_data_schemas_retrieve- enabled: false- external-data-schemas-update:- operation: external_data_schemas_update- enabled: false- external-data-sources-bulk-update-schemas-partial-update:- operation: external_data_sources_bulk_update_schemas_partial_update- enabled: false- external-data-sources-cdc-status-retrieve:- operation: external_data_sources_cdc_status_retrieve- enabled: false- external-data-sources-check-cdc-prerequisites-create:- operation: external_data_sources_check_cdc_prerequisites_create- enabled: false- external-data-sources-check-cdc-prerequisites-for-source-create:- operation: external_data_sources_check_cdc_prerequisites_for_source_create- enabled: false- external-data-sources-connect-link-retrieve:- operation: external_data_sources_connect_link_retrieve- enabled: false- external-data-sources-connections-list:- operation: external_data_sources_connections_list- enabled: false- external-data-sources-create:- operation: external_data_sources_create- enabled: false- external-data-sources-create-webhook-create:- operation: external_data_sources_create_webhook_create- enabled: false- external-data-sources-database-schema-create:- operation: external_data_sources_database_schema_create- enabled: false- external-data-sources-delete-webhook-create:- operation: external_data_sources_delete_webhook_create- enabled: false- external-data-sources-destroy:- operation: external_data_sources_destroy- enabled: false- external-data-sources-disable-cdc-create:- operation: external_data_sources_disable_cdc_create- enabled: false- external-data-sources-enable-cdc-create:- operation: external_data_sources_enable_cdc_create- enabled: false- external-data-sources-jobs-retrieve:- operation: external_data_sources_jobs_retrieve- enabled: false- external-data-sources-list:- operation: external_data_sources_list- enabled: false- external-data-sources-partial-update:- operation: external_data_sources_partial_update- enabled: false- external-data-sources-refresh-schemas-create:- operation: external_data_sources_refresh_schemas_create- enabled: false- external-data-sources-reload-create:- operation: external_data_sources_reload_create- enabled: false- external-data-sources-retrieve:- operation: external_data_sources_retrieve- enabled: false- external-data-sources-revenue-analytics-config-partial-update:- operation: external_data_sources_revenue_analytics_config_partial_update- enabled: false- external-data-sources-setup-create:- operation: external_data_sources_setup_create- enabled: false- external-data-sources-source-prefix-create:- operation: external_data_sources_source_prefix_create- enabled: false- external-data-sources-store-credentials-create:- operation: external_data_sources_store_credentials_create- enabled: false- external-data-sources-stored-credentials-list:- operation: external_data_sources_stored_credentials_list- enabled: false- external-data-sources-update:- operation: external_data_sources_update- enabled: false- external-data-sources-update-cdc-settings-create:- operation: external_data_sources_update_cdc_settings_create- enabled: false- external-data-sources-update-webhook-inputs-create:- operation: external_data_sources_update_webhook_inputs_create- enabled: false- external-data-sources-webhook-info-retrieve:- operation: external_data_sources_webhook_info_retrieve- enabled: false- external-data-sources-wizard-retrieve:- operation: external_data_sources_wizard_retrieve- enabled: false- fix-hogql-create:- operation: fix_hogql_create- enabled: false- fix-hogql-destroy:- operation: fix_hogql_destroy- enabled: false- fix-hogql-list:- operation: fix_hogql_list- enabled: false- fix-hogql-partial-update:- operation: fix_hogql_partial_update- enabled: false- fix-hogql-retrieve:- operation: fix_hogql_retrieve- enabled: false- fix-hogql-update:- operation: fix_hogql_update- enabled: false- insight-variables-create:- operation: insight_variables_create- enabled: false- insight-variables-destroy:- operation: insight_variables_destroy- enabled: false- insight-variables-list:- operation: insight_variables_list- enabled: false- insight-variables-partial-update:- operation: insight_variables_partial_update- enabled: false- insight-variables-retrieve:- operation: insight_variables_retrieve- enabled: false- insight-variables-update:- operation: insight_variables_update- enabled: false- lineage-get-upstream-retrieve:- operation: lineage_get_upstream_retrieve- enabled: false- managed-viewsets-retrieve:- operation: managed_viewsets_retrieve- enabled: false- managed-viewsets-update:- operation: managed_viewsets_update- enabled: false- query-tab-state-create:- operation: query_tab_state_create- enabled: false- query-tab-state-destroy:- operation: query_tab_state_destroy- enabled: false- query-tab-state-list:- operation: query_tab_state_list- enabled: false- query-tab-state-partial-update:- operation: query_tab_state_partial_update- enabled: false- query-tab-state-retrieve:- operation: query_tab_state_retrieve- enabled: false- query-tab-state-update:- operation: query_tab_state_update- enabled: false- query-tab-state-user-retrieve:- operation: query_tab_state_user_retrieve- enabled: false- warehouse-dag-list:- operation: warehouse_dag_list- enabled: false- warehouse-model-paths-list:- operation: warehouse_model_paths_list- enabled: false- warehouse-model-paths-retrieve:- operation: warehouse_model_paths_retrieve- enabled: false- warehouse-saved-queries-activity-retrieve:- operation: warehouse_saved_queries_activity_retrieve- enabled: false- warehouse-saved-queries-ancestors-create:- operation: warehouse_saved_queries_ancestors_create- enabled: false- warehouse-saved-queries-cancel-create:- operation: warehouse_saved_queries_cancel_create- enabled: false- warehouse-saved-queries-create:- operation: warehouse_saved_queries_create- enabled: false- warehouse-saved-queries-dependencies-retrieve:- operation: warehouse_saved_queries_dependencies_retrieve- enabled: false- warehouse-saved-queries-descendants-create:- operation: warehouse_saved_queries_descendants_create- enabled: false- warehouse-saved-queries-destroy:- operation: warehouse_saved_queries_destroy- enabled: false- warehouse-saved-queries-list:- operation: warehouse_saved_queries_list- enabled: false- warehouse-saved-queries-materialize-create:- operation: warehouse_saved_queries_materialize_create- enabled: false- warehouse-saved-queries-partial-update:- operation: warehouse_saved_queries_partial_update- enabled: false- warehouse-saved-queries-resume-schedules-create:- operation: warehouse_saved_queries_resume_schedules_create- enabled: false- warehouse-saved-queries-retrieve:- operation: warehouse_saved_queries_retrieve- enabled: false- warehouse-saved-queries-revert-materialization-create:- operation: warehouse_saved_queries_revert_materialization_create- enabled: false- warehouse-saved-queries-run-create:- operation: warehouse_saved_queries_run_create- enabled: false- warehouse-saved-queries-run-history-retrieve:- operation: warehouse_saved_queries_run_history_retrieve- enabled: false- warehouse-saved-queries-update:- operation: warehouse_saved_queries_update- enabled: false- warehouse-saved-query-drafts-create:- operation: warehouse_saved_query_drafts_create- enabled: false- warehouse-saved-query-drafts-destroy:- operation: warehouse_saved_query_drafts_destroy- enabled: false- warehouse-saved-query-drafts-list:- operation: warehouse_saved_query_drafts_list- enabled: false- warehouse-saved-query-drafts-partial-update:- operation: warehouse_saved_query_drafts_partial_update- enabled: false- warehouse-saved-query-drafts-retrieve:- operation: warehouse_saved_query_drafts_retrieve- enabled: false- warehouse-saved-query-drafts-update:- operation: warehouse_saved_query_drafts_update- enabled: false- warehouse-saved-query-folders-create:- operation: warehouse_saved_query_folders_create- enabled: false- warehouse-saved-query-folders-destroy:- operation: warehouse_saved_query_folders_destroy- enabled: false- warehouse-saved-query-folders-list:- operation: warehouse_saved_query_folders_list- enabled: false- warehouse-saved-query-folders-partial-update:- operation: warehouse_saved_query_folders_partial_update- enabled: false- warehouse-saved-query-folders-retrieve:- operation: warehouse_saved_query_folders_retrieve- enabled: false- warehouse-tables-create:- operation: warehouse_tables_create- enabled: false- warehouse-tables-destroy:- operation: warehouse_tables_destroy- enabled: false- warehouse-tables-file-create:- operation: warehouse_tables_file_create- enabled: false- warehouse-tables-list:- operation: warehouse_tables_list- enabled: false- warehouse-tables-partial-update:- operation: warehouse_tables_partial_update- enabled: false- warehouse-tables-refresh-schema-create:- operation: warehouse_tables_refresh_schema_create- enabled: false- warehouse-tables-retrieve:- operation: warehouse_tables_retrieve- enabled: false- warehouse-tables-update:- operation: warehouse_tables_update- enabled: false- warehouse-tables-update-schema-create:- operation: warehouse_tables_update_schema_create- enabled: false- warehouse-view-link-create:- operation: warehouse_view_link_create- enabled: false- warehouse-view-link-destroy:- operation: warehouse_view_link_destroy- enabled: false- warehouse-view-link-list:- operation: warehouse_view_link_list- enabled: false- warehouse-view-link-partial-update:- operation: warehouse_view_link_partial_update- enabled: false- warehouse-view-link-retrieve:- operation: warehouse_view_link_retrieve- enabled: false- warehouse-view-link-update:- operation: warehouse_view_link_update- enabled: false- warehouse-view-link-validate-create:- operation: warehouse_view_link_validate_create- enabled: false- warehouse-view-links-create:- operation: warehouse_view_links_create- enabled: false- warehouse-view-links-destroy:- operation: warehouse_view_links_destroy- enabled: false- warehouse-view-links-list:- operation: warehouse_view_links_list- enabled: false- warehouse-view-links-partial-update:- operation: warehouse_view_links_partial_update- enabled: false- warehouse-view-links-retrieve:- operation: warehouse_view_links_retrieve- enabled: false- warehouse-view-links-update:- operation: warehouse_view_links_update- enabled: false- warehouse-view-links-validate-create:- operation: warehouse_view_links_validate_create- enabled: falsediff --git a/services/mcp/scripts/scaffold-yaml.ts b/services/mcp/scripts/scaffold-yaml.tsindex c575da15ccd9..020d41730ead 100644--- a/services/mcp/scripts/scaffold-yaml.ts+++ b/services/mcp/scripts/scaffold-yaml.ts@@ -2,8 +2,11 @@/*** Scaffolds YAML tool definitions from the OpenAPI schema.*- * Discovers operations using x-product (priority 1) and URL path- * substring matching (fallback), same approach as generate-openapi-types.mjs.+ * Discovers operations by the x-product values the spec emits per operation:+ * auto-derived from the ViewSet module path (products/<name>/backend/) or+ * declared explicitly via @extend_schema(extensions={"x-product": "<name>"}).+ * There is deliberately no URL-based guessing — paths are a lossy projection+ * of ownership and used to poach operations across products.** Idempotent: re-running on an existing file only adds newly discovered* operations and removes stale ones. All hand-authored config is preserved.@@ -94,28 +97,32 @@ function operationIdToToolName(operationId: string): string {}/**- * Find operations by x-product — same priority-1 approach as- * frontend/bin/generate-openapi-types.mjs resolveTagToProduct().- * Values are set via @extend_schema(tags=[...]) or auto-derived from- * the ViewSet module path (products/<name>/backend/ → "<name>").+ * Find operations whose x-product list names this product. Values are+ * auto-derived from the ViewSet module path (products/<name>/backend/ →+ * "<name>") or declared via @extend_schema(extensions={"x-product": "..."}).+ * Both sides are normalized (kebab → snake) so hyphenated definition+ * filenames like proxy-records match the snake_case x-product value.*/-function findOperationsByTag(spec: OpenApiSpec, product: string): DiscoveredOperation[] {+function findOperationsByProduct(spec: OpenApiSpec, product: string): DiscoveredOperation[] {const ops: DiscoveredOperation[] = []const httpMethods = new Set(['get', 'post', 'put', 'patch', 'delete'])- const matchingTags = new Set([- product,- ...Object.entries(productAliases)- .filter(([, target]) => target === product)- .map(([source]) => source),- ])+ const normalize = (name: string): string => name.toLowerCase().replace(/-/g, '_')+ const matchingProducts = new Set(+ [+ product,+ ...Object.entries(productAliases)+ .filter(([, target]) => target === product)+ .map(([source]) => source),+ ].map(normalize)+ )for (const [urlPath, methods] of Object.entries(spec.paths)) {for (const [method, op] of Object.entries(methods)) {if (!httpMethods.has(method) || !op?.operationId || op.deprecated) {continue}- const tags = op['x-product'] ?? []- if (tags.some((tag) => matchingTags.has(tag.replace(/-/g, '_')))) {+ const xProduct = op['x-product'] ?? []+ if (xProduct.some((value) => matchingProducts.has(normalize(value)))) {ops.push({operationId: op.operationId,method: method.toUpperCase(),@@ -129,87 +136,6 @@ function findOperationsByTag(spec: OpenApiSpec, product: string): DiscoveredOperreturn ops}-/**- * Find operations whose URL path contains /{product}/ — fallback when- * x-product doesn't match, same as generate-openapi-types.mjs- * matchUrlToProduct().- */-function findOperationsByUrl(spec: OpenApiSpec, product: string, syncedProducts?: Set<string>): DiscoveredOperation[] {- const ops: DiscoveredOperation[] = []- const httpMethods = new Set(['get', 'post', 'put', 'patch', 'delete'])- const productsToMatch = [- product,- ...Object.entries(productAliases)- .filter(([, target]) => target === product)- .map(([source]) => source),- ]- const needles = productsToMatch.map((productName) => `/${productName.replace(/-/g, '_').toLowerCase()}/`)-- for (const [urlPath, methods] of Object.entries(spec.paths)) {- const normalizedPath = urlPath.toLowerCase().replace(/-/g, '_')- if (!needles.some((needle) => normalizedPath.includes(needle))) {- continue- }-- for (const [method, op] of Object.entries(methods)) {- if (!httpMethods.has(method) || !op?.operationId || op.deprecated) {- continue- }-- // Don't let the URL fallback poach an op that another *synced* product- // already owns via x-product — e.g. agent .../sessions/{id}/logs/ is- // tagged agent_platform but its path matches the logs product. Ops whose- // x-product isn't a synced product (e.g. reverse_proxy ops grouped under- // the proxy-records definition) still match by path, as do legacy ops- // with no x-product.- if (syncedProducts) {- const normProduct = product.replace(/-/g, '_').toLowerCase()- const xProduct = (op['x-product'] ?? []).map((p) => p.replace(/-/g, '_').toLowerCase())- if (!xProduct.includes(normProduct) && xProduct.some((p) => syncedProducts.has(p))) {- continue- }- }-- ops.push({- operationId: op.operationId,- method: method.toUpperCase(),- path: urlPath,- description: op.summary || op.description,- })- }- }-- return ops-}--/**- * Find operations for a product. Uses the same priority as- * frontend/bin/generate-openapi-types.mjs:- * 1. x-product match (covers ViewSets with @extend_schema(tags=[...])- * and ViewSets in products/<name>/backend/)- * 2. URL path substring match (fallback for legacy endpoints)- */-function findOperationsByProduct(- spec: OpenApiSpec,- product: string,- syncedProducts?: Set<string>-): DiscoveredOperation[] {- const byTag = findOperationsByTag(spec, product)- const byUrl = findOperationsByUrl(spec, product, syncedProducts)-- // Merge, preferring tag-matched ops and deduping by operationId- const seen = new Set(byTag.map((op) => op.operationId))- const merged = [...byTag]- for (const op of byUrl) {- if (!seen.has(op.operationId)) {- merged.push(op)- seen.add(op.operationId)- }- }-- return merged-}-function findOperationsByPath(spec: OpenApiSpec, pathPrefix: string): DiscoveredOperation[] {const ops: DiscoveredOperation[] = []const httpMethods = new Set(['get', 'post', 'put', 'patch', 'delete'])@@ -458,19 +384,16 @@ function syncAll(spec: OpenApiSpec): void {const writtenFiles: string[] = []const noOpsProducts: string[] = []- // Every product/definition being synced, normalized. The URL fallback uses this- // to avoid poaching an op that another synced product owns via x-product.- const syncedProducts = new Set(targets.map((t) => t.product.replace(/-/g, '_').toLowerCase()))-for (const { product, filePath, subset } of targets) {- const rawOps = findOperationsByProduct(spec, product, syncedProducts)+ const rawOps = findOperationsByProduct(spec, product)const ops = deduplicateOperations(rawOps)if (ops.length === 0) {const label = path.relative(REPO_ROOT, filePath)const normalized = product.replace(/-/g, '_').toLowerCase()process.stderr.write(`⚠ ${label}: no operations found in OpenAPI for "${product}"\n` +- ` → ensure the ViewSet has @extend_schema(tags=["${normalized}"]) or the URL contains /${normalized}/\n`+ ` → declare @extend_schema(extensions={"x-product": "${normalized}"}) on the ViewSet, ` ++ `or place it in products/${normalized}/backend/ for module-path auto-attribution\n`)noOpsProducts.push(label)continue@@ -505,7 +428,7 @@ function syncAll(spec: OpenApiSpec): void {process.stdout.write(`${label}: ${parts.join(', ')}\n`)if (unmatchedTools.length > 0) {process.stderr.write(- ` ⚠ ${unmatchedTools.length} tool(s) not found in OpenAPI — add @extend_schema(tags=["${product}"]) to the ViewSet\n`+ ` ⚠ ${unmatchedTools.length} tool(s) not found in OpenAPI — add @extend_schema(extensions={"x-product": "${product}"}) to the ViewSet\n`)for (const tool of unmatchedTools) {process.stderr.write(` - ${tool}\n`)@@ -550,7 +473,8 @@ function main(): void {console.error(' scaffold-yaml --path <prefix> [--output <file>]')console.error(' scaffold-yaml --sync-all')console.error('')- console.error('--product discovers endpoints by x-product first, then URL path fallback.')+ console.error('--product discovers endpoints by x-product: module-path auto-attribution,')+ console.error('or declared explicitly via @extend_schema(extensions={"x-product": "..."}).')console.error('Uses the product folder name (underscores), e.g. error_tracking, workflows.')process.exit(1)}