: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
feat(autoresearch): expose the API as MCP tools (#101569)
Andrew Maguirec25525c98445
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.tsindex 9361799baa13..a2963c401bb8 100644--- a/frontend/src/lib/agentScopes.generated.ts+++ b/frontend/src/lib/agentScopes.generated.ts@@ -20,6 +20,8 @@ export const AGENT_USE_CASE_SCOPES = ['annotation:write','approvals:read','approvals:write',+ 'autoresearch:read',+ 'autoresearch:write','batch_export:read','batch_export:write','billing:read',diff --git a/products/autoresearch/AGENTS.md b/products/autoresearch/AGENTS.mdindex e8557476d231..062c78218435 100644--- a/products/autoresearch/AGENTS.md+++ b/products/autoresearch/AGENTS.md@@ -8,7 +8,7 @@ The framing is Karpathy's `autoresearch` prompt pattern: an agent edits one thinHere the "one thing" is a feature set plus a model spec, the fixed eval is holdout AUC on a labeled training population, and the loop runs inside a Tasks sandbox.This directory holds the data model, the access gate, and the backend packages that have landed so far; each package has its own `AGENTS.md`.-The training loop, inference, evaluation, the API, the MCP tools, and the frontend land in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).+The frontend lands in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).## Data model in one passdiff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.mdindex a5ba64c171ea..2b0315a12726 100644--- a/products/autoresearch/backend/presentation/AGENTS.md+++ b/products/autoresearch/backend/presentation/AGENTS.md@@ -5,7 +5,7 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably mThese serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.-The `autoresearch-*` MCP tools that expose this API to the sandbox agent arrive at the end of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).+The `autoresearch-*` MCP tools that expose this API to the sandbox agent are declared in `../../mcp/tools.yaml`.## What lives herediff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex 9896456fb4a0..8e332651dd3c 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -1648,10 +1648,7 @@ class PopulationSpecField(serializers.JSONField):class ResolveTemplateRequestSerializer(serializers.Serializer):template_key = serializers.ChoiceField(choices=TEMPLATE_KEY_CHOICES,- help_text=(- "Template to resolve. Use autoresearch-templates-list to see all available templates "- "with descriptions. Required."- ),+ help_text="Template to resolve. The templates endpoint lists each one with its description. Required.",)target_event = serializers.CharField(required=False,diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex 2a5f531d1f81..33ab992d5c77 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -1342,7 +1342,7 @@ export const TemplateKeyEnumApi = {} as constexport interface ResolveTemplateRequestApi {- /** Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.+ /** Template to resolve. The templates endpoint lists each one with its description. Required.** * `likely_active_soon` - Likely Active Soon* * `at_risk_of_inactivity` - At Risk Of Inactivitydiff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.tsindex 0ac7f62e138a..67e7b0ee9188 100644--- a/products/autoresearch/frontend/generated/api.zod.ts+++ b/products/autoresearch/frontend/generated/api.zod.ts@@ -641,7 +641,7 @@ export const AutoresearchResolveTemplateCreateBody = /* @__PURE__ */ zod.object('\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior').describe(- 'Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.\n\n\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'+ 'Template to resolve. The templates endpoint lists each one with its description. Required.\n\n\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'),target_event: zod.string()diff --git a/products/autoresearch/mcp/AGENTS.md b/products/autoresearch/mcp/AGENTS.mdnew file mode 100644index 000000000000..bce81e609b7f--- /dev/null+++ b/products/autoresearch/mcp/AGENTS.md@@ -0,0 +1,65 @@+# MCP tools++The `autoresearch-*` tool surface. Unusually for a PostHog product, these tools are not primarily for users or for Max — **they are how the training agent operates the product on itself.**++During a run, the sandbox agent has no other write path. It records iterations, materializes features, uploads its bundle, and finalizes its run entirely through these tools. Everything a tool description does not say, the agent has to guess.++## What lives here++- `tools.yaml`+ The whole surface: 20 enabled tools, `category: Autoresearch`, `feature: autoresearch`, `url_prefix: /` until the list scene lands its route. The family must stay at or below 25 tools: above that the exec tool's compact domain index splits it into sub-domains, and the serialized exec schema crosses the claude.ai registry cap (see `services/mcp/tests/unit/instructions-formatter-snapshot.test.ts`). Duplicative tools (`suggestions-retrieve`, `templates-list`, `validate-online-create`, `artifacts-delete-create`) are disabled rather than removed. `resolve-template-create` names every template key, so it replaces `templates-list` as the template entry point.+ Each entry names an `operation` (an operation id from the OpenAPI spec), an `enabled` flag, required `scopes` (`autoresearch:read` / `autoresearch:write`, plus every extra scope the endpoint's `required_scopes` names, such as `query:read`: MCP hides a tool whose scopes the key lacks), `annotations` (`readOnly`, `destructive`, `idempotent`), and a `title` + `description`.++Tool entries are scaffolded from the OpenAPI schema — `pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all` keeps the tool list and operation ids in sync. Everything editorial (description, title, `enrich_url`, `exclude_params`) is yours to write.++## The two tool families++**Agent-facing** — the training loop's own control surface, backed by `AutoresearchTrainingRunViewSet`:++`autoresearch-training-runs-iterations-create`, `-materialize-features`, `-artifacts-upload-create`, `-artifacts-get-create`, `-artifacts-retrieve`, `-complete-create`, `-history`.++**Bring-your-own agents** — an agent that trains outside PostHog (for example on a laptop) calls `autoresearch-training-runs-create` to open a run, then the agent-facing tools above except `-materialize-features`, which writes into a PostHog sandbox; it pulls data with `execute-sql` instead. A sandbox request to open a run is refused.++**User-facing** — creating and inspecting pipelines: `autoresearch-resolve-template-create`, `-validate-create`, `-create`, `-train-create`, `-list`, `-retrieve`, `-training-runs-list`, `-suggestions-create`, `-suggestions-list` (to read the agent's response).++Pipeline lifecycle (`archive`, `pause`, `resume`), manual `score`, and the inference-run list stay disabled: the UI covers the lifecycle, the daily workflows score, and nothing agent-driven needs the rest yet. Enabling one is a one-line change here.++The split matters when you change a description. An agent-facing description is a **contract**: `autoresearch-training-runs-iterations-create` has to tell the agent what a valid `feature_sql` looks like, because the server will reject anything that is not a read-only `SELECT` keyed on `person_id` and the agent has no other way to learn that.++## Descriptions are the product++The descriptions here already do real work, and that is the standard to hold. Examples of what "good" looks like in this file:++- `autoresearch-create` spells out the mutual exclusion — pass `target_event` _or_ `target_definition`, exactly one — and names the next call (`autoresearch-train-create`).+- It also tells the caller to run `autoresearch-validate-create` first _and_ warns that the endpoint does not block on validation errors, so the model knows the check is advisory.+- `autoresearch-train-create` says what happens to the existing champion on a retrain and names every refusal (run in progress, paused pipeline, no PostHog Desktop access).++Write for a model that has read nothing else. Name the prerequisite call, the next call, and the failure mode.++## Cross-run memory++These tools are also how a run learns from previous ones. A training agent can call `autoresearch-models-list` and `autoresearch-training-runs-history` on _sibling_ pipelines and build on what already worked — that behavior has been observed in practice, with a run opening by reading an earlier pipeline's champion recipe and using it as its baseline.++That makes the read tools load-bearing for model quality, not just for introspection. Do not disable or narrow them casually.++## Where the rest of the system meets this file++- **Backed by** — `../backend/presentation/views/views.py`. A tool is only as good as its serializer annotations; `help_text` and `@extend_schema` flow directly into these schemas.+- **Generated into** — `services/mcp/src/tools/generated/autoresearch.ts` and `services/mcp/src/generated/autoresearch/api.ts`.+- **Consumed by** — the sandbox agent during `../backend/training/` runs, plus any normal MCP client.++## `enrich_url` needs a documented response schema++`enrich_url: '{id}'` makes the generated handler read `result.id`, so the operation's **response** type has to actually carry that field.++This broke once: `autoresearch-create` failed MCP typecheck with `Property 'id' does not exist on type 'AutoresearchPipelineCreate'`. The endpoint returned the read serializer at runtime but only declared the write one, so drf-spectacular typed the response as the request body — which has no `id`. Fixed by declaring `responses={201: AutoresearchPipelineSerializer}` on the viewset's `create`.++If you add `enrich_url` to a tool, check the operation's declared response schema contains the field you interpolate. Fix it on the endpoint and regenerate; never patch the generated file.++## When editing this file++- **Adding an endpoint does not expose it.** A tool exists only once it has an entry here with `enabled: true`.+- Set `scopes` and `annotations` deliberately — `readOnly` and `destructive` change how clients treat a tool.+- Prefer improving the serializer's `help_text` over writing a longer tool description; the serializer feeds the frontend types too, so the fix lands in both places.+- After any change run `pnpm --filter=@posthog/mcp run typecheck` and commit the regenerated files — CI checks for drift.+- **If you add or retire a tool, update this file to match.**diff --git a/products/autoresearch/mcp/CLAUDE.md b/products/autoresearch/mcp/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/autoresearch/mcp/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yamlnew file mode 100644index 000000000000..4b79898f3690--- /dev/null+++ b/products/autoresearch/mcp/tools.yaml@@ -0,0 +1,663 @@+# 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: Autoresearch+feature: autoresearch+url_prefix: /+ui_apps: {}+tools:+ autoresearch-archive-create:+ operation: autoresearch_archive_create+ enabled: false+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Archive pipeline+ description: >+ Soft-delete a pipeline. Stops daily scoring and training. Prediction history and model artifacts are+ preserved. Archived pipelines are excluded from autoresearch-list. Refused while a training run is in+ progress. There is no unarchive, so use autoresearch-pause-create to stop a pipeline temporarily.+ feature_flag: autoresearch+ autoresearch-create:+ operation: autoresearch_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create a pipeline+ description: >+ Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this+ endpoint does not block on validation errors. The prediction target is either an event (pass target_event,+ e.g. '$pageview') or a PostHog action (pass target_definition = {"type": "action", "action_id": N} to+ predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display+ label and the source of the derived output property name). An action target needs the action:read scope.+ horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from+ target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique+ among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an+ asynchronous agent training run.+ exclude_params:+ - id+ - created_by+ - created_at+ - updated_at+ - last_scored_at+ - status+ - iteration_budget_remaining+ feature_flag: autoresearch+ autoresearch-destroy:+ operation: autoresearch_destroy+ enabled: false+ autoresearch-list:+ operation: autoresearch_list+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List pipelines+ description: >+ List autoresearch prediction pipelines for the current project. Archived pipelines are excluded. Each+ pipeline entry includes its status (draft, bootstrapping, running, converged, paused), target event,+ horizon, and timestamps. Use autoresearch-retrieve to get full details including population definitions.+ feature_flag: autoresearch+ response:+ include:+ - id+ - name+ - description+ - target_event+ - horizon_days+ - status+ - iteration_budget+ - iteration_budget_remaining+ - last_scored_at+ - created_at+ - updated_at+ autoresearch-materialize-features:+ operation: autoresearch_training_runs_materialize_features_create+ enabled: true+ scopes:+ - autoresearch:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Materialize training features to the sandbox+ description: >+ Run your features.sql server-side against the labeled training population and write the train/holdout+ feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path,+ train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list —+ the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the+ returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it+ whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog+ sandbox; an agent training outside PostHog pulls its data with execute-sql instead.+ feature_flag: autoresearch+ autoresearch-models-list:+ operation: autoresearch_models_list+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List models for a pipeline+ description: >+ List champion, challenger, and archived model versions for a pipeline. Each model includes its+ holdout_score, role, recipe_hash, is_preliminary flag, and agent_description. The active scoring model has+ role='champion'. Use the recipe_hash to detect when the champion has changed across training runs.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - role+ - recipe_hash+ - holdout_score+ - realized_score+ - is_preliminary+ - agent_description+ - trained_on_start+ - trained_on_end+ - promoted_at+ - created_at+ autoresearch-models-retrieve:+ operation: autoresearch_models_retrieve+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get model+ description: >+ Get full details for a specific model version, including the portable model recipe (feature SQL, transforms,+ model class, params) and feature importance explanation.+ feature_flag: autoresearch+ autoresearch-partial-update:+ operation: autoresearch_partial_update+ enabled: false+ autoresearch-pause-create:+ operation: autoresearch_pause_create+ enabled: false+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Pause pipeline+ description: >+ Pause a running pipeline. Daily scoring and training stop until the pipeline is resumed. A training run+ already in progress finishes and can promote a new champion, but the pipeline scores nobody until it is+ resumed. Use autoresearch-resume-create to restart.+ feature_flag: autoresearch+ autoresearch-resolve-template-create:+ operation: autoresearch_resolve_template_create+ enabled: true+ scopes:+ - autoresearch:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Resolve a template+ description: >+ Start here to create a pipeline from a template. Resolve a template key and optional overrides into a+ ready-to-use pipeline config. An unknown key returns 400. For activity-based templates+ ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved+ from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve+ with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior',+ supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved+ target_event, horizon_days, training_lookback_days, training_population and inference_population, so+ validation counts the same window the pipeline will use; (2) if can_proceed is true, call+ autoresearch-create with name set to suggested_name and the same five fields plus output_person_property.+ For an action target, pass the same target_definition to both calls; target_event then only labels it, and+ both calls need the action:read scope.+ exclude_params:+ - resolved_activity_event+ - activity_event_alternatives+ - display_name+ - description+ - notes+ feature_flag: autoresearch+ autoresearch-resume-create:+ operation: autoresearch_resume_create+ enabled: false+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Resume pipeline+ description: |+ Resume a paused pipeline. Returns 400 if the pipeline is not currently paused.+ feature_flag: autoresearch+ autoresearch-retrieve:+ operation: autoresearch_retrieve+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get pipeline+ description: >+ Get full details for a specific autoresearch pipeline by ID, including population definitions, training+ configuration, and current status.+ feature_flag: autoresearch+ response:+ exclude:+ - created_by+ autoresearch-runs-list:+ operation: autoresearch_runs_list+ enabled: false+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List inference runs+ description: >+ List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status+ to understand scoring history. run_type is 'inference' for daily scoring runs.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - model+ - run_type+ - status+ - rows_scored+ - error+ - started_at+ - completed_at+ - created_at+ autoresearch-runs-retrieve:+ operation: autoresearch_runs_retrieve+ enabled: false+ autoresearch-score-create:+ operation: autoresearch_score_create+ enabled: false+ scopes:+ - autoresearch:write+ - query:read+ - person:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ title: Run inference (score users)+ description: >+ Score the inference population using the champion model and emit 'autoresearch_prediction' events for each+ user. Returns the inference run object with rows_scored and status. Requires a champion model and a pipeline+ that is not paused — run autoresearch-train-create first if the pipeline has no champion. A pipeline with an+ action target also needs the action:read scope. Each scored user gets a '$autoresearch_p_y' property on+ their prediction event and a person property update. After scoring, query predictions with execute-sql:+ SELECT distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND+ properties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.+ feature_flag: autoresearch+ autoresearch-suggestions-create:+ operation: autoresearch_suggestions_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Submit a suggestion+ description: >+ Inject a free-text hypothesis or direction into a running pipeline for the sandbox agent to consider. The+ agent reads queued suggestions at the start of each training batch and decides whether to translate the+ suggestion into a concrete iteration ('acted_on'), apply it as a search constraint ('picked_up'), or reject+ it with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before+ autonomous iterations; 'consider' (default) is advisory. Check 'agent_response' after the next training run+ to see how the suggestion was interpreted. Examples: 'try a gradient boosting model', 'remove recency+ features — I suspect leakage', 'the target event has a 7-day spike on Mondays, account for day-of-week'.+ Suggestions survive pipeline pauses and are included in the next training batch when the pipeline resumes.+ exclude_params:+ - source+ - status+ - agent_response+ - created_by+ - linked_iteration_ids+ feature_flag: autoresearch+ autoresearch-suggestions-list:+ operation: autoresearch_suggestions_list+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List suggestions+ description: >+ List steering suggestions for a pipeline, ordered most recent first. Each entry shows the prompt, priority,+ status (queued/picked_up/acted_on/dismissed), and the agent's response when available. Use+ 'linked_iteration_ids' to trace which iterations were spawned from a suggestion.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - prompt+ - priority+ - status+ - source+ - agent_response+ - linked_iteration_ids+ - created_at+ autoresearch-suggestions-respond:+ operation: autoresearch_suggestions_respond_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Respond to a suggestion+ description: >+ Record how you handled a steering suggestion so the human who submitted it sees the outcome (it stays+ 'queued' in the UI until you do). Set status to 'picked_up' (applied as a search constraint across+ iterations), 'acted_on' (spawned one or more iterations from it), or 'dismissed' (rejected — explain why in+ agent_response), and write a one-line agent_response. Recording an iteration with parent_suggestion set+ already advances a suggestion to 'acted_on'; use this tool to add the narrative or to mark a suggestion+ picked_up/dismissed without a dedicated iteration.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - status+ - agent_response+ - linked_iteration_ids+ autoresearch-suggestions-retrieve:+ operation: autoresearch_suggestions_retrieve+ enabled: false+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get suggestion+ description: |+ Get full details for a specific suggestion including its status and agent_response.+ feature_flag: autoresearch+ autoresearch-templates-list:+ operation: autoresearch_templates_list+ enabled: false+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List available templates+ description: >+ List all built-in autoresearch prediction templates. Each entry includes the template key, display name,+ description, default horizon, prediction mode, and whether you need to supply a target_event. Templates:+ 'likely_active_soon' (best universal starter — predicts next-7d activity), 'at_risk_of_inactivity' (predicts+ 14d inactivity risk), 'return_after_first_use' (predicts new-user return within 7d), 'feature_adoption'+ (predicts first use of your chosen event within 14d — requires target_event), 'repeat_key_behavior'+ (predicts repeat use of your chosen event within 7d — requires target_event). After picking a template, call+ autoresearch-resolve-template-create to get a resolved pipeline config.+ feature_flag: autoresearch+ autoresearch-train-create:+ operation: autoresearch_train_create+ enabled: true+ scopes:+ - autoresearch:write+ - query:read+ - insight:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Start training+ description: >+ Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns+ the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run+ reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side+ promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if+ a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid+ (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog+ Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job+ scores the inference population and emits autoresearch_prediction events. You can optionally override the+ iteration_budget for this run. A pipeline with an action target also needs the action:read scope.+ feature_flag: autoresearch+ autoresearch-training-runs-artifacts-delete-create:+ operation: autoresearch_training_runs_artifacts_delete_create+ enabled: false+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete an artifact bundle file+ description: >+ Remove one file from a training run's artifact bundle. Idempotent — deleting a missing file is a no-op. Only+ allowed while the run is still running; the bundle is frozen once the run completes or fails.+ feature_flag: autoresearch+ autoresearch-training-runs-artifacts-get-create:+ operation: autoresearch_training_runs_artifacts_get_create+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get an artifact bundle file+ description: >+ Fetch one file from a training run's artifact bundle, base64-encoded. Use this to read the prior champion's+ train.py / features.sql as a starting point before iterating (look up the champion's source_training_run via+ autoresearch-models-retrieve).+ feature_flag: autoresearch+ autoresearch-training-runs-artifacts-retrieve:+ operation: autoresearch_training_runs_artifacts_retrieve+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List artifact bundle files+ description: >+ List the files uploaded for a training run's artifact bundle (train.py, predict.py, features.sql, and any+ eda/ notebooks). Use to confirm a complete bundle is present before finalizing the run.+ feature_flag: autoresearch+ autoresearch-training-runs-artifacts-upload-create:+ operation: autoresearch_training_runs_artifacts_upload_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Upload an artifact bundle file+ description: >+ Upload one file of a training run's runnable model bundle. Send the file contents base64-encoded in+ content_base64; path is the relative path within the bundle (train.py, predict.py, features.sql, or an eda/+ notebook). Re-uploading the same path overwrites it. Keep each file under about 700 KB: the base64 body must+ fit the MCP server's 1 MiB request limit. A bundle holds at most 32 files. This is how you author the model+ — author train.py and predict.py (standalone sklearn scripts; the framework runs `python train.py+ <train_features.parquet> <train_labels.parquet> <model.pkl> <output.json> <holdout_features.parquet>+ <holdout_labels.parquet> --random-state N`, which pickles {"model", "feature_cols"} and writes+ {"holdout_auc", "n_train", "n_features"} to output.json, and `python predict.py <score_features.parquet>+ <model.pkl> <scores.parquet>`, which writes distinct_id,p_y; features parquet is distinct_id plus numeric+ columns, labels parquet is distinct_id,__label) and features.sql (HogQL with the {anchors}/{lookback_days}+ contract), then upload each here. Do NOT use set_output or curl — the bundle you upload is what inference+ runs in a sandbox. Only allowed while the run is still running; the bundle is frozen once the run completes+ or fails.+ feature_flag: autoresearch+ autoresearch-training-runs-complete-create:+ operation: autoresearch_training_runs_complete_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Complete a training run+ description: >+ Finalize a training run. The backend selects the kept iteration with the highest holdout_score.+ best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle+ of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder+ (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot+ set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the+ resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the+ model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a+ future run should try next) — these are stored in the run summary and read back by the next run during+ orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded+ iterations.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - status+ - iteration_count+ - best_holdout_score+ - summary+ - error+ - completed_at+ autoresearch-training-runs-create:+ operation: autoresearch_training_runs_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Open a training run+ description: >+ Open a new training run for a pipeline and return its id, for a bring-your-own agent that trains outside+ PostHog. The agent then records iterations against this run with+ autoresearch-training-runs-iterations-create and finalizes it with+ autoresearch-training-runs-complete-create. The run starts in 'running'. Optionally override the+ iteration_budget for this run. Refused from inside a sandbox: the in-house training agent works in the run+ that autoresearch-train-create opened for it. A pipeline with an action target also needs the action:read+ scope.+ feature_flag: autoresearch+ autoresearch-training-runs-history:+ operation: autoresearch_training_runs_history_retrieve+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Read prior training-run history+ description: >+ Cross-run learning memory. Returns recent completed training runs — this pipeline first, then same-target+ sibling pipelines on the team. Each run has a distilled `summary` (read this first: distillation,+ recommended_next, the kept_ladder of winning approaches, and dead_ends to avoid) plus the full `iterations`+ trail (every recipe tried, its agent_description rationale, holdout_score, kept/discarded status,+ model_spec) to drill into when a summary points somewhere worth it. Call this before iterating to reuse the+ features and transforms that won and avoid repeating approaches already discarded. Optional `limit` (default+ 5, max 20) caps how many prior runs are returned.+ feature_flag: autoresearch+ autoresearch-training-runs-iterations-create:+ operation: autoresearch_training_runs_iterations_create+ enabled: true+ scopes:+ - autoresearch:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Record a training iteration+ description: >+ Record one iteration of an open training run. Idempotent on iteration_number — re-sending the same number+ updates that iteration in place. The recipe is validated server-side: feature_sql in recipe_snapshot must be+ a read-only SELECT that outputs the anchor key exactly once as a.person_id AS distinct_id, and every events+ join must be bounded by e.timestamp < fromUnixTimestamp(a.cutoff_ts) and exclude NOT startsWith(e.event,+ 'autoresearch_'), the model's own prediction events. The validator cannot prove either rule, and without+ them the features see the outcome window or the model's own past scores, and the holdout AUC is leaked.+ model_class in model_spec is informational when you upload your own train.py and predict.py bundle; it must+ be in the sklearn/xgboost allowlist only when the run completes without a bundle. Use status='kept' if the+ iteration beats the best AUC so far in this run (the first scored iteration is always kept, whatever the+ current champion scores), 'discarded' otherwise, 'crashed' on failure. Iterations are picked up at+ completion time to choose the champion. If this iteration was spawned from a pending steering suggestion,+ pass parent_suggestion = the suggestion's ID — that links the iteration to the suggestion for attribution+ and marks the suggestion 'acted_on'.+ feature_flag: autoresearch+ response:+ include:+ - id+ - training_run+ - iteration_number+ - recipe_hash+ - train_score+ - holdout_score+ - status+ - parent_suggestion+ autoresearch-training-runs-list:+ operation: autoresearch_training_runs_list+ enabled: true+ scopes:+ - autoresearch:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List training runs+ description: >+ List training runs for a pipeline, ordered most recent first. Check status (completed/failed),+ iteration_count, and best_holdout_score to understand training history.+ feature_flag: autoresearch+ response:+ include:+ - id+ - pipeline+ - status+ - iteration_budget+ - iteration_count+ - best_holdout_score+ - error+ - started_at+ - completed_at+ - created_at+ autoresearch-training-runs-retrieve:+ operation: autoresearch_training_runs_retrieve+ enabled: false+ autoresearch-update:+ operation: autoresearch_update+ enabled: false+ autoresearch-validate-create:+ operation: autoresearch_validate_create+ enabled: true+ scopes:+ - autoresearch:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Validate a pipeline definition+ description: >+ Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass+ target_event) or a PostHog action (pass target_definition = {"type": "action", "action_id": N}); base-rate+ and volume estimates are computed against whichever you provide. Returns volume estimates, base rate,+ positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling+ autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking+ warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or+ low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above+ horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings+ include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the+ action:read scope. Always validate before creating.+ feature_flag: autoresearch+ autoresearch-validate-online-create:+ operation: autoresearch_validate_online_create+ enabled: false+ scopes:+ - autoresearch:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Run online validation+ description: >+ Validate predictions against realized outcomes for all matured prediction dates. A prediction date is+ matured when today >= prediction_date + horizon_days — meaning the outcome window has closed and+ ground-truth labels can be fetched. Computes per-model realized AUC, Brier score, expected calibration error+ (ECE), and lift@10/20. Updates the model's realized_score and calibration_error in Postgres, and clears the+ is_preliminary flag after the first successful validation cycle. Already-validated dates are skipped+ automatically. Returns one run object per prediction date processed; an empty list means no dates have+ matured yet. In production this is triggered by the daily Temporal validation workflow after inference runs.+ Call autoresearch-models-list after this to see updated realized_score values on champion/challenger models.+ feature_flag: autoresearchdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex eba1fbb779e9..44f1580b89fd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1089,6 +1089,306 @@"readOnlyHint": true}},+ "autoresearch-create": {+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an asynchronous agent training run.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Create a pipeline",+ "title": "Create a pipeline",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-list": {+ "description": "List autoresearch prediction pipelines for the current project. Archived pipelines are excluded. Each pipeline entry includes its status (draft, bootstrapping, running, converged, paused), target event, horizon, and timestamps. Use autoresearch-retrieve to get full details including population definitions.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List pipelines",+ "title": "List pipelines",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-materialize-features": {+ "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Materialize training features to the sandbox",+ "title": "Materialize training features to the sandbox",+ "required_scopes": ["autoresearch:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-models-list": {+ "description": "List champion, challenger, and archived model versions for a pipeline. Each model includes its holdout_score, role, recipe_hash, is_preliminary flag, and agent_description. The active scoring model has role='champion'. Use the recipe_hash to detect when the champion has changed across training runs.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List models for a pipeline",+ "title": "List models for a pipeline",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-models-retrieve": {+ "description": "Get full details for a specific model version, including the portable model recipe (feature SQL, transforms, model class, params) and feature importance explanation.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get model",+ "title": "Get model",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-resolve-template-create": {+ "description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Resolve a template",+ "title": "Resolve a template",+ "required_scopes": ["autoresearch:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-retrieve": {+ "description": "Get full details for a specific autoresearch pipeline by ID, including population definitions, training configuration, and current status.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get pipeline",+ "title": "Get pipeline",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-create": {+ "description": "Inject a free-text hypothesis or direction into a running pipeline for the sandbox agent to consider. The agent reads queued suggestions at the start of each training batch and decides whether to translate the suggestion into a concrete iteration ('acted_on'), apply it as a search constraint ('picked_up'), or reject it with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before autonomous iterations; 'consider' (default) is advisory. Check 'agent_response' after the next training run to see how the suggestion was interpreted. Examples: 'try a gradient boosting model', 'remove recency features — I suspect leakage', 'the target event has a 7-day spike on Mondays, account for day-of-week'. Suggestions survive pipeline pauses and are included in the next training batch when the pipeline resumes.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Submit a suggestion",+ "title": "Submit a suggestion",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-list": {+ "description": "List steering suggestions for a pipeline, ordered most recent first. Each entry shows the prompt, priority, status (queued/picked_up/acted_on/dismissed), and the agent's response when available. Use 'linked_iteration_ids' to trace which iterations were spawned from a suggestion.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List suggestions",+ "title": "List suggestions",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-respond": {+ "description": "Record how you handled a steering suggestion so the human who submitted it sees the outcome (it stays 'queued' in the UI until you do). Set status to 'picked_up' (applied as a search constraint across iterations), 'acted_on' (spawned one or more iterations from it), or 'dismissed' (rejected — explain why in agent_response), and write a one-line agent_response. Recording an iteration with parent_suggestion set already advances a suggestion to 'acted_on'; use this tool to add the narrative or to mark a suggestion picked_up/dismissed without a dedicated iteration.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Respond to a suggestion",+ "title": "Respond to a suggestion",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-train-create": {+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Start training",+ "title": "Start training",+ "required_scopes": ["autoresearch:write", "query:read", "insight:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-get-create": {+ "description": "Fetch one file from a training run's artifact bundle, base64-encoded. Use this to read the prior champion's train.py / features.sql as a starting point before iterating (look up the champion's source_training_run via autoresearch-models-retrieve).",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get an artifact bundle file",+ "title": "Get an artifact bundle file",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-retrieve": {+ "description": "List the files uploaded for a training run's artifact bundle (train.py, predict.py, features.sql, and any eda/ notebooks). Use to confirm a complete bundle is present before finalizing the run.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List artifact bundle files",+ "title": "List artifact bundle files",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-upload-create": {+ "description": "Upload one file of a training run's runnable model bundle. Send the file contents base64-encoded in content_base64; path is the relative path within the bundle (train.py, predict.py, features.sql, or an eda/ notebook). Re-uploading the same path overwrites it. Keep each file under about 700 KB: the base64 body must fit the MCP server's 1 MiB request limit. A bundle holds at most 32 files. This is how you author the model — author train.py and predict.py (standalone sklearn scripts; the framework runs `python train.py <train_features.parquet> <train_labels.parquet> <model.pkl> <output.json> <holdout_features.parquet> <holdout_labels.parquet> --random-state N`, which pickles {\"model\", \"feature_cols\"} and writes {\"holdout_auc\", \"n_train\", \"n_features\"} to output.json, and `python predict.py <score_features.parquet> <model.pkl> <scores.parquet>`, which writes distinct_id,p_y; features parquet is distinct_id plus numeric columns, labels parquet is distinct_id,__label) and features.sql (HogQL with the {anchors}/{lookback_days} contract), then upload each here. Do NOT use set_output or curl — the bundle you upload is what inference runs in a sandbox. Only allowed while the run is still running; the bundle is frozen once the run completes or fails.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Upload an artifact bundle file",+ "title": "Upload an artifact bundle file",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-complete-create": {+ "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Complete a training run",+ "title": "Complete a training run",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-create": {+ "description": "Open a new training run for a pipeline and return its id, for a bring-your-own agent that trains outside PostHog. The agent then records iterations against this run with autoresearch-training-runs-iterations-create and finalizes it with autoresearch-training-runs-complete-create. The run starts in 'running'. Optionally override the iteration_budget for this run. Refused from inside a sandbox: the in-house training agent works in the run that autoresearch-train-create opened for it. A pipeline with an action target also needs the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Open a training run",+ "title": "Open a training run",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-history": {+ "description": "Cross-run learning memory. Returns recent completed training runs — this pipeline first, then same-target sibling pipelines on the team. Each run has a distilled `summary` (read this first: distillation, recommended_next, the kept_ladder of winning approaches, and dead_ends to avoid) plus the full `iterations` trail (every recipe tried, its agent_description rationale, holdout_score, kept/discarded status, model_spec) to drill into when a summary points somewhere worth it. Call this before iterating to reuse the features and transforms that won and avoid repeating approaches already discarded. Optional `limit` (default 5, max 20) caps how many prior runs are returned.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Read prior training-run history",+ "title": "Read prior training-run history",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-iterations-create": {+ "description": "Record one iteration of an open training run. Idempotent on iteration_number — re-sending the same number updates that iteration in place. The recipe is validated server-side: feature_sql in recipe_snapshot must be a read-only SELECT that outputs the anchor key exactly once as a.person_id AS distinct_id, and every events join must be bounded by e.timestamp < fromUnixTimestamp(a.cutoff_ts) and exclude NOT startsWith(e.event, 'autoresearch_'), the model's own prediction events. The validator cannot prove either rule, and without them the features see the outcome window or the model's own past scores, and the holdout AUC is leaked. model_class in model_spec is informational when you upload your own train.py and predict.py bundle; it must be in the sklearn/xgboost allowlist only when the run completes without a bundle. Use status='kept' if the iteration beats the best AUC so far in this run (the first scored iteration is always kept, whatever the current champion scores), 'discarded' otherwise, 'crashed' on failure. Iterations are picked up at completion time to choose the champion. If this iteration was spawned from a pending steering suggestion, pass parent_suggestion = the suggestion's ID — that links the iteration to the suggestion for attribution and marks the suggestion 'acted_on'.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Record a training iteration",+ "title": "Record a training iteration",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-list": {+ "description": "List training runs for a pipeline, ordered most recent first. Check status (completed/failed), iteration_count, and best_holdout_score to understand training history.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List training runs",+ "title": "List training runs",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-validate-create": {+ "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the action:read scope. Always validate before creating.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Validate a pipeline definition",+ "title": "Validate a pipeline definition",+ "required_scopes": ["autoresearch:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },"batch-export-create": {"description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, sessions, or hogql). Omitting it defaults to events. For the hogql model, provide hogql_query.","category": "Data pipelines",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 14cf274ef272..b4f6d2c381d3 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1104,6 +1104,306 @@"readOnlyHint": true}},+ "autoresearch-create": {+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an asynchronous agent training run.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Create a pipeline",+ "title": "Create a pipeline",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-list": {+ "description": "List autoresearch prediction pipelines for the current project. Archived pipelines are excluded. Each pipeline entry includes its status (draft, bootstrapping, running, converged, paused), target event, horizon, and timestamps. Use autoresearch-retrieve to get full details including population definitions.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List pipelines",+ "title": "List pipelines",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-materialize-features": {+ "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Materialize training features to the sandbox",+ "title": "Materialize training features to the sandbox",+ "required_scopes": ["autoresearch:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-models-list": {+ "description": "List champion, challenger, and archived model versions for a pipeline. Each model includes its holdout_score, role, recipe_hash, is_preliminary flag, and agent_description. The active scoring model has role='champion'. Use the recipe_hash to detect when the champion has changed across training runs.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List models for a pipeline",+ "title": "List models for a pipeline",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-models-retrieve": {+ "description": "Get full details for a specific model version, including the portable model recipe (feature SQL, transforms, model class, params) and feature importance explanation.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get model",+ "title": "Get model",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-resolve-template-create": {+ "description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Resolve a template",+ "title": "Resolve a template",+ "required_scopes": ["autoresearch:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-retrieve": {+ "description": "Get full details for a specific autoresearch pipeline by ID, including population definitions, training configuration, and current status.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get pipeline",+ "title": "Get pipeline",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-create": {+ "description": "Inject a free-text hypothesis or direction into a running pipeline for the sandbox agent to consider. The agent reads queued suggestions at the start of each training batch and decides whether to translate the suggestion into a concrete iteration ('acted_on'), apply it as a search constraint ('picked_up'), or reject it with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before autonomous iterations; 'consider' (default) is advisory. Check 'agent_response' after the next training run to see how the suggestion was interpreted. Examples: 'try a gradient boosting model', 'remove recency features — I suspect leakage', 'the target event has a 7-day spike on Mondays, account for day-of-week'. Suggestions survive pipeline pauses and are included in the next training batch when the pipeline resumes.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Submit a suggestion",+ "title": "Submit a suggestion",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-list": {+ "description": "List steering suggestions for a pipeline, ordered most recent first. Each entry shows the prompt, priority, status (queued/picked_up/acted_on/dismissed), and the agent's response when available. Use 'linked_iteration_ids' to trace which iterations were spawned from a suggestion.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List suggestions",+ "title": "List suggestions",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-suggestions-respond": {+ "description": "Record how you handled a steering suggestion so the human who submitted it sees the outcome (it stays 'queued' in the UI until you do). Set status to 'picked_up' (applied as a search constraint across iterations), 'acted_on' (spawned one or more iterations from it), or 'dismissed' (rejected — explain why in agent_response), and write a one-line agent_response. Recording an iteration with parent_suggestion set already advances a suggestion to 'acted_on'; use this tool to add the narrative or to mark a suggestion picked_up/dismissed without a dedicated iteration.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Respond to a suggestion",+ "title": "Respond to a suggestion",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-train-create": {+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Start training",+ "title": "Start training",+ "required_scopes": ["autoresearch:write", "query:read", "insight:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-get-create": {+ "description": "Fetch one file from a training run's artifact bundle, base64-encoded. Use this to read the prior champion's train.py / features.sql as a starting point before iterating (look up the champion's source_training_run via autoresearch-models-retrieve).",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Get an artifact bundle file",+ "title": "Get an artifact bundle file",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-retrieve": {+ "description": "List the files uploaded for a training run's artifact bundle (train.py, predict.py, features.sql, and any eda/ notebooks). Use to confirm a complete bundle is present before finalizing the run.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List artifact bundle files",+ "title": "List artifact bundle files",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-artifacts-upload-create": {+ "description": "Upload one file of a training run's runnable model bundle. Send the file contents base64-encoded in content_base64; path is the relative path within the bundle (train.py, predict.py, features.sql, or an eda/ notebook). Re-uploading the same path overwrites it. Keep each file under about 700 KB: the base64 body must fit the MCP server's 1 MiB request limit. A bundle holds at most 32 files. This is how you author the model — author train.py and predict.py (standalone sklearn scripts; the framework runs `python train.py <train_features.parquet> <train_labels.parquet> <model.pkl> <output.json> <holdout_features.parquet> <holdout_labels.parquet> --random-state N`, which pickles {\"model\", \"feature_cols\"} and writes {\"holdout_auc\", \"n_train\", \"n_features\"} to output.json, and `python predict.py <score_features.parquet> <model.pkl> <scores.parquet>`, which writes distinct_id,p_y; features parquet is distinct_id plus numeric columns, labels parquet is distinct_id,__label) and features.sql (HogQL with the {anchors}/{lookback_days} contract), then upload each here. Do NOT use set_output or curl — the bundle you upload is what inference runs in a sandbox. Only allowed while the run is still running; the bundle is frozen once the run completes or fails.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Upload an artifact bundle file",+ "title": "Upload an artifact bundle file",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-complete-create": {+ "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Complete a training run",+ "title": "Complete a training run",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-create": {+ "description": "Open a new training run for a pipeline and return its id, for a bring-your-own agent that trains outside PostHog. The agent then records iterations against this run with autoresearch-training-runs-iterations-create and finalizes it with autoresearch-training-runs-complete-create. The run starts in 'running'. Optionally override the iteration_budget for this run. Refused from inside a sandbox: the in-house training agent works in the run that autoresearch-train-create opened for it. A pipeline with an action target also needs the action:read scope.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Open a training run",+ "title": "Open a training run",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-history": {+ "description": "Cross-run learning memory. Returns recent completed training runs — this pipeline first, then same-target sibling pipelines on the team. Each run has a distilled `summary` (read this first: distillation, recommended_next, the kept_ladder of winning approaches, and dead_ends to avoid) plus the full `iterations` trail (every recipe tried, its agent_description rationale, holdout_score, kept/discarded status, model_spec) to drill into when a summary points somewhere worth it. Call this before iterating to reuse the features and transforms that won and avoid repeating approaches already discarded. Optional `limit` (default 5, max 20) caps how many prior runs are returned.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Read prior training-run history",+ "title": "Read prior training-run history",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-iterations-create": {+ "description": "Record one iteration of an open training run. Idempotent on iteration_number — re-sending the same number updates that iteration in place. The recipe is validated server-side: feature_sql in recipe_snapshot must be a read-only SELECT that outputs the anchor key exactly once as a.person_id AS distinct_id, and every events join must be bounded by e.timestamp < fromUnixTimestamp(a.cutoff_ts) and exclude NOT startsWith(e.event, 'autoresearch_'), the model's own prediction events. The validator cannot prove either rule, and without them the features see the outcome window or the model's own past scores, and the holdout AUC is leaked. model_class in model_spec is informational when you upload your own train.py and predict.py bundle; it must be in the sklearn/xgboost allowlist only when the run completes without a bundle. Use status='kept' if the iteration beats the best AUC so far in this run (the first scored iteration is always kept, whatever the current champion scores), 'discarded' otherwise, 'crashed' on failure. Iterations are picked up at completion time to choose the champion. If this iteration was spawned from a pending steering suggestion, pass parent_suggestion = the suggestion's ID — that links the iteration to the suggestion for attribution and marks the suggestion 'acted_on'.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Record a training iteration",+ "title": "Record a training iteration",+ "required_scopes": ["autoresearch:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-training-runs-list": {+ "description": "List training runs for a pipeline, ordered most recent first. Check status (completed/failed), iteration_count, and best_holdout_score to understand training history.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List training runs",+ "title": "List training runs",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },+ "autoresearch-validate-create": {+ "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the action:read scope. Always validate before creating.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "Validate a pipeline definition",+ "title": "Validate a pipeline definition",+ "required_scopes": ["autoresearch:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },"batch-export-create": {"description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, sessions, or hogql). Omitting it defaults to events. For the hogql model, provide hogql_query.","category": "Data pipelines",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 81f60cb4cf90..19f972c060fc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -87714,7 +87714,7 @@ export namespace Schemas {} as const;export interface ResolveTemplateRequest {- /** Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.+ /** Template to resolve. The templates endpoint lists each one with its description. Required.** * `likely_active_soon` - Likely Active Soon* * `at_risk_of_inactivity` - At Risk Of Inactivitydiff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.tsnew file mode 100644index 000000000000..b8d692a498de--- /dev/null+++ b/services/mcp/src/generated/autoresearch/api.ts@@ -0,0 +1,741 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 20 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const AutoresearchListParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const AutoresearchCreateParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchCreateBodyNameMax = 255++export const autoresearchCreateBodyTargetEventMax = 255++export const autoresearchCreateBodyHorizonDaysMax = 365++export const autoresearchCreateBodyTrainingLookbackDaysMin = 7+export const autoresearchCreateBodyTrainingLookbackDaysMax = 730++export const autoresearchCreateBodyCadenceDaysMax = 365++export const autoresearchCreateBodyIterationBudgetMax = 500++export const autoresearchCreateBodySuccessAucMin = 0+export const autoresearchCreateBodySuccessAucMax = 1++export const autoresearchCreateBodyPlateauIterationsMax = 2147483647++export const autoresearchCreateBodyOutputPersonPropertyMax = 255++export const AutoresearchCreateBody = () => zod.object({+ name: zod.string().max(autoresearchCreateBodyNameMax).describe('Display name for the pipeline.'),+ description: zod.string().optional().describe('Optional free-text description.'),+ target_event: zod+ .string()+ .max(autoresearchCreateBodyTargetEventMax)+ .optional()+ .describe(+ "PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead)."+ ),+ target_definition: zod+ .union([+ zod+ .object({+ type: zod.enum(['event']),+ })+ .describe('Predict target_event. The default when target_definition is omitted.'),+ zod+ .object({+ type: zod.enum(['action']),+ action_id: zod.number().min(1).describe('ID of the action to predict.'),+ })+ .describe('Predict a PostHog action in this project.'),+ ])+ .optional()+ .describe(+ 'Omit (or pass {\"type\": \"event\"}) to predict target_event; pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action. No other shapes are accepted.'+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyHorizonDaysMax)+ .optional()+ .describe(+ 'Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.'+ ),+ training_lookback_days: zod+ .number()+ .min(autoresearchCreateBodyTrainingLookbackDaysMin)+ .max(autoresearchCreateBodyTrainingLookbackDaysMax)+ .optional()+ .describe(+ 'How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.'+ ),+ training_population: zod+ .looseObject({})+ .optional()+ .describe('Training population filter. Use {} for all identified users.'),+ inference_population: zod+ .looseObject({})+ .optional()+ .describe('Inference population filter. Defaults to training_population if not set.'),+ cadence_days: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyCadenceDaysMax)+ .optional()+ .describe('Re-score the inference population every N days (1-365). Default: 1.'),+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyIterationBudgetMax)+ .optional()+ .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ success_auc: zod+ .number()+ .min(autoresearchCreateBodySuccessAucMin)+ .max(autoresearchCreateBodySuccessAucMax)+ .nullish()+ .describe('Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.'),+ plateau_iterations: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyPlateauIterationsMax)+ .optional()+ .describe('Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.'),+ output_person_property: zod+ .string()+ .max(autoresearchCreateBodyOutputPersonPropertyMax)+ .optional()+ .describe(+ "Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines."+ ),+})++/**+ * List and retrieve champion/challenger models for a pipeline.+ *+ * Models are the persisted artifacts produced by training runs. Each model+ * holds a portable recipe (feature SQL, transforms, model class, params) that+ * the daily inference workflow compiles to score users.+ */+export const AutoresearchModelsListParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchModelsListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * List and retrieve champion/challenger models for a pipeline.+ *+ * Models are the persisted artifacts produced by training runs. Each model+ * holds a portable recipe (feature SQL, transforms, model class, params) that+ * the daily inference workflow compiles to score users.+ */+export const AutoresearchModelsRetrieveParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch model.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * List steering suggestions for a pipeline, ordered most recent first. Check 'status' to see which have been picked up or acted on by the agent.+ * @summary List suggestions+ */+export const AutoresearchSuggestionsListParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchSuggestionsListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Inject a free-text hypothesis or direction into a running pipeline. The sandbox agent reads queued suggestions at the start of each iteration batch and decides: translate into a concrete iteration ('acted_on'), apply as a search constraint ('picked_up'), or reject with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before autonomous iterations; 'consider' is advisory. Check 'agent_response' after the next training run to see how the suggestion was interpreted.+ * @summary Submit a suggestion+ */+export const AutoresearchSuggestionsCreateParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchSuggestionsCreateBodyPromptMax = 2000++export const autoresearchSuggestionsCreateBodyPriorityDefault = `consider`++export const AutoresearchSuggestionsCreateBody = () => zod.object({+ prompt: zod+ .string()+ .max(autoresearchSuggestionsCreateBodyPromptMax)+ .describe(+ "Free-text hypothesis or direction for the agent to explore, e.g. 'try a tree-based model' or 'remove recency features, I suspect leakage'."+ ),+ priority: zod+ .enum(['try_next', 'consider'])+ .describe('\* `try_next` - try_next\n\* `consider` - consider')+ .default(autoresearchSuggestionsCreateBodyPriorityDefault)+ .describe(+ "'try_next' asks the agent to act on this before other autonomous iterations; 'consider' is advisory context.\n\n\* `try_next` - try_next\n\* `consider` - consider"+ ),+})++/**+ * Record how the agent handled a steering suggestion: set status to 'picked_up' (applied as a search constraint), 'acted_on' (spawned iterations), or 'dismissed' (rejected — explain in agent_response), and write the agent_response note the human will read. Call this from the training loop after deciding what to do with a pending suggestion. Recording an iteration with parent_suggestion set already advances a suggestion to 'acted_on'; use this to add the narrative or to mark a suggestion picked_up/dismissed without spawning an iteration. A suggestion only moves forward (queued, picked_up, then acted_on or dismissed); the same status again updates the note.+ * @summary Respond to a suggestion+ */+export const AutoresearchSuggestionsRespondCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch suggestion.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchSuggestionsRespondCreateBodyAgentResponseMax = 2000++export const AutoresearchSuggestionsRespondCreateBody = () => zod+ .object({+ status: zod+ .enum(['picked_up', 'acted_on', 'dismissed'])+ .describe('\* `picked_up` - picked_up\n\* `acted_on` - acted_on\n\* `dismissed` - dismissed')+ .describe(+ "How the agent handled the suggestion: 'picked_up' (applied as a search constraint), 'acted_on' (spawned one or more iterations), or 'dismissed' (rejected — explain why in agent_response).\n\n\* `picked_up` - picked_up\n\* `acted_on` - acted_on\n\* `dismissed` - dismissed"+ ),+ agent_response: zod+ .string()+ .max(autoresearchSuggestionsRespondCreateBodyAgentResponseMax)+ .optional()+ .describe(+ 'Plain-English note on how the suggestion was interpreted and acted upon. A dismissal needs a note, sent now or recorded earlier. Omit it to keep the note already recorded; send an empty string to clear it.'+ ),+ })+ .describe('Input for the agent to record how it interpreted a steering suggestion.')++/**+ * List and retrieve training runs for a pipeline.+ *+ * A training run records the agent's search for a model: each iteration's recipe and holdout+ * score, and the summary of the run once it completes.+ */+export const AutoresearchTrainingRunsListParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchTrainingRunsListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Open a new training run for a pipeline and return its id. An agent — the in-house sandbox, an external bring-your-own agent, or a scheduled job — then records iterations against this run and finalizes it with the complete endpoint. The run starts in 'running'.+ * @summary Open a training run+ */+export const AutoresearchTrainingRunsCreateParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsCreateBodyIterationBudgetMax = 500++export const AutoresearchTrainingRunsCreateBody = () => zod+ .object({+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchTrainingRunsCreateBodyIterationBudgetMax)+ .optional()+ .describe("Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted."),+ })+ .describe('Input for opening an agent-driven training run.')++/**+ * List the files an agent has uploaded for this training run's artifact bundle (train.py, predict.py, features.sql, and any eda/ notebooks).+ * @summary List artifact bundle files+ */+export const AutoresearchTrainingRunsArtifactsRetrieveParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Fetch one file from this training run's artifact bundle, base64-encoded.+ * @summary Get an artifact bundle file+ */+export const AutoresearchTrainingRunsArtifactsGetCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsArtifactsGetCreateBodyPathMax = 500++export const AutoresearchTrainingRunsArtifactsGetCreateBody = () => zod+ .object({+ path: zod+ .string()+ .max(autoresearchTrainingRunsArtifactsGetCreateBodyPathMax)+ .describe("Relative path of the file within the bundle, e.g. 'train.py'."),+ })+ .describe('Input for fetching or deleting one bundle file by path.')++/**+ * Upload one file of this training run's artifact bundle. Send the file contents base64-encoded in content_base64. Re-uploading the same path overwrites it. Use this — not curl/set_output — to author train.py, predict.py, and features.sql. The bundle is frozen once the run completes or fails.+ * @summary Upload an artifact bundle file+ */+export const AutoresearchTrainingRunsArtifactsUploadCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsArtifactsUploadCreateBodyPathMax = 500++export const AutoresearchTrainingRunsArtifactsUploadCreateBody = () => zod+ .object({+ path: zod+ .string()+ .max(autoresearchTrainingRunsArtifactsUploadCreateBodyPathMax)+ .describe(+ "Relative path within the bundle, e.g. 'train.py', 'predict.py', 'features.sql', or 'eda\/iter-3-gbm.ipynb'. Segments are limited to [A-Za-z0-9_.-]; absolute paths and '..' traversal are rejected."+ ),+ content_base64: zod+ .string()+ .describe(+ 'File contents, base64-encoded. Decoded server-side and written to object storage. Max 10 MB decoded.'+ ),+ })+ .describe("Input for uploading one file of a training run's artifact bundle.")++/**+ * Finalize a training run. The backend selects the kept iteration with the highest holdout score, decides champion vs challenger via the promotion ladder, and persists the model. best_iteration_id is advisory: it breaks a tie at the top score and is otherwise logged and ignored. Agents cannot set the champion directly, because promotion is server-side.+ * @summary Complete a training run+ */+export const AutoresearchTrainingRunsCompleteCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault = ``+export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000++export const autoresearchTrainingRunsCompleteCreateBodyDistillationDefault = ``+export const autoresearchTrainingRunsCompleteCreateBodyDistillationMax = 2000++export const AutoresearchTrainingRunsCompleteCreateBody = () => zod+ .object({+ best_iteration_id: zod+ .string()+ .nullish()+ .describe(+ 'Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.'+ ),+ model_explanation: zod+ .looseObject({})+ .optional()+ .describe('Global feature importance \/ directionality bundle for the champion model card.'),+ recommended_next: zod+ .string()+ .max(autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax)+ .default(autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault)+ .describe(+ 'What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.'+ ),+ distillation: zod+ .string()+ .max(autoresearchTrainingRunsCompleteCreateBodyDistillationMax)+ .default(autoresearchTrainingRunsCompleteCreateBodyDistillationDefault)+ .describe(+ 'A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.'+ ),+ })+ .describe('Input for finalizing a training run. The backend selects\/promotes the champion.')++/**+ * Record one iteration of an open training run. Idempotent on iteration_number: re-sending the same number updates that iteration. A new iteration_number is refused once the run's iteration_budget is used. The recipe is validated server-side: feature_sql must be a read-only SELECT from {anchors} keyed on person_id, and model_class must be set. The class allowlist applies only at completion, to a run that uploaded no bundle.+ * @summary Record a training iteration+ */+export const AutoresearchTrainingRunsIterationsCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsIterationsCreateBodyIterationNumberMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyIterationNumberMax = 2147483647++export const autoresearchTrainingRunsIterationsCreateBodyTrainScoreMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyTrainScoreMax = 1++export const autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMax = 1++export const autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionDefault = ``+export const autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionMax = 2000++export const autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMax = 1++export const AutoresearchTrainingRunsIterationsCreateBody = () => zod+ .object({+ iteration_number: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyIterationNumberMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyIterationNumberMax)+ .describe(+ 'Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).'+ ),+ recipe_snapshot: zod+ .object({+ feature_sql: zod+ .string()+ .describe('A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id.'),+ feature_transforms: zod+ .array(zod.looseObject({}))+ .nullish()+ .describe(+ 'Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.'+ ),+ })+ .describe(+ 'Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms.'+ ),+ model_spec: zod+ .object({+ model_class: zod.string().describe('Dotted path of the estimator class.'),+ model_params: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe("Keyword arguments for the estimator's constructor; null or absent means the defaults."),+ })+ .describe(+ 'model_class and model_params tried this iteration. Any class is accepted here; the sklearn\/xgboost allowlist applies at completion, to a run that uploaded no bundle.'+ ),+ status: zod+ .enum(['kept', 'discarded', 'crashed'])+ .describe('\* `kept` - kept\n\* `discarded` - discarded\n\* `crashed` - crashed')+ .describe(+ "'kept' if this iteration improved on the best score, 'discarded' otherwise, 'crashed' on failure.\n\n\* `kept` - kept\n\* `discarded` - discarded\n\* `crashed` - crashed"+ ),+ train_score: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyTrainScoreMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyTrainScoreMax)+ .nullish()+ .describe('Training-set AUC for this iteration (0-1).'),+ holdout_score: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMax)+ .nullish()+ .describe('Held-out AUC for this iteration (0-1). Used to pick the champion at completion.'),+ agent_description: zod+ .string()+ .max(autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionMax)+ .default(autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionDefault)+ .describe("Agent's plain-English rationale for this iteration. Max 2000 characters."),+ agent_confidence: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMax)+ .nullish()+ .describe("Agent's self-assessed confidence (0-1) that this iteration helps."),+ parent_suggestion: zod+ .string()+ .nullish()+ .describe(+ "UUID of the steering suggestion this iteration was spawned from, if any. Set it whenever the iteration acts on a pending suggestion — it links the iteration back to the suggestion for attribution and advances the suggestion to 'acted_on'."+ ),+ })+ .describe('Input for recording one training iteration. Validated against the recipe allowlist.')++/**+ * Run features_sql server-side against the labeled training population and write the resulting train/holdout feature and label parquet files directly into this run's sandbox. Returns the local sandbox paths, row counts, and feature columns. The rows never pass through the agent's context and there is no 500-row cap. Read the returned paths with pd.read_parquet and iterate in Python.+ * @summary Materialize training features to the sandbox+ */+export const AutoresearchTrainingRunsMaterializeFeaturesCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch training run.'),+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchTrainingRunsMaterializeFeaturesCreateBody = () => zod+ .object({+ features_sql: zod+ .string()+ .describe(+ 'Your HogQL feature query, using the {anchors}\/{lookback_days} contract. Must be a read-only SELECT keyed on person_id (aliased to distinct_id), one row per user. The backend runs it server-side against the labeled training population — no 500-row cap — and writes the resulting train\/holdout feature and label parquet files into your sandbox.'+ ),+ })+ .describe("Input for materializing the labeled training feature matrix into the run's sandbox.")++/**+ * Return recent completed training runs and their iteration trails so a new run can learn from what was already tried. Scoped to this pipeline first, then same-target sibling pipelines on the team. Read this before iterating to reuse winning features and avoid repeating discarded approaches.+ * @summary Read prior training-run history+ */+export const AutoresearchTrainingRunsHistoryRetrieveParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainingRunsHistoryRetrieveQueryLimitDefault = 5+export const autoresearchTrainingRunsHistoryRetrieveQueryLimitMax = 20++export const AutoresearchTrainingRunsHistoryRetrieveQueryParams = () => zod.object({+ limit: zod+ .number()+ .min(1)+ .max(autoresearchTrainingRunsHistoryRetrieveQueryLimitMax)+ .default(autoresearchTrainingRunsHistoryRetrieveQueryLimitDefault)+ .describe('Maximum number of prior runs to return (default 5, at most 20).'),+})++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const AutoresearchRetrieveParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch pipeline.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Start an asynchronous training run for this pipeline. Creates a Task/TaskRun sandbox where the autoresearch agent iterates on features and models, and returns the run immediately with status 'running'. Poll the training run until it reaches a terminal status (completed or failed). A pipeline's first run has no champion until it completes and promotion runs; on a retrain the existing champion stays live and keeps scoring until a new one is promoted.+ * @summary Start a training run+ */+export const AutoresearchTrainCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this autoresearch pipeline.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchTrainCreateBodyIterationBudgetMax = 500++export const AutoresearchTrainCreateBody = () => zod.object({+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchTrainCreateBodyIterationBudgetMax)+ .optional()+ .describe('Override the pipeline iteration budget for this training run.'),+})++/**+ * Resolve a template key and optional overrides into a concrete pipeline config. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target event is auto-resolved from your event schema — check resolved_activity_event and activity_event_alternatives, then override if needed. For 'feature_adoption' and 'repeat_key_behavior', supply target_event. After resolving, call autoresearch-validate-create to check volume and warnings, then autoresearch-create to create the pipeline.+ * @summary Resolve a template+ */+export const AutoresearchResolveTemplateCreateParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchResolveTemplateCreateBodyHorizonDaysMax = 365++export const AutoresearchResolveTemplateCreateBody = () => zod.object({+ template_key: zod+ .enum([+ 'likely_active_soon',+ 'at_risk_of_inactivity',+ 'return_after_first_use',+ 'feature_adoption',+ 'repeat_key_behavior',+ ])+ .describe(+ '\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'+ )+ .describe(+ 'Template to resolve. The templates endpoint lists each one with its description. Required.\n\n\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'+ ),+ target_event: zod+ .string()+ .optional()+ .describe(+ "Event name to use as the prediction target. Required for 'feature_adoption' and 'repeat_key_behavior'. Optional override for activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'); omit to use the auto-resolved event. To predict an action, create the pipeline with target_definition after resolving."+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchResolveTemplateCreateBodyHorizonDaysMax)+ .optional()+ .describe("Override the template's default prediction horizon in days."),+})++/**+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.+ * @summary Validate a pipeline definition+ */+export const AutoresearchValidateCreateParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const autoresearchValidateCreateBodyTargetEventDefault = ``+export const autoresearchValidateCreateBodyHorizonDaysDefault = 7+export const autoresearchValidateCreateBodyHorizonDaysMax = 365++export const autoresearchValidateCreateBodyTrainingLookbackDaysDefault = 180+export const autoresearchValidateCreateBodyTrainingLookbackDaysMin = 7+export const autoresearchValidateCreateBodyTrainingLookbackDaysMax = 730++export const AutoresearchValidateCreateBody = () => zod.object({+ target_event: zod+ .string()+ .default(autoresearchValidateCreateBodyTargetEventDefault)+ .describe(+ "Event name to predict, e.g. '$pageview'. Must exist in the team's event schema. Omit when predicting an action target (pass target_definition instead)."+ ),+ target_definition: zod+ .union([+ zod+ .object({+ type: zod.enum(['event']),+ })+ .describe('Predict target_event. The default when target_definition is omitted.'),+ zod+ .object({+ type: zod.enum(['action']),+ action_id: zod.number().min(1).describe('ID of the action to predict.'),+ })+ .describe('Predict a PostHog action in this project.'),+ ])+ .optional()+ .describe(+ 'Optional target definition. Pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action (multi-step \/ property \/ autocapture matcher) instead of a single event.'+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchValidateCreateBodyHorizonDaysMax)+ .default(autoresearchValidateCreateBodyHorizonDaysDefault)+ .describe('Predict whether the target event occurs within this many days.'),+ training_lookback_days: zod+ .number()+ .min(autoresearchValidateCreateBodyTrainingLookbackDaysMin)+ .max(autoresearchValidateCreateBodyTrainingLookbackDaysMax)+ .default(autoresearchValidateCreateBodyTrainingLookbackDaysDefault)+ .describe('How far back to look for training examples. Default: 180.'),+ training_population: zod+ .looseObject({})+ .optional()+ .describe('Population filter for training examples. Use {} for all identified users.'),+ inference_population: zod+ .looseObject({})+ .optional()+ .describe(+ 'Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it.'+ ),+})diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.tsnew file mode 100644index 000000000000..2c76fd83e52b--- /dev/null+++ b/services/mcp/src/tools/generated/autoresearch.ts@@ -0,0 +1,780 @@+// AUTO-GENERATED from products/autoresearch/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import * as orvalSchemas from '@/generated/autoresearch/api'+import { withPostHogUrl, pickResponseFields, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const AutoresearchCreateSchema = () => {+ const AutoresearchCreateBody = orvalSchemas.AutoresearchCreateBody()+ return AutoresearchCreateBody+}++const autoresearchCreate = (): ToolBase<ReturnType<typeof AutoresearchCreateSchema>, Schemas.AutoresearchPipeline> => ({+ name: 'autoresearch-create',+ schema: AutoresearchCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.target_event !== undefined) {+ body['target_event'] = params.target_event+ }+ if (params.target_definition !== undefined) {+ body['target_definition'] = params.target_definition+ }+ if (params.horizon_days !== undefined) {+ body['horizon_days'] = params.horizon_days+ }+ if (params.training_lookback_days !== undefined) {+ body['training_lookback_days'] = params.training_lookback_days+ }+ if (params.training_population !== undefined) {+ body['training_population'] = params.training_population+ }+ if (params.inference_population !== undefined) {+ body['inference_population'] = params.inference_population+ }+ if (params.cadence_days !== undefined) {+ body['cadence_days'] = params.cadence_days+ }+ if (params.iteration_budget !== undefined) {+ body['iteration_budget'] = params.iteration_budget+ }+ if (params.success_auc !== undefined) {+ body['success_auc'] = params.success_auc+ }+ if (params.plateau_iterations !== undefined) {+ body['plateau_iterations'] = params.plateau_iterations+ }+ if (params.output_person_property !== undefined) {+ body['output_person_property'] = params.output_person_property+ }+ const result = await context.api.request<Schemas.AutoresearchPipeline>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/`,+ body,+ })+ return result+ },+})++const AutoresearchListSchema = () => {+ const AutoresearchListQueryParams = orvalSchemas.AutoresearchListQueryParams()+ return AutoresearchListQueryParams+}++const autoresearchList = (): ToolBase<+ ReturnType<typeof AutoresearchListSchema>,+ WithPostHogUrl<Schemas.PaginatedAutoresearchPipelineList>+> => ({+ name: 'autoresearch-list',+ schema: AutoresearchListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedAutoresearchPipelineList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'name',+ 'description',+ 'target_event',+ 'horizon_days',+ 'status',+ 'iteration_budget',+ 'iteration_budget_remaining',+ 'last_scored_at',+ 'created_at',+ 'updated_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/')+ },+})++const AutoresearchMaterializeFeaturesSchema = () => {+ const AutoresearchTrainingRunsMaterializeFeaturesCreateBody =+ orvalSchemas.AutoresearchTrainingRunsMaterializeFeaturesCreateBody()+ const AutoresearchTrainingRunsMaterializeFeaturesCreateParams =+ orvalSchemas.AutoresearchTrainingRunsMaterializeFeaturesCreateParams()+ return AutoresearchTrainingRunsMaterializeFeaturesCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsMaterializeFeaturesCreateBody.shape+ )+}++const autoresearchMaterializeFeatures = (): ToolBase<+ ReturnType<typeof AutoresearchMaterializeFeaturesSchema>,+ Schemas.MaterializeFeaturesResponse+> => ({+ name: 'autoresearch-materialize-features',+ schema: AutoresearchMaterializeFeaturesSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchMaterializeFeaturesSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.features_sql !== undefined) {+ body['features_sql'] = params.features_sql+ }+ const result = await context.api.request<Schemas.MaterializeFeaturesResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/materialize-features/`,+ body,+ })+ return result+ },+})++const AutoresearchModelsListSchema = () => {+ const AutoresearchModelsListParams = orvalSchemas.AutoresearchModelsListParams()+ const AutoresearchModelsListQueryParams = orvalSchemas.AutoresearchModelsListQueryParams()+ return AutoresearchModelsListParams.omit({ project_id: true }).extend(AutoresearchModelsListQueryParams.shape)+}++const autoresearchModelsList = (): ToolBase<+ ReturnType<typeof AutoresearchModelsListSchema>,+ WithPostHogUrl<Schemas.PaginatedAutoresearchModelList>+> => ({+ name: 'autoresearch-models-list',+ schema: AutoresearchModelsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchModelsListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedAutoresearchModelList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/models/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'pipeline',+ 'role',+ 'recipe_hash',+ 'holdout_score',+ 'realized_score',+ 'is_preliminary',+ 'agent_description',+ 'trained_on_start',+ 'trained_on_end',+ 'promoted_at',+ 'created_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/')+ },+})++const AutoresearchModelsRetrieveSchema = () => {+ const AutoresearchModelsRetrieveParams = orvalSchemas.AutoresearchModelsRetrieveParams()+ return AutoresearchModelsRetrieveParams.omit({ project_id: true })+}++const autoresearchModelsRetrieve = (): ToolBase<+ ReturnType<typeof AutoresearchModelsRetrieveSchema>,+ Schemas.AutoresearchModel+> => ({+ name: 'autoresearch-models-retrieve',+ schema: AutoresearchModelsRetrieveSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchModelsRetrieveSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.AutoresearchModel>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/models/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const AutoresearchResolveTemplateCreateSchema = () => {+ const AutoresearchResolveTemplateCreateBody = orvalSchemas.AutoresearchResolveTemplateCreateBody()+ return AutoresearchResolveTemplateCreateBody+}++const autoresearchResolveTemplateCreate = (): ToolBase<+ ReturnType<typeof AutoresearchResolveTemplateCreateSchema>,+ Schemas.ResolvedTemplate+> => ({+ name: 'autoresearch-resolve-template-create',+ schema: AutoresearchResolveTemplateCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchResolveTemplateCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.template_key !== undefined) {+ body['template_key'] = params.template_key+ }+ if (params.target_event !== undefined) {+ body['target_event'] = params.target_event+ }+ if (params.horizon_days !== undefined) {+ body['horizon_days'] = params.horizon_days+ }+ const result = await context.api.request<Schemas.ResolvedTemplate>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/resolve-template/`,+ body,+ })+ return result+ },+})++const AutoresearchRetrieveSchema = () => {+ const AutoresearchRetrieveParams = orvalSchemas.AutoresearchRetrieveParams()+ return AutoresearchRetrieveParams.omit({ project_id: true })+}++const autoresearchRetrieve = (): ToolBase<+ ReturnType<typeof AutoresearchRetrieveSchema>,+ Schemas.AutoresearchPipeline+> => ({+ name: 'autoresearch-retrieve',+ schema: AutoresearchRetrieveSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchRetrieveSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.AutoresearchPipeline>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.id))}/`,+ })+ const filtered = omitResponseFields(result, ['created_by']) as typeof result+ return filtered+ },+})++const AutoresearchSuggestionsCreateSchema = () => {+ const AutoresearchSuggestionsCreateBody = orvalSchemas.AutoresearchSuggestionsCreateBody()+ const AutoresearchSuggestionsCreateParams = orvalSchemas.AutoresearchSuggestionsCreateParams()+ return AutoresearchSuggestionsCreateParams.omit({ project_id: true }).extend(+ AutoresearchSuggestionsCreateBody.shape+ )+}++const autoresearchSuggestionsCreate = (): ToolBase<+ ReturnType<typeof AutoresearchSuggestionsCreateSchema>,+ Schemas.AutoresearchSuggestion+> => ({+ name: 'autoresearch-suggestions-create',+ schema: AutoresearchSuggestionsCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchSuggestionsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.prompt !== undefined) {+ body['prompt'] = params.prompt+ }+ if (params.priority !== undefined) {+ body['priority'] = params.priority+ }+ const result = await context.api.request<Schemas.AutoresearchSuggestion>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/suggestions/`,+ body,+ })+ return result+ },+})++const AutoresearchSuggestionsListSchema = () => {+ const AutoresearchSuggestionsListParams = orvalSchemas.AutoresearchSuggestionsListParams()+ const AutoresearchSuggestionsListQueryParams = orvalSchemas.AutoresearchSuggestionsListQueryParams()+ return AutoresearchSuggestionsListParams.omit({ project_id: true }).extend(+ AutoresearchSuggestionsListQueryParams.shape+ )+}++const autoresearchSuggestionsList = (): ToolBase<+ ReturnType<typeof AutoresearchSuggestionsListSchema>,+ WithPostHogUrl<Schemas.PaginatedAutoresearchSuggestionList>+> => ({+ name: 'autoresearch-suggestions-list',+ schema: AutoresearchSuggestionsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchSuggestionsListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedAutoresearchSuggestionList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/suggestions/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'pipeline',+ 'prompt',+ 'priority',+ 'status',+ 'source',+ 'agent_response',+ 'linked_iteration_ids',+ 'created_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/')+ },+})++const AutoresearchSuggestionsRespondSchema = () => {+ const AutoresearchSuggestionsRespondCreateBody = orvalSchemas.AutoresearchSuggestionsRespondCreateBody()+ const AutoresearchSuggestionsRespondCreateParams = orvalSchemas.AutoresearchSuggestionsRespondCreateParams()+ return AutoresearchSuggestionsRespondCreateParams.omit({ project_id: true }).extend(+ AutoresearchSuggestionsRespondCreateBody.shape+ )+}++const autoresearchSuggestionsRespond = (): ToolBase<+ ReturnType<typeof AutoresearchSuggestionsRespondSchema>,+ Schemas.AutoresearchSuggestion+> => ({+ name: 'autoresearch-suggestions-respond',+ schema: AutoresearchSuggestionsRespondSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchSuggestionsRespondSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.status !== undefined) {+ body['status'] = params.status+ }+ if (params.agent_response !== undefined) {+ body['agent_response'] = params.agent_response+ }+ const result = await context.api.request<Schemas.AutoresearchSuggestion>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/suggestions/${encodeURIComponent(String(params.id))}/respond/`,+ body,+ })+ const filtered = pickResponseFields(result, [+ 'id',+ 'pipeline',+ 'status',+ 'agent_response',+ 'linked_iteration_ids',+ ]) as typeof result+ return filtered+ },+})++const AutoresearchTrainCreateSchema = () => {+ const AutoresearchTrainCreateBody = orvalSchemas.AutoresearchTrainCreateBody()+ const AutoresearchTrainCreateParams = orvalSchemas.AutoresearchTrainCreateParams()+ return AutoresearchTrainCreateParams.omit({ project_id: true }).extend(AutoresearchTrainCreateBody.shape)+}++const autoresearchTrainCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainCreateSchema>,+ Schemas.AutoresearchTrainingRun+> => ({+ name: 'autoresearch-train-create',+ schema: AutoresearchTrainCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchTrainCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.iteration_budget !== undefined) {+ body['iteration_budget'] = params.iteration_budget+ }+ const result = await context.api.request<Schemas.AutoresearchTrainingRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.id))}/train/`,+ body,+ })+ return result+ },+})++const AutoresearchTrainingRunsArtifactsGetCreateSchema = () => {+ const AutoresearchTrainingRunsArtifactsGetCreateBody = orvalSchemas.AutoresearchTrainingRunsArtifactsGetCreateBody()+ const AutoresearchTrainingRunsArtifactsGetCreateParams =+ orvalSchemas.AutoresearchTrainingRunsArtifactsGetCreateParams()+ return AutoresearchTrainingRunsArtifactsGetCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsArtifactsGetCreateBody.shape+ )+}++const autoresearchTrainingRunsArtifactsGetCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsArtifactsGetCreateSchema>,+ Schemas.ArtifactContent+> => ({+ name: 'autoresearch-training-runs-artifacts-get-create',+ schema: AutoresearchTrainingRunsArtifactsGetCreateSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof AutoresearchTrainingRunsArtifactsGetCreateSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.path !== undefined) {+ body['path'] = params.path+ }+ const result = await context.api.request<Schemas.ArtifactContent>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/artifacts/get/`,+ body,+ })+ return result+ },+})++const AutoresearchTrainingRunsArtifactsRetrieveSchema = () => {+ const AutoresearchTrainingRunsArtifactsRetrieveParams =+ orvalSchemas.AutoresearchTrainingRunsArtifactsRetrieveParams()+ return AutoresearchTrainingRunsArtifactsRetrieveParams.omit({ project_id: true })+}++const autoresearchTrainingRunsArtifactsRetrieve = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsArtifactsRetrieveSchema>,+ Schemas.ArtifactList+> => ({+ name: 'autoresearch-training-runs-artifacts-retrieve',+ schema: AutoresearchTrainingRunsArtifactsRetrieveSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof AutoresearchTrainingRunsArtifactsRetrieveSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ArtifactList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/artifacts/`,+ })+ return result+ },+})++const AutoresearchTrainingRunsArtifactsUploadCreateSchema = () => {+ const AutoresearchTrainingRunsArtifactsUploadCreateBody =+ orvalSchemas.AutoresearchTrainingRunsArtifactsUploadCreateBody()+ const AutoresearchTrainingRunsArtifactsUploadCreateParams =+ orvalSchemas.AutoresearchTrainingRunsArtifactsUploadCreateParams()+ return AutoresearchTrainingRunsArtifactsUploadCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsArtifactsUploadCreateBody.shape+ )+}++const autoresearchTrainingRunsArtifactsUploadCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsArtifactsUploadCreateSchema>,+ Schemas.StoredArtifact+> => ({+ name: 'autoresearch-training-runs-artifacts-upload-create',+ schema: AutoresearchTrainingRunsArtifactsUploadCreateSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof AutoresearchTrainingRunsArtifactsUploadCreateSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.path !== undefined) {+ body['path'] = params.path+ }+ if (params.content_base64 !== undefined) {+ body['content_base64'] = params.content_base64+ }+ const result = await context.api.request<Schemas.StoredArtifact>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/artifacts/upload/`,+ body,+ })+ return result+ },+})++const AutoresearchTrainingRunsCompleteCreateSchema = () => {+ const AutoresearchTrainingRunsCompleteCreateBody = orvalSchemas.AutoresearchTrainingRunsCompleteCreateBody()+ const AutoresearchTrainingRunsCompleteCreateParams = orvalSchemas.AutoresearchTrainingRunsCompleteCreateParams()+ return AutoresearchTrainingRunsCompleteCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsCompleteCreateBody.shape+ )+}++const autoresearchTrainingRunsCompleteCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsCompleteCreateSchema>,+ Schemas.AutoresearchTrainingRun+> => ({+ name: 'autoresearch-training-runs-complete-create',+ schema: AutoresearchTrainingRunsCompleteCreateSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof AutoresearchTrainingRunsCompleteCreateSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.best_iteration_id !== undefined) {+ body['best_iteration_id'] = params.best_iteration_id+ }+ if (params.model_explanation !== undefined) {+ body['model_explanation'] = params.model_explanation+ }+ if (params.recommended_next !== undefined) {+ body['recommended_next'] = params.recommended_next+ }+ if (params.distillation !== undefined) {+ body['distillation'] = params.distillation+ }+ const result = await context.api.request<Schemas.AutoresearchTrainingRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/complete/`,+ body,+ })+ const filtered = pickResponseFields(result, [+ 'id',+ 'pipeline',+ 'status',+ 'iteration_count',+ 'best_holdout_score',+ 'summary',+ 'error',+ 'completed_at',+ ]) as typeof result+ return filtered+ },+})++const AutoresearchTrainingRunsCreateSchema = () => {+ const AutoresearchTrainingRunsCreateBody = orvalSchemas.AutoresearchTrainingRunsCreateBody()+ const AutoresearchTrainingRunsCreateParams = orvalSchemas.AutoresearchTrainingRunsCreateParams()+ return AutoresearchTrainingRunsCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsCreateBody.shape+ )+}++const autoresearchTrainingRunsCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsCreateSchema>,+ Schemas.AutoresearchTrainingRun+> => ({+ name: 'autoresearch-training-runs-create',+ schema: AutoresearchTrainingRunsCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchTrainingRunsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.iteration_budget !== undefined) {+ body['iteration_budget'] = params.iteration_budget+ }+ const result = await context.api.request<Schemas.AutoresearchTrainingRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/`,+ body,+ })+ return result+ },+})++const AutoresearchTrainingRunsHistorySchema = () => {+ const AutoresearchTrainingRunsHistoryRetrieveParams = orvalSchemas.AutoresearchTrainingRunsHistoryRetrieveParams()+ const AutoresearchTrainingRunsHistoryRetrieveQueryParams =+ orvalSchemas.AutoresearchTrainingRunsHistoryRetrieveQueryParams()+ return AutoresearchTrainingRunsHistoryRetrieveParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsHistoryRetrieveQueryParams.shape+ )+}++const autoresearchTrainingRunsHistory = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsHistorySchema>,+ Schemas.TrainingRunHistory+> => ({+ name: 'autoresearch-training-runs-history',+ schema: AutoresearchTrainingRunsHistorySchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchTrainingRunsHistorySchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.TrainingRunHistory>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/history/`,+ query: {+ limit: params.limit,+ },+ })+ return result+ },+})++const AutoresearchTrainingRunsIterationsCreateSchema = () => {+ const AutoresearchTrainingRunsIterationsCreateBody = orvalSchemas.AutoresearchTrainingRunsIterationsCreateBody()+ const AutoresearchTrainingRunsIterationsCreateParams = orvalSchemas.AutoresearchTrainingRunsIterationsCreateParams()+ return AutoresearchTrainingRunsIterationsCreateParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsIterationsCreateBody.shape+ )+}++const autoresearchTrainingRunsIterationsCreate = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsIterationsCreateSchema>,+ Schemas.AutoresearchIteration+> => ({+ name: 'autoresearch-training-runs-iterations-create',+ schema: AutoresearchTrainingRunsIterationsCreateSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof AutoresearchTrainingRunsIterationsCreateSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.iteration_number !== undefined) {+ body['iteration_number'] = params.iteration_number+ }+ if (params.recipe_snapshot !== undefined) {+ body['recipe_snapshot'] = params.recipe_snapshot+ }+ if (params.model_spec !== undefined) {+ body['model_spec'] = params.model_spec+ }+ if (params.status !== undefined) {+ body['status'] = params.status+ }+ if (params.train_score !== undefined) {+ body['train_score'] = params.train_score+ }+ if (params.holdout_score !== undefined) {+ body['holdout_score'] = params.holdout_score+ }+ if (params.agent_description !== undefined) {+ body['agent_description'] = params.agent_description+ }+ if (params.agent_confidence !== undefined) {+ body['agent_confidence'] = params.agent_confidence+ }+ if (params.parent_suggestion !== undefined) {+ body['parent_suggestion'] = params.parent_suggestion+ }+ const result = await context.api.request<Schemas.AutoresearchIteration>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/iterations/`,+ body,+ })+ const filtered = pickResponseFields(result, [+ 'id',+ 'training_run',+ 'iteration_number',+ 'recipe_hash',+ 'train_score',+ 'holdout_score',+ 'status',+ 'parent_suggestion',+ ]) as typeof result+ return filtered+ },+})++const AutoresearchTrainingRunsListSchema = () => {+ const AutoresearchTrainingRunsListParams = orvalSchemas.AutoresearchTrainingRunsListParams()+ const AutoresearchTrainingRunsListQueryParams = orvalSchemas.AutoresearchTrainingRunsListQueryParams()+ return AutoresearchTrainingRunsListParams.omit({ project_id: true }).extend(+ AutoresearchTrainingRunsListQueryParams.shape+ )+}++const autoresearchTrainingRunsList = (): ToolBase<+ ReturnType<typeof AutoresearchTrainingRunsListSchema>,+ WithPostHogUrl<Schemas.PaginatedAutoresearchTrainingRunList>+> => ({+ name: 'autoresearch-training-runs-list',+ schema: AutoresearchTrainingRunsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchTrainingRunsListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedAutoresearchTrainingRunList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'pipeline',+ 'status',+ 'iteration_budget',+ 'iteration_count',+ 'best_holdout_score',+ 'error',+ 'started_at',+ 'completed_at',+ 'created_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/')+ },+})++const AutoresearchValidateCreateSchema = () => {+ const AutoresearchValidateCreateBody = orvalSchemas.AutoresearchValidateCreateBody()+ return AutoresearchValidateCreateBody+}++const autoresearchValidateCreate = (): ToolBase<+ ReturnType<typeof AutoresearchValidateCreateSchema>,+ Schemas.ValidatePipelineResponse+> => ({+ name: 'autoresearch-validate-create',+ schema: AutoresearchValidateCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchValidateCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.target_event !== undefined) {+ body['target_event'] = params.target_event+ }+ if (params.target_definition !== undefined) {+ body['target_definition'] = params.target_definition+ }+ if (params.horizon_days !== undefined) {+ body['horizon_days'] = params.horizon_days+ }+ if (params.training_lookback_days !== undefined) {+ body['training_lookback_days'] = params.training_lookback_days+ }+ if (params.training_population !== undefined) {+ body['training_population'] = params.training_population+ }+ if (params.inference_population !== undefined) {+ body['inference_population'] = params.inference_population+ }+ const result = await context.api.request<Schemas.ValidatePipelineResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/validate/`,+ body,+ })+ return result+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'autoresearch-create': autoresearchCreate,+ 'autoresearch-list': autoresearchList,+ 'autoresearch-materialize-features': autoresearchMaterializeFeatures,+ 'autoresearch-models-list': autoresearchModelsList,+ 'autoresearch-models-retrieve': autoresearchModelsRetrieve,+ 'autoresearch-resolve-template-create': autoresearchResolveTemplateCreate,+ 'autoresearch-retrieve': autoresearchRetrieve,+ 'autoresearch-suggestions-create': autoresearchSuggestionsCreate,+ 'autoresearch-suggestions-list': autoresearchSuggestionsList,+ 'autoresearch-suggestions-respond': autoresearchSuggestionsRespond,+ 'autoresearch-train-create': autoresearchTrainCreate,+ 'autoresearch-training-runs-artifacts-get-create': autoresearchTrainingRunsArtifactsGetCreate,+ 'autoresearch-training-runs-artifacts-retrieve': autoresearchTrainingRunsArtifactsRetrieve,+ 'autoresearch-training-runs-artifacts-upload-create': autoresearchTrainingRunsArtifactsUploadCreate,+ 'autoresearch-training-runs-complete-create': autoresearchTrainingRunsCompleteCreate,+ 'autoresearch-training-runs-create': autoresearchTrainingRunsCreate,+ 'autoresearch-training-runs-history': autoresearchTrainingRunsHistory,+ 'autoresearch-training-runs-iterations-create': autoresearchTrainingRunsIterationsCreate,+ 'autoresearch-training-runs-list': autoresearchTrainingRunsList,+ 'autoresearch-validate-create': autoresearchValidateCreate,+}diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex e4745696d33d..4d4916857c94 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -6,6 +6,7 @@ import { GENERATED_TOOLS as actions } from './actions'import { GENERATED_TOOLS as ai_observability } from './ai_observability'import { GENERATED_TOOLS as alerts } from './alerts'import { GENERATED_TOOLS as annotations } from './annotations'+import { GENERATED_TOOLS as autoresearch } from './autoresearch'import { GENERATED_TOOLS as batch_exports } from './batch_exports'import { GENERATED_TOOLS as billing } from './billing'import { GENERATED_TOOLS as billing_alerts } from './billing_alerts'@@ -73,6 +74,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...ai_observability,...alerts,...annotations,+ ...autoresearch,...batch_exports,...billing,...billing_alerts,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex dd0176f6174a..7ce9b6f6461c 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1033,9 +1033,10 @@ describe('Tool Filtering - Feature Flags', () => {'data-quality-checks','context-layer','warehouse-multi-destination',+ 'autoresearch',]))- expect(flags).toHaveLength(37)+ expect(flags).toHaveLength(38)})it('every loops tool is gated on the loops flag', () => {