Skip to content

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

feat(signals): add atomic scout creation API (#73321)

Radu Raicea046164527192
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 7b13f5af75ca..6e374bd4bfd3 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -299,7 +299,7 @@ Defined in `backend/temporal/agentic/scout_coordinator.py`.
**Flow:**
-1. Activity `fetch_enabled_signals_scout_runs_activity` bounds candidates to the teams enrolled via the `signals-scout` feature flag's JSON payload allowlist — `guaranteed_team_ids` minus `skip_team_ids`, with a hardcoded fail-safe default (`_participating_teams` → `_enrolled_team_ids`, modeled on `posthog/temporal/ai_observability/team_discovery.py`). Enrollment is flag-driven: editing the payload in the flag UI enrolls or drains a team next tick with no manual seed. For each enrolled team it calls `sync_canonical_skills(team, prune=True)` to mirror the on-disk `signals-scout-*` skills onto the team's `LLMSkill` rows, then auto-registers a `SignalScoutConfig` for any scout skill missing one (`scout_harness/config_registry.register_missing_configs`; the `scout-config-create` endpoint is the explicit upsert counterpart, so a freshly authored scout is configurable without waiting for a tick). Failures here are logged and the tick continues — a stale skill is preferable to a dead tick.
+1. Activity `fetch_enabled_signals_scout_runs_activity` bounds candidates to the teams enrolled via the `signals-scout` feature flag's JSON payload allowlist — `guaranteed_team_ids` minus `skip_team_ids`, with a hardcoded fail-safe default (`_participating_teams` → `_enrolled_team_ids`, modeled on `posthog/temporal/ai_observability/team_discovery.py`). Enrollment is flag-driven: editing the payload in the flag UI enrolls or drains a team next tick with no manual seed. For each enrolled team it calls `sync_canonical_skills(team, prune=True)` to mirror the on-disk `signals-scout-*` skills onto the team's `LLMSkill` rows, then auto-registers a `SignalScoutConfig` for any scout skill missing one (`scout_harness/config_registry.register_missing_configs`). The `scout-create` endpoint atomically creates a custom skill and config; `scout-config-create` is the lower-level explicit upsert for an existing skill. Failures here are logged and the tick continues — a stale skill is preferable to a dead tick.
2. For each enabled config, the coordinator computes how overdue the scout is. Rolling schedules are due when `last_run_at is None`, or `now - last_run_at >= run_interval_minutes`. A config with a `run_cron_schedule` is due at the earliest unfulfilled cron slot, evaluated as wall-clock time in the project's timezone (so slots follow daylight-saving changes). It runs on the first coordinator tick at or after that slot. Saving the config after a slot has passed waits for the next slot. There is no sampling — every due scout is planned.
3. Due runs are sorted most-overdue-first and truncated at `MAX_RUNS_PER_TICK` (50 per tick; the cost bound — overflow catches up next tick). `last_run_at` is advanced via `.update()` for everything dispatched (bypasses `save()`, so the per-tick write never hits the activity log). Planned runs are re-sorted by `(team_id, skill_name)` for stable child IDs.
4. Each `PlannedRun` becomes a child `RunSignalsScoutWorkflow` started with `ParentClosePolicy.ABANDON` and a deterministic workflow ID per `(team_id, skill_name, tick_id)` so retried coordinators can't double-launch within a tick.
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index b8bf45d2b0c2..1d1c869ae188 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -8,6 +8,7 @@ from products.signals.backend.scout_harness.views import (
SignalScoutMetadataViewSet,
SignalScoutNoteViewSet,
SignalScoutRunViewSet,
+ SignalScoutViewSet,
SignalScratchpadViewSet,
)
from products.signals.backend.views import SignalViewSet
@@ -66,3 +67,4 @@ def register_routes(routers: RouterRegistry) -> None:
"project_signals_scout_members",
["team_id"],
)
+ routers.projects.register(r"signals/scout", SignalScoutViewSet, "project_signals_scout", ["team_id"])
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index d380bc23efca..31e3b17f14dd 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -167,9 +167,12 @@ ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's
- `views.py`
`SignalScoutRunViewSet`, `SignalScoutConfigViewSet`, `SignalScratchpadViewSet`,
`SignalScoutNoteViewSet`, `SignalProjectProfileViewSet`, `SignalScoutMetadataViewSet`,
- `SignalScoutMembersViewSet`.
- Routed under `environment_signals_scout_*` basenames in `posthog/api/__init__.py`
+ `SignalScoutMembersViewSet`, `SignalScoutViewSet`.
+ Routed under `project_signals_scout_*` basenames in `products/signals/backend/routes.py`
and exposed as `scout-*` MCP tools via `products/signals/mcp/tools.yaml`.
+ `SignalScoutViewSet` backs `scout-create`: it creates a custom `signals-scout-*` skill
+ and its runnable config atomically, grants the report-channel tools server-side, and
+ treats an identical definition as a retry while rejecting conflicting definitions.
`SignalScoutMembersViewSet` (`scout-members-list`) is the reviewer-routing roster:
it returns the project's members (those with access to the team) with `user_uuid` / `email` /
`github_login` so a report-channel scout can populate `suggested_reviewers` at cold start. The roster
@@ -182,8 +185,8 @@ ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's
`report_generation/resolve_reviewers.list_project_members` (through `Team.all_users_with_access()`,
so private-project access control is honored), the project-nested path that the org-nested
`org-members-list` tool (stripped + 403'd for a scoped-team token) can't provide.
- The config viewset is the no-wait creation path: `create` registers (upserts) a
- config for an already-authored skill with its schedule/emit posture in one call.
+ The config viewset remains the lower-level no-wait creation path: `create` registers
+ (upserts) a config for an already-authored skill with its schedule/emit posture in one call.
`list` is strictly read-only (its MCP tool is annotated `readOnly`) — it never
mints config rows. The metadata viewset is the read-only `scout/metadata/current/`
endpoint that reports enrollment + banner + enforced limits via
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 94d0870d092c..01932ef989d3 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -34,6 +34,13 @@ from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_
from products.signals.backend.scout_harness.tools.report import MAX_REPORT_TITLE_LENGTH, MAX_SUGGESTED_REVIEWERS
from products.signals.backend.scout_harness.tools.runs import DEFAULT_FINDINGS_WINDOW_HOURS, MAX_FINDINGS_WINDOW_HOURS
from products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH
+from products.skills.backend.api.skill_serializers import (
+ MAX_SKILL_FILE_COUNT,
+ LLMSkillFileInputSerializer,
+ validate_skill_body_size,
+ validate_skill_name_value,
+)
+from products.skills.backend.models.skills import LLMSkill
# --- Run history -----------------------------------------------------------
@@ -1855,20 +1862,9 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):
fields = ["enabled", "emit", "run_interval_minutes", "run_cron_schedule", "output_destinations"]
-class SignalScoutConfigCreateSerializer(serializers.Serializer):
- """Request body for registering a scout config without waiting for the coordinator tick.
+class SignalScoutConfigOptionsSerializer(serializers.Serializer):
+ """Schedule, enablement, and delivery options accepted while creating a scout."""
- Upsert keyed on `skill_name`: if the coordinator (or a concurrent caller) already
- registered the row, the provided tunables are applied to it instead.
- """
-
- skill_name = serializers.CharField(
- max_length=200,
- help_text=(
- "The `signals-scout-*` skill to register a config for. The skill must already "
- "exist on this project — author it via the skills store first."
- ),
- )
enabled = serializers.BooleanField(
required=False,
help_text="Whether this scout runs on its schedule. Defaults to true.",
@@ -1904,6 +1900,29 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):
def validate_run_cron_schedule(self, value: str | None) -> str | None:
return _validate_run_cron_schedule(value) if value is not None else None
+ def validate_output_destinations(self, value: dict) -> dict:
+ context = self.context
+ if not isinstance(context.get("project_id"), int):
+ team = context.get("team")
+ context = {**context, "project_id": getattr(team, "project_id", None)}
+ return _validate_output_destinations(value, context)
+
+
+class SignalScoutConfigCreateSerializer(SignalScoutConfigOptionsSerializer):
+ """Request body for registering a scout config without waiting for the coordinator tick.
+
+ Upsert keyed on `skill_name`: if the coordinator (or a concurrent caller) already
+ registered the row, the provided tunables are applied to it instead.
+ """
+
+ skill_name = serializers.CharField(
+ max_length=200,
+ help_text=(
+ "The `signals-scout-*` skill to register a config for. The skill must already "
+ "exist on this project — author it via the skills store first."
+ ),
+ )
+
def validate_skill_name(self, value: str) -> str:
# A config for a non-scout skill would never dispatch (the coordinator only considers
# `signals-scout-*` names), so reject it here instead of minting an invisible orphan.
@@ -1911,8 +1930,78 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):
raise serializers.ValidationError(f"Scout skill names must start with '{SIGNALS_SCOUT_SKILL_PREFIX}'.")
return value
- def validate_output_destinations(self, value: dict) -> dict:
- return _validate_output_destinations(value, self.context)
+
+class SignalScoutCreateSerializer(serializers.Serializer):
+ """Create a runnable custom scout and its config in one atomic request."""
+
+ name = serializers.CharField(
+ max_length=64,
+ help_text=(
+ "Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, "
+ "numbers, and hyphens."
+ ),
+ )
+ description = serializers.CharField(
+ max_length=4096,
+ help_text="Short description of the signal or behavior this scout investigates.",
+ )
+ body = serializers.CharField(
+ trim_whitespace=False,
+ help_text=(
+ "Complete markdown prompt executed on every scout run. Include any project-specific signal names, "
+ "thresholds, investigation steps, and report criteria here."
+ ),
+ )
+ files = LLMSkillFileInputSerializer(
+ many=True,
+ required=False,
+ help_text="Optional reference files bundled with the scout prompt.",
+ )
+ config = SignalScoutConfigOptionsSerializer(
+ required=False,
+ help_text=(
+ "Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, "
+ "emitting scout on the daily interval with no external destination."
+ ),
+ )
+
+ def validate_name(self, value: str) -> str:
+ value = validate_skill_name_value(value)
+ if not value.startswith(SIGNALS_SCOUT_SKILL_PREFIX):
+ raise serializers.ValidationError(f"Scout names must start with '{SIGNALS_SCOUT_SKILL_PREFIX}'.")
+ return value
+
+ def validate_body(self, value: str) -> str:
+ return validate_skill_body_size(value)
+
+ def validate_files(self, value: list[dict[str, str]]) -> list[dict[str, str]]:
+ if len(value) > MAX_SKILL_FILE_COUNT:
+ raise serializers.ValidationError(f"A scout may contain at most {MAX_SKILL_FILE_COUNT} files.")
+ paths = [file["path"] for file in value]
+ if len(paths) != len(set(paths)):
+ raise serializers.ValidationError("Duplicate file paths are not allowed.")
+ return value
+
+
+class SignalScoutSkillSummarySerializer(serializers.ModelSerializer):
+ allowed_tools = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Server-managed report tools granted to this scout.",
+ )
+
+ class Meta:
+ model = LLMSkill
+ fields = ["id", "name", "description", "version", "allowed_tools"]
+ read_only_fields = fields
+
+
+class SignalScoutCreateResponseSerializer(serializers.Serializer):
+ created = serializers.BooleanField(
+ help_text="True when this request created the missing scout skill or config; false when both already existed."
+ )
+ skill = SignalScoutSkillSummarySerializer()
+ config = SignalScoutConfigSerializer()
class SignalScoutManualRunSerializer(serializers.Serializer):
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 43b2076f6c5e..eb21b6a3ecb5 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -25,6 +25,7 @@ from dataclasses import dataclass
from datetime import timedelta
from typing import cast
+from django.db import transaction
from django.utils import timezone
import structlog
@@ -37,7 +38,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from temporalio.exceptions import WorkflowAlreadyStartedError
-from posthog.api.mixins import validated_request
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
# PostHog's `SessionAuthentication` (not DRF's) calls `enforce_two_factor()`.
@@ -48,7 +49,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.permissions import APIScopePermission
+from posthog.permissions import AccessControlPermission, APIScopePermission
from posthog.rbac.user_access_control import UserAccessControl
from posthog.temporal.common.client import sync_connect
@@ -98,12 +99,18 @@ from products.signals.backend.scout_harness.serializers import (
SignalScoutConfigCreateSerializer,
SignalScoutConfigSerializer,
SignalScoutConfigUpdateSerializer,
+ SignalScoutCreateResponseSerializer,
+ SignalScoutCreateSerializer,
SignalScoutEmissionSerializer,
SignalScoutManualRunSerializer,
SignalScoutRunDetailSerializer,
SignalScoutRunSummarySerializer,
)
-from products.signals.backend.scout_harness.skill_loader import SkillNotFoundError, load_skill_for_run
+from products.signals.backend.scout_harness.skill_loader import (
+ REPORT_CHANNEL_TOOLS,
+ SkillNotFoundError,
+ load_skill_for_run,
+)
from products.signals.backend.scout_harness.team_limits import (
DAILY_BUDGET_WINDOW,
_canonicalize_team_config_keys,
@@ -146,7 +153,8 @@ from products.signals.backend.scout_harness.tools.scratchpad import (
search_scratchpad,
)
from products.signals.backend.scout_report import InvalidScoutReportError
-from products.skills.backend.models.skills import LLMSkill
+from products.skills.backend.api.skill_services import LLMSkillDuplicateNameConflictError, create_skill
+from products.skills.backend.models.skills import LLMSkill, LLMSkillFile
from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
@@ -1487,6 +1495,79 @@ def _reject_if_enabled_cap_reached(team_id: int, skill_name: str) -> None:
)
+def _upsert_scout_config(
+ *,
+ team_id: int,
+ skill_name: str,
+ tunables: dict,
+ request: Request,
+ serializer_context: dict,
+) -> tuple[SignalScoutConfig, bool]:
+ """Create or tune one config while preserving the existing config endpoint's upsert semantics."""
+
+ # The per-team cap only gates net-new enables: creating an enabled row or
+ # flipping a disabled row on. Reasserting an already-enabled scout stays exempt.
+ existing = SignalScoutConfig.objects.for_team(team_id).filter(skill_name=skill_name).first()
+ will_enable = (
+ tunables.get("enabled", True)
+ if existing is None
+ else (not existing.enabled and tunables.get("enabled") is True)
+ )
+ if will_enable:
+ _reject_if_enabled_cap_reached(team_id, skill_name)
+
+ # `team_id` stays in the kwargs because queryset filters do not propagate into
+ # the row Django builds for `get_or_create`.
+ config, created = SignalScoutConfig.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ skill_name=skill_name,
+ defaults={
+ **tunables,
+ "created_by": request.user,
+ "enabled_by": request.user if tunables.get("enabled", True) else None,
+ },
+ )
+ if created or not tunables:
+ return config, created
+
+ # The coordinator or another caller may have won the create race. Apply only
+ # fields supplied by this request so omitted settings remain untouched.
+ update = SignalScoutConfigUpdateSerializer(
+ config,
+ data=tunables,
+ partial=True,
+ context=serializer_context,
+ )
+ update.is_valid(raise_exception=True)
+ save_kwargs = {}
+ if not config.enabled and update.validated_data.get("enabled"):
+ save_kwargs["enabled_by"] = request.user
+ return update.save(**save_kwargs), False
+
+
+def _skill_matches_scout_definition(
+ skill: LLMSkill,
+ *,
+ description: str,
+ body: str,
+ files: list[dict[str, str]],
+) -> bool:
+ stored_files = list(
+ LLMSkillFile.objects.filter(skill=skill).order_by("path").values_list("path", "content", "content_type")
+ )
+ requested_files = sorted((file["path"], file["content"], file.get("content_type", "text/plain")) for file in files)
+ return (
+ skill.description == description
+ and skill.body == body
+ and skill.category == "scout"
+ and skill.license == ""
+ and skill.compatibility == ""
+ and skill.metadata == {}
+ and set(skill.allowed_tools or []) == REPORT_CHANNEL_TOOLS
+ and stored_files == requested_files
+ )
+
+
@dataclass(frozen=True)
class _ScoutSkillInfo:
"""Per-skill metadata the config serializer needs but doesn't store on the config row.
@@ -1519,6 +1600,114 @@ def _skill_info_for(team_id: int, skill_names: list[str]) -> dict[str, _ScoutSki
}
+class SignalScoutViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Create a runnable custom scout and its config through one atomic API call."""
+
+ serializer_class = SignalScoutCreateSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [
+ IsAuthenticated,
+ APIScopePermission,
+ AccessControlPermission,
+ ScoutCanonicalTeamAccessPermission,
+ ]
+ required_scopes = ["llm_skill:write", "signal_scout:write"]
+ scope_object = "llm_skill"
+ queryset = LLMSkill.objects.all()
+ pagination_class = None
+
+ def _assert_can_create_scout(self, *, user: User, canonical_team: Team) -> None:
+ access = UserAccessControl(user=user, team=canonical_team)
+ if not access.check_access_level_for_resource("llm_skill", "editor"):
+ raise exceptions.PermissionDenied("Creating a scout requires editor access to skills.")
+
+ @validated_request(
+ SignalScoutCreateSerializer,
+ responses={
+ 201: OpenApiResponse(
+ response=SignalScoutCreateResponseSerializer,
+ description="The scout skill, config, or both were created.",
+ ),
+ 200: OpenApiResponse(
+ response=SignalScoutCreateResponseSerializer,
+ description="The scout definition already existed; the requested config fields were applied.",
+ ),
+ 400: OpenApiResponse(description="The scout definition, config, or destination is invalid."),
+ 409: OpenApiResponse(description="A scout with this name already exists with a different definition."),
+ },
+ summary="Create a scout",
+ description=(
+ "Create a `signals-scout-*` skill and its runnable config atomically. The skill always receives the "
+ "report-channel tools. The optional config controls schedule, enablement, dry-run posture, and typed "
+ "destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields; "
+ "reusing its name for a different definition returns 409."
+ ),
+ operation_id="signals_scout_create",
+ include_serializer_context=True,
+ )
+ def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ canonical_team = self.team.parent_team or self.team
+ user = cast(User, request.user)
+ self._assert_can_create_scout(user=user, canonical_team=canonical_team)
+ team_id = canonical_team.id
+ validated = request.validated_data
+ name = validated["name"]
+ description = validated["description"]
+ body = validated["body"]
+ files = validated.get("files", [])
+ config_options = validated.get("config", {})
+ serializer_context = {**self.get_serializer_context(), "project_id": self.team.project_id}
+
+ with transaction.atomic():
+ try:
+ skill = create_skill(
+ canonical_team,
+ user=user,
+ name=name,
+ description=description,
+ body=body,
+ allowed_tools=sorted(REPORT_CHANNEL_TOOLS),
+ files=files,
+ )
+ skill_created = True
+ except LLMSkillDuplicateNameConflictError:
+ existing_skill = (
+ LLMSkill.objects.select_for_update()
+ .filter(team=canonical_team, name=name, is_latest=True, deleted=False)
+ .first()
+ )
+ if existing_skill is None:
+ raise
+ if not _skill_matches_scout_definition(
+ existing_skill,
+ description=description,
+ body=body,
+ files=files,
+ ):
+ raise Conflict("A scout with this name already exists with a different definition.")
+ skill = existing_skill
+ skill_created = False
+
+ config, config_created = _upsert_scout_config(
+ team_id=team_id,
+ skill_name=name,
+ tunables=config_options,
+ request=request,
+ serializer_context=serializer_context,
+ )
+
+ created = skill_created or config_created
+ skill_info = _skill_info_for(team_id, [name])
+ response = SignalScoutCreateResponseSerializer(
+ {"created": created, "skill": skill, "config": config},
+ context={"skill_info": skill_info},
+ )
+ return Response(
+ response.data,
+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
+ )
+
+
class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Per-scout config: list, register, tune, and delete each scout's schedule, enablement,
and emit posture.
@@ -1615,43 +1804,13 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# the skills UI's Scouts tab immediately, without waiting for the next coordinator reconcile.
ensure_scout_category(team_id, skill_name=skill_name)
tunables = {key: value for key, value in serializer.validated_data.items() if key != "skill_name"}
- # The per-team cap only gates net-new enables: a fresh row defaulting (or set) to
- # enabled, or an upsert flipping a disabled row on. Tuning an already-enabled scout
- # stays exempt via the exclude-self count.
- existing = SignalScoutConfig.objects.for_team(team_id).filter(skill_name=skill_name).first()
- will_enable = (
- tunables.get("enabled", True)
- if existing is None
- else (not existing.enabled and tunables.get("enabled") is True)
- )
- if will_enable:
- _reject_if_enabled_cap_reached(team_id, skill_name)
- # `team_id` stays in the kwargs: `get_or_create` builds the created row from
- # kwargs/defaults only — the queryset's team filter does not propagate into `create`.
- config, created = SignalScoutConfig.objects.for_team(team_id).get_or_create(
+ config, created = _upsert_scout_config(
team_id=team_id,
skill_name=skill_name,
- defaults={
- **tunables,
- "created_by": request.user,
- # Configs default enabled; record who switched the scout on (it drives spend).
- "enabled_by": request.user if tunables.get("enabled", True) else None,
- },
+ tunables=tunables,
+ request=request,
+ serializer_context={**self.get_serializer_context(), "project_id": self.team.project_id},
)
- if not created and tunables:
- # The coordinator tick (or a concurrent caller) won the race — apply the provided
- # fields to the existing row so the call still lands the requested settings.
- update = SignalScoutConfigUpdateSerializer(
- config,
- data=tunables,
- partial=True,
- context={**self.get_serializer_context(), "project_id": self.team.project_id},
- )
- update.is_valid(raise_exception=True)
- save_kwargs = {}
- if not config.enabled and update.validated_data.get("enabled"):
- save_kwargs["enabled_by"] = request.user
- config = update.save(**save_kwargs)
skill_info = _skill_info_for(team_id, [config.skill_name])
return Response(
SignalScoutConfigSerializer(config, context={"skill_info": skill_info}).data,
diff --git a/products/signals/backend/test/test_scout_create_api.py b/products/signals/backend/test/test_scout_create_api.py
new file mode 100644
index 000000000000..6a47cca1416c
--- /dev/null
+++ b/products/signals/backend/test/test_scout_create_api.py
@@ -0,0 +1,214 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.team import Team
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.signals.backend.models import SignalScoutConfig
+from products.skills.backend.models.skills import LLMSkill, LLMSkillFile
+
+
+class TestSignalScoutCreateAPI(APIBaseTest):
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/"
+
+ def _payload(self) -> dict:
+ return {
+ "name": "signals-scout-checkout-failures",
+ "description": "Investigates meaningful checkout_failed spikes.",
+ "body": "# Checkout failure scout\n\nInvestigate the `checkout_failed` signal and file actionable reports.",
+ "files": [
+ {
+ "path": "references/checkout.md",
+ "content": "Treat payment_declined as expected unless its reach changes materially.",
+ "content_type": "text/markdown",
+ }
+ ],
+ }
+
+ def test_create_builds_runnable_scout_with_slack_destination(self) -> None:
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ payload = {
+ **self._payload(),
+ "config": {
+ "enabled": False,
+ "emit": False,
+ "run_cron_schedule": "30 9 * * 1-5",
+ "output_destinations": {
+ "slack": {
+ "integration_id": integration.id,
+ "channel": "CSCOUTS|#scout-findings",
+ }
+ },
+ },
+ }
+
+ response = self.client.post(self._url(), data=payload, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["created"] is True
+ skill = LLMSkill.objects.get(team=self.team, name=payload["name"], is_latest=True)
+ assert skill.body == payload["body"]
+ assert skill.allowed_tools == ["edit_report", "emit_report"]
+ assert skill.category == "scout"
+ assert list(LLMSkillFile.objects.filter(skill=skill).values_list("path", flat=True)) == [
+ "references/checkout.md"
+ ]
+ config = SignalScoutConfig.all_teams.get(team=self.team, skill_name=payload["name"])
+ assert config.enabled is False
+ assert config.emit is False
+ assert config.run_cron_schedule == "30 9 * * 1-5"
+ assert config.output_destinations == payload["config"]["output_destinations"]
+ assert response.json()["config"]["description"] == payload["description"]
+
+ def test_matching_definition_retry_is_idempotent_and_applies_config(self) -> None:
+ payload = self._payload()
+
+ first = self.client.post(self._url(), data=payload, format="json")
+ second = self.client.post(
+ self._url(),
+ data={**payload, "config": {"enabled": False, "emit": False}},
+ format="json",
+ )
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json()["created"] is False
+ assert LLMSkill.objects.filter(team=self.team, name=payload["name"], deleted=False).count() == 1
+ assert SignalScoutConfig.all_teams.filter(team=self.team, skill_name=payload["name"]).count() == 1
+ config = SignalScoutConfig.all_teams.get(team=self.team, skill_name=payload["name"])
+ assert config.enabled is False
+ assert config.emit is False
+
+ def test_conflicting_definition_returns_409_without_changing_scout(self) -> None:
+ payload = self._payload()
+ self.client.post(self._url(), data=payload, format="json")
+
+ response = self.client.post(
+ self._url(),
+ data={**payload, "body": "# Different instructions", "config": {"enabled": False}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ skill = LLMSkill.objects.get(team=self.team, name=payload["name"], is_latest=True)
+ assert skill.body == payload["body"]
+ config = SignalScoutConfig.all_teams.get(team=self.team, skill_name=payload["name"])
+ assert config.enabled is True
+
+ def test_invalid_slack_destination_does_not_create_skill(self) -> None:
+ other_organization = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_organization, name="Other")
+ integration = Integration.objects.create(team=other_team, kind=Integration.IntegrationKind.SLACK)
+ payload = {
+ **self._payload(),
+ "config": {
+ "output_destinations": {
+ "slack": {
+ "integration_id": integration.id,
+ "channel": "CSCOUTS|#scout-findings",
+ }
+ }
+ },
+ }
+
+ response = self.client.post(self._url(), data=payload, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not LLMSkill.objects.filter(team=self.team, name=payload["name"], deleted=False).exists()
+
+ def test_config_failure_rolls_back_skill_creation(self) -> None:
+ LLMSkill.objects.create(
+ team=self.team,
+ name="signals-scout-existing",
+ description="Existing scout",
+ body="# Existing",
+ )
+ SignalScoutConfig.all_teams.create(
+ team=self.team,
+ skill_name="signals-scout-existing",
+ enabled=True,
+ )
+ payload = self._payload()
+
+ with patch("products.signals.backend.scout_harness.views.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
+ response = self.client.post(self._url(), data=payload, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not LLMSkill.objects.filter(team=self.team, name=payload["name"], deleted=False).exists()
+ assert not SignalScoutConfig.all_teams.filter(team=self.team, skill_name=payload["name"]).exists()
+
+ @parameterized.expand(
+ [
+ ("both_scopes", ["llm_skill:write", "signal_scout:write"], status.HTTP_201_CREATED),
+ ("missing_scout_scope", ["llm_skill:write"], status.HTTP_403_FORBIDDEN),
+ ("missing_skill_scope", ["signal_scout:write"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_scoped_key_requires_skill_and_scout_write(
+ self, _name: str, scopes: list[str], expected_status: int
+ ) -> None:
+ api_key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+ payload = self._payload()
+
+ response = self.client.post(self._url(), data=payload, format="json")
+
+ assert response.status_code == expected_status
+ assert LLMSkill.objects.filter(team=self.team, name=payload["name"], deleted=False).exists() is (
+ expected_status == status.HTTP_201_CREATED
+ )
+
+ def test_child_scoped_api_key_cannot_create_parent_scout(self) -> None:
+ environment = Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Child-scoped key",
+ user=self.user,
+ secure_value=hash_key_value(raw_key),
+ scopes=["llm_skill:write", "signal_scout:write"],
+ scoped_teams=[environment.id],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")
+ payload = self._payload()
+
+ response = self.client.post(
+ f"/api/projects/{environment.id}/signals/scout/",
+ data=payload,
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not LLMSkill.objects.filter(team=self.team, name=payload["name"], deleted=False).exists()
+
+ def test_environment_create_requires_skill_editor_access_on_parent(self) -> None:
+ environment = Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ with patch("products.signals.backend.scout_harness.views.UserAccessControl") as user_access_control:
+ user_access_control.return_value.check_access_level_for_resource.return_value = False
+ response = self.client.post(
+ f"/api/projects/{environment.id}/signals/scout/",
+ data=self._payload(),
+ format="json",
+ )
+
+ user_access_control.assert_called_once_with(user=self.user, team=self.team)
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not LLMSkill.objects.filter(team=self.team, name=self._payload()["name"], deleted=False).exists()
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 1fd77c5698ff..67f098d78693 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1460,12 +1460,20 @@ export interface SignalReportRefundSummaryResponseApi {
period_billable_credits: number
}
-export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]
-
-export const ScoutOriginEnumApi = {
- Canonical: 'canonical',
- Custom: 'custom',
-} as const
+export interface LLMSkillFileInputApi {
+ /**
+ * File path relative to skill root, e.g. 'scripts/setup.sh' or 'references/guide.md'.
+ * @maxLength 500
+ */
+ path: string
+ /** Text content of the file. */
+ content: string
+ /**
+ * MIME type of the file content.
+ * @maxLength 100
+ */
+ content_type?: string
+}
export interface SignalScoutSlackDestinationApi {
/**
@@ -1486,6 +1494,68 @@ export interface SignalScoutOutputDestinationsApi {
slack?: SignalScoutSlackDestinationApi | null
}
+/**
+ * Schedule, enablement, and delivery options accepted while creating a scout.
+ */
+export interface SignalScoutConfigOptionsApi {
+ /** Whether this scout runs on its schedule. Defaults to true. */
+ enabled?: boolean
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
+ emit?: boolean
+ /**
+ * Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).
+ * @minimum 30
+ * @maximum 43200
+ */
+ run_interval_minutes?: number
+ /** Destinations that receive each finding or report this scout emits. Empty by default. */
+ output_destinations?: SignalScoutOutputDestinationsApi
+ /**
+ * Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart.
+ * @maxLength 100
+ * @nullable
+ */
+ run_cron_schedule?: string | null
+}
+
+/**
+ * Create a runnable custom scout and its config in one atomic request.
+ */
+export interface SignalScoutCreateApi {
+ /**
+ * Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, numbers, and hyphens.
+ * @maxLength 64
+ */
+ name: string
+ /**
+ * Short description of the signal or behavior this scout investigates.
+ * @maxLength 4096
+ */
+ description: string
+ /** Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here. */
+ body: string
+ /** Optional reference files bundled with the scout prompt. */
+ files?: LLMSkillFileInputApi[]
+ /** Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination. */
+ config?: SignalScoutConfigOptionsApi
+}
+
+export interface SignalScoutSkillSummaryApi {
+ readonly id: string
+ readonly name: string
+ readonly description: string
+ readonly version: number
+ /** Server-managed report tools granted to this scout. */
+ readonly allowed_tools: readonly string[]
+}
+
+export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]
+
+export const ScoutOriginEnumApi = {
+ Canonical: 'canonical',
+ Custom: 'custom',
+} as const
+
/**
* Read shape for a per-(team, skill) scout config.
*
@@ -1525,6 +1595,13 @@ export interface SignalScoutConfigApi {
readonly created_at: string
}
+export interface SignalScoutCreateResponseApi {
+ /** True when this request created the missing scout skill or config; false when both already existed. */
+ created: boolean
+ skill: SignalScoutSkillSummaryApi
+ config: SignalScoutConfigApi
+}
+
/**
* Request body for registering a scout config without waiting for the coordinator tick.
*
@@ -1532,11 +1609,6 @@ export interface SignalScoutConfigApi {
* registered the row, the provided tunables are applied to it instead.
*/
export interface SignalScoutConfigCreateApi {
- /**
- * The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.
- * @maxLength 200
- */
- skill_name: string
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -1555,6 +1627,11 @@ export interface SignalScoutConfigCreateApi {
* @nullable
*/
run_cron_schedule?: string | null
+ /**
+ * The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.
+ * @maxLength 200
+ */
+ skill_name: string
}
/**
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index acea60e5a0d6..04dfacf7b4fb 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -51,6 +51,8 @@ import type {
SignalReportStateRequestApi,
SignalScoutConfigApi,
SignalScoutConfigCreateApi,
+ SignalScoutCreateApi,
+ SignalScoutCreateResponseApi,
SignalScoutEmissionApi,
SignalScoutManualRunApi,
SignalScoutRunDetailApi,
@@ -485,6 +487,27 @@ export const signalsReportsRefundSummaryRetrieve = async (
})
}
+export const getSignalsScoutCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/scout/`
+}
+
+/**
+ * Create a `signals-scout-*` skill and its runnable config atomically. The skill always receives the report-channel tools. The optional config controls schedule, enablement, dry-run posture, and typed destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields; reusing its name for a different definition returns 409.
+ * @summary Create a scout
+ */
+export const signalsScoutCreate = async (
+ projectId: string,
+ signalScoutCreateApi: SignalScoutCreateApi,
+ options?: RequestInit
+): Promise<SignalScoutCreateResponseApi> => {
+ return apiMutator<SignalScoutCreateResponseApi>(getSignalsScoutCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalScoutCreateApi),
+ })
+}
+
export const getSignalsScoutConfigListUrl = (projectId: string) => {
return `/api/projects/${projectId}/signals/scout/configs/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 07d580b7799a..5f82311503a4 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -225,12 +225,128 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Create a `signals-scout-*` skill and its runnable config atomically. The skill always receives the report-channel tools. The optional config controls schedule, enablement, dry-run posture, and typed destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields; reusing its name for a different definition returns 409.
+ * @summary Create a scout
+ */
+export const signalsScoutCreateBodyNameMax = 64
+
+export const signalsScoutCreateBodyDescriptionMax = 4096
+
+export const signalsScoutCreateBodyFilesItemPathMax = 500
+
+export const signalsScoutCreateBodyFilesItemContentTypeDefault = `text/plain`
+export const signalsScoutCreateBodyFilesItemContentTypeMax = 100
+
+export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30
+export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
+
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255
+
+export const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100
+
+export const SignalsScoutCreateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(signalsScoutCreateBodyNameMax)
+ .describe(
+ 'Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, numbers, and hyphens.'
+ ),
+ description: zod
+ .string()
+ .max(signalsScoutCreateBodyDescriptionMax)
+ .describe('Short description of the signal or behavior this scout investigates.'),
+ body: zod
+ .string()
+ .describe(
+ 'Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here.'
+ ),
+ files: zod
+ .array(
+ zod.object({
+ path: zod
+ .string()
+ .max(signalsScoutCreateBodyFilesItemPathMax)
+ .describe(
+ "File path relative to skill root, e.g. 'scripts\/setup.sh' or 'references\/guide.md'."
+ ),
+ content: zod.string().describe('Text content of the file.'),
+ content_type: zod
+ .string()
+ .max(signalsScoutCreateBodyFilesItemContentTypeMax)
+ .default(signalsScoutCreateBodyFilesItemContentTypeDefault)
+ .describe('MIME type of the file content.'),
+ })
+ )
+ .optional()
+ .describe('Optional reference files bundled with the scout prompt.'),
+ config: zod
+ .object({
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether this scout runs on its schedule. Defaults to true.'),
+ emit: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutCreateBodyConfigOneRunIntervalMinutesMin)
+ .max(signalsScoutCreateBodyConfigOneRunIntervalMinutesMax)
+ .optional()
+ .describe('Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).'),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe('Destinations that receive each finding or report this scout emits. Empty by default.'),
+ run_cron_schedule: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOneRunCronScheduleMax)
+ .nullish()
+ .describe(
+ "Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."
+ ),
+ })
+ .describe('Schedule, enablement, and delivery options accepted while creating a scout.')
+ .optional()
+ .describe(
+ 'Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination.'
+ ),
+ })
+ .describe('Create a runnable custom scout and its config in one atomic request.')
+
/**
* Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, and output destinations. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
* @summary Create a scout config
*/
-export const signalsScoutConfigCreateBodySkillNameMax = 200
-
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
@@ -238,14 +354,10 @@ export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
+export const signalsScoutConfigCreateBodySkillNameMax = 200
+
export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.object({
- skill_name: zod
- .string()
- .max(signalsScoutConfigCreateBodySkillNameMax)
- .describe(
- 'The `signals-scout-\*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.'
- ),
enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),
emit: zod
.boolean()
@@ -294,6 +406,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.describe(
"Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."
),
+ skill_name: zod
+ .string()
+ .max(signalsScoutConfigCreateBodySkillNameMax)
+ .describe(
+ 'The `signals-scout-\*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.'
+ ),
})
.describe(
'Request body for registering a scout config without waiting for the coordinator tick.\n\nUpsert keyed on `skill_name`: if the coordinator (or a concurrent caller) already\nregistered the row, the provided tunables are applied to it instead.'
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index f0489858dc8e..2e02ff047088 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -438,6 +438,29 @@ tools:
minutes apart; set null to return to the rolling interval. You can also configure
`output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records
who flipped it on and is activity-logged, since running a scout drives spend.
+ scout-create:
+ operation: signals_scout_create
+ enabled: true
+ scopes:
+ - llm_skill:write
+ - signal_scout:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Create a scout
+ description: >
+ Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete
+ markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps,
+ and report criteria there. The server always grants the report-channel tools. Optional `files` bundle
+ reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and
+ typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied
+ config fields. Reusing the name for a different definition returns a conflict.
+ confirmed_action:
+ message: >
+ About to create scout '{name}', a persistent automation that can run unattended on its configured
+ schedule and write reports to the inbox when enabled with emit on. Reply 'confirm' to create it.
+ action_label: create scout
scout-edit-report:
operation: signals_scout_edit_report
enabled: true
diff --git a/products/signals/skills/AGENTS.md b/products/signals/skills/AGENTS.md
index 100568c053a2..962c3e07812f 100644
--- a/products/signals/skills/AGENTS.md
+++ b/products/signals/skills/AGENTS.md
@@ -313,8 +313,10 @@ every 24 hours) and a `last_run_at` stamp. Every tick the coordinator:
enrolls or drains a team next tick — no manual seed.
2. Auto-registers a config for any `signals-scout-*` skill missing one
(`scout_harness/config_registry.register_missing_configs`) — on an enrolled team,
- authoring a skill is enough to get a scout. To register (and tune) one immediately
- instead, use the `scout-config-create` endpoint.
+ authoring a skill is enough to get a scout. For custom scouts, `scout-create-prepare`
+ validates and signs the skill and config, then `scout-create-execute` creates them
+ after the user confirms; `scout-config-create` remains the lower-level way to register
+ a config for an existing skill.
3. Dispatches every enabled scout whose schedule is due (`last_run_at is None`, or
`now - last_run_at >= run_interval_minutes`), most-overdue first, capped at
`MAX_RUNS_PER_TICK` per tick. Each due scout becomes one `RunSignalsScoutWorkflow`
@@ -322,8 +324,8 @@ every 24 hours) and a `last_run_at` stamp. Every tick the coordinator:
Pausing a scout is `enabled=False` on its config; slowing it is a larger
`run_interval_minutes`. Both are tunable via the `scout-config-update` MCP
-tool, and settable at creation time via `scout-config-create` (an upsert that
-registers the config immediately instead of waiting for the tick). See
+tool, and settable for a new custom scout via the nested `config` object on
+`scout-create-prepare`. See
`scout_coordinator._collect_planned_runs` for the exact due-check.
### Authoring a new scout
diff --git a/products/signals/skills/authoring-scouts/SKILL.md b/products/signals/skills/authoring-scouts/SKILL.md
index a79da13f7e34..918ed2924076 100644
--- a/products/signals/skills/authoring-scouts/SKILL.md
+++ b/products/signals/skills/authoring-scouts/SKILL.md
@@ -64,10 +64,10 @@ There are two independent decisions: **what** you're building, and **where** it
### Where
-| Path | Mechanism | Use when |
-| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
-| **Per-team** (the common user path) | Create/edit a `signals-scout-*` `LLMSkill` row in the project's skills store via `posthog:skill-create` / `-update` / `-file-create`, then register its config immediately via `posthog:scout-config-create`. | Customizing for one project. The harness globs the row in on the next tick; canonical sync leaves your edited ("diverged") row alone. |
-| **Canonical** (PostHog contributors) | Edit disk under `products/signals/skills/signals-scout-*/`, lint/build, open a PR. | Improving a scout for _every_ enrolled project. `lazy_seed` mirrors it onto all enrolled teams on the next tick. |
+| Path | Mechanism | Use when |
+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
+| **Per-team** (the common user path) | Prepare a new runnable scout via `posthog:scout-create-prepare`, show its confirmation message, wait for the user to type `confirm`, then call `posthog:scout-create-execute`; edit its prompt or files later via `posthog:skill-update` / `-file-create`, and tune its runtime config via `posthog:scout-config-update`. | Customizing for one project. The harness globs the row in on the next tick; canonical sync leaves your edited ("diverged") row alone. |
+| **Canonical** (PostHog contributors) | Edit disk under `products/signals/skills/signals-scout-*/`, lint/build, open a PR. | Improving a scout for _every_ enrolled project. `lazy_seed` mirrors it onto all enrolled teams on the next tick. |
**Adapting-in-place tradeoff:** editing a canonical scout's row for your team marks it **diverged** — you stop receiving upstream improvements to that scout.
If you only need an _additional_ behavior, prefer authoring a **new, differently-named** scout (`signals-scout-<your-scope>`) and leaving the canonical one intact.
@@ -98,8 +98,9 @@ Name it explicitly near the top of the body so every run anchors on it.
## Run posture (config)
A scout's schedule and emit behavior live on its `SignalScoutConfig`, separate from the skill body.
-For a **brand-new scout**, register the config immediately after creating the skill with `posthog:scout-config-create {"skill_name": "signals-scout-<scope>", ...}`, setting any of the fields below in the same call — including creating it disabled or in dry-run **before it ever runs**.
-(It's an upsert: if the coordinator already auto-registered the row, your fields are applied to it.)
+For a **brand-new scout**, pass these settings in the nested `config` object of the `posthog:scout-create-prepare` call, including creating it disabled or in dry-run **before it ever runs**.
+Show the returned confirmation message, wait for the user to type `confirm`, then call `posthog:scout-create-execute` with the returned `confirmation_hash` and that literal confirmation.
+The endpoint creates the skill and config atomically, always opts the scout into the report channel, and safely re-applies config fields when the same definition is retried.
Otherwise the coordinator auto-registers an enabled config on the default every-24-hours schedule on its next tick (up to ~30 min).
For an **existing scout**, tune with `posthog:scout-config-update` (find the `id` via `-config-list`):
@@ -163,7 +164,7 @@ The standard loop is **dogfood → run once ready → inspect**:
1. Dogfood the discriminator + explore patterns yourself against the live project (above).
Refine the body until the logic holds on real data — this is the cheap, iterable part.
-2. Author the scout and register its config (`-config-create`, the default `emit=true`), then spend one `-run-now` to watch the whole scout execute end-to-end.
+2. Create the scout and its config together via `posthog:scout-create-prepare` → `-execute` (schedule and the default `emit=true` go in the nested `config`), then spend one `-run-now` to watch the whole scout execute end-to-end.
Leave `run_interval_minutes` at a sustainable value — you no longer need a short interval to force an early run.
3. After the run finishes, read what it did: `posthog:inbox-reports-list` (the reports it actually wrote), `posthog:scout-runs-list` (run summaries), `-runs-retrieve` (full reasoning for one run), and `-scratchpad-search` (the durable memory it wrote).
4. If it needs work, go back to dogfooding the queries by hand for the iteration — only spend another `-run-now` once you've batched a meaningful change worth a fresh end-to-end run.
@@ -176,7 +177,7 @@ Treat suggestions as input, not instructions — the owner decides.
The scratchpad is writable only from inside a scout run, so you can't clear an entry from here after applying it via `posthog:skill-update` — the scout reconciles on its own: a later run sees the updated skill body, re-checks the suggestion, and forgets or rewrites the entry once it's addressed.
(Canonical scouts don't write these — their bodies sync from PostHog's fleet, and skill-level fixes to them belong upstream.)
-**Want to be extra careful?** Set `emit=false` to dry-run first — create the config with `emit=false` via `-config-create`, then trigger it with `-run-now`: it runs and logs what it _would_ have written (visible via `-runs-list` / `-runs-retrieve`) without writing to the inbox.
+**Want to be extra careful?** Set `emit=false` to dry-run first — pass `emit=false` in the nested `config` at `scout-create-prepare` time (or flip it later with `-config-update`), then trigger it with `-run-now`: it runs and logs what it _would_ have written (visible via `-runs-list` / `-runs-retrieve`) without writing to the inbox.
Inspect, refine, then flip `emit=true` and run it again.
Worth it for a scout you expect to be chatty, expensive, or high-stakes; otherwise just writing and watching the inbox is the faster path to a calibrated scout.
diff --git a/products/signals/skills/authoring-scouts/references/lifecycle-and-testing.md b/products/signals/skills/authoring-scouts/references/lifecycle-and-testing.md
index f377377a9690..fbb82a1cee6f 100644
--- a/products/signals/skills/authoring-scouts/references/lifecycle-and-testing.md
+++ b/products/signals/skills/authoring-scouts/references/lifecycle-and-testing.md
@@ -9,7 +9,9 @@ How scouts get discovered, scheduled, and dispatched; the two distribution paths
No registration step.
- **Config.** Each scout has one `SignalScoutConfig` per `(project, skill_name)` carrying `run_interval_minutes` (default 1440), `enabled`, `emit`, and a `last_run_at` stamp.
A config is **auto-registered** the first time the coordinator sees a `signals-scout-*` skill without one — authoring the skill is enough to get a scout.
- To configure a fresh scout immediately (instead of waiting for the tick), register the config yourself with `posthog:scout-config-create`, setting the schedule / emit posture in the same call; until one of those happens, the scout has no config row and won't show in `-config-list`.
+ Prepare a fresh per-team scout and its config together with `posthog:scout-create-prepare`; the nested `config` object sets its schedule, emit posture, and destinations before it can run.
+ Show the returned confirmation message, wait for the user to type `confirm`, then call `posthog:scout-create-execute` with the returned `confirmation_hash` and that literal confirmation.
+ The lower-level `posthog:scout-config-create` remains available when a skill already exists without a config.
Config responses also carry the scout's `description`, read live from the skill's frontmatter — not a config field you set.
- **Coordinator.** A periodic Temporal workflow ticks (~every 30 min).
Each tick it bounds candidates to projects enrolled via the `signals-scout` feature-flag allowlist, then dispatches every **enabled** scout whose schedule is **due** (`last_run_at is None`, or `now - last_run_at ≥ run_interval_minutes`), most-overdue first, capped per tick.
@@ -21,7 +23,7 @@ How scouts get discovered, scheduled, and dispatched; the two distribution paths
Pausing a scout = `enabled=false`.
Slowing it = a larger `run_interval_minutes`.
Dry-running it = `emit=false`.
-All three via `posthog:scout-config-update` (get the `id` from `-config-list`), or set at creation time via `-config-create`.
+All three via `posthog:scout-config-update` (get the `id` from `-config-list`), or set at creation time in the nested `config` object passed to `posthog:scout-create-prepare`.
## Path A — per-team (skills store)
@@ -35,12 +37,11 @@ posthog:skill-list {"search": "signals-scout"}
# Read a canonical scout to use as a template
posthog:skill-get {"skill_name": "signals-scout-error-tracking"}
-# New scout from scratch — always include the report-channel allowed_tools
-posthog:skill-create {"name": "signals-scout-<scope>", "description": "...", "body": "...", "allowed_tools": ["emit_report", "edit_report"], "compatibility": "...", "metadata": {"owner_team": "<team>", "scope": "<scope>"}}
+# New scout from scratch: prepare the complete definition and config.
+posthog:scout-create-prepare {"name": "signals-scout-<scope>", "description": "...", "body": "...", "config": {"run_interval_minutes": 120}}
-# Register its config immediately with the schedule you want (otherwise the coordinator
-# auto-registers the default every-24-hours schedule on its next tick)
-posthog:scout-config-create {"skill_name": "signals-scout-<scope>", "run_interval_minutes": 120}
+# Show the returned message and wait for the user to type `confirm`, then execute.
+posthog:scout-create-execute {"confirmation_hash": "<returned-hash>", "confirmation": "confirm"}
# Adapt an existing per-team scout — use the SMALLEST primitive (find/replace, not full-body)
posthog:skill-get {"skill_name": "signals-scout-<scope>"} # get current version first
@@ -95,7 +96,7 @@ There's no free test run, and it's slow (async, one run per call): firing the sa
The loop is **dogfood → run once ready → inspect**:
1. Dogfood the discriminator + explore patterns yourself against the live project (above), refining the body until the logic holds — the cheap, iterable part.
-2. Author the scout and register its config (`-config-create`, default `emit=true`), leaving `run_interval_minutes` at a sustainable value — no short-interval trick needed.
+2. Create the scout and its config together via `posthog:scout-create-prepare` → `-execute` (the default `emit=true` goes in the nested `config`), leaving `run_interval_minutes` at a sustainable value — no short-interval trick needed.
Then spend one `-run-now` to watch the whole scout execute end-to-end, and inspect once it finishes:
- `posthog:inbox-reports-list` — the reports it actually wrote.
- `posthog:scout-runs-list` — run summaries.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 3a61506dab60..526a5b8b2ad9 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -7886,6 +7886,34 @@
"readOnlyHint": false
}
},
+ "scout-create-execute": {
+ "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Create a scout (execute)",
+ "title": "Create a scout (execute)",
+ "required_scopes": ["llm_skill:write", "signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-create-prepare": {
+ "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Create a scout (prepare)",
+ "title": "Create a scout (prepare)",
+ "required_scopes": ["llm_skill:write", "signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-edit-report": {
"description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, and/or set its `suggested_reviewers`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. NOT idempotent — a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c438c811c813..d8195bae3f15 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8435,6 +8435,34 @@
"readOnlyHint": false
}
},
+ "scout-create-execute": {
+ "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Create a scout (execute)",
+ "title": "Create a scout (execute)",
+ "required_scopes": ["llm_skill:write", "signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-create-prepare": {
+ "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Create a scout (prepare)",
+ "title": "Create a scout (prepare)",
+ "required_scopes": ["llm_skill:write", "signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-edit-report": {
"description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, and/or set its `suggested_reviewers`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. NOT idempotent — a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2493e0367eea..f55ec07d84cb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -60881,11 +60881,35 @@ export namespace Schemas {
* registered the row, the provided tunables are applied to it instead.
*/
export interface SignalScoutConfigCreate {
+ /** Whether this scout runs on its schedule. Defaults to true. */
+ enabled?: boolean;
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
+ emit?: boolean;
+ /**
+ * Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).
+ * @minimum 30
+ * @maximum 43200
+ */
+ run_interval_minutes?: number;
+ /** Destinations that receive each finding or report this scout emits. Empty by default. */
+ output_destinations?: SignalScoutOutputDestinations;
+ /**
+ * Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart.
+ * @maxLength 100
+ * @nullable
+ */
+ run_cron_schedule?: string | null;
/**
* The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.
* @maxLength 200
*/
skill_name: string;
+ }
+
+ /**
+ * Schedule, enablement, and delivery options accepted while creating a scout.
+ */
+ export interface SignalScoutConfigOptions {
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean;
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -60906,6 +60930,44 @@ export namespace Schemas {
run_cron_schedule?: string | null;
}
+ /**
+ * Create a runnable custom scout and its config in one atomic request.
+ */
+ export interface SignalScoutCreate {
+ /**
+ * Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, numbers, and hyphens.
+ * @maxLength 64
+ */
+ name: string;
+ /**
+ * Short description of the signal or behavior this scout investigates.
+ * @maxLength 4096
+ */
+ description: string;
+ /** Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here. */
+ body: string;
+ /** Optional reference files bundled with the scout prompt. */
+ files?: LLMSkillFileInput[];
+ /** Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination. */
+ config?: SignalScoutConfigOptions;
+ }
+
+ export interface SignalScoutSkillSummary {
+ readonly id: string;
+ readonly name: string;
+ readonly description: string;
+ readonly version: number;
+ /** Server-managed report tools granted to this scout. */
+ readonly allowed_tools: readonly string[];
+ }
+
+ export interface SignalScoutCreateResponse {
+ /** True when this request created the missing scout skill or config; false when both already existed. */
+ created: boolean;
+ skill: SignalScoutSkillSummary;
+ config: SignalScoutConfig;
+ }
+
/**
* One finding a scout run emitted to the inbox — the persisted, queryable record of
* *what* the run surfaced, returned by `scout-runs-emissions-list`. The emitted text
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 0a1270fc3942..7d9ec027b7cf 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 38 enabled ops
+ * PostHog API - MCP 39 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -386,6 +386,132 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Create a `signals-scout-*` skill and its runnable config atomically. The skill always receives the report-channel tools. The optional config controls schedule, enablement, dry-run posture, and typed destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields; reusing its name for a different definition returns 409.
+ * @summary Create a scout
+ */
+export const SignalsScoutCreateParams = /* @__PURE__ */ 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 signalsScoutCreateBodyNameMax = 64
+
+export const signalsScoutCreateBodyDescriptionMax = 4096
+
+export const signalsScoutCreateBodyFilesItemPathMax = 500
+
+export const signalsScoutCreateBodyFilesItemContentTypeDefault = `text/plain`
+export const signalsScoutCreateBodyFilesItemContentTypeMax = 100
+
+export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30
+export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
+
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255
+
+export const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100
+
+export const SignalsScoutCreateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(signalsScoutCreateBodyNameMax)
+ .describe(
+ 'Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, numbers, and hyphens.'
+ ),
+ description: zod
+ .string()
+ .max(signalsScoutCreateBodyDescriptionMax)
+ .describe('Short description of the signal or behavior this scout investigates.'),
+ body: zod
+ .string()
+ .describe(
+ 'Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here.'
+ ),
+ files: zod
+ .array(
+ zod.object({
+ path: zod
+ .string()
+ .max(signalsScoutCreateBodyFilesItemPathMax)
+ .describe(
+ "File path relative to skill root, e.g. 'scripts\/setup.sh' or 'references\/guide.md'."
+ ),
+ content: zod.string().describe('Text content of the file.'),
+ content_type: zod
+ .string()
+ .max(signalsScoutCreateBodyFilesItemContentTypeMax)
+ .default(signalsScoutCreateBodyFilesItemContentTypeDefault)
+ .describe('MIME type of the file content.'),
+ })
+ )
+ .optional()
+ .describe('Optional reference files bundled with the scout prompt.'),
+ config: zod
+ .object({
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether this scout runs on its schedule. Defaults to true.'),
+ emit: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutCreateBodyConfigOneRunIntervalMinutesMin)
+ .max(signalsScoutCreateBodyConfigOneRunIntervalMinutesMax)
+ .optional()
+ .describe('Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).'),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe('Destinations that receive each finding or report this scout emits. Empty by default.'),
+ run_cron_schedule: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOneRunCronScheduleMax)
+ .nullish()
+ .describe(
+ "Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."
+ ),
+ })
+ .describe('Schedule, enablement, and delivery options accepted while creating a scout.')
+ .optional()
+ .describe(
+ 'Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination.'
+ ),
+ })
+ .describe('Create a runnable custom scout and its config in one atomic request.')
+
/**
* List the per-(team, skill) scout configs for this project. Each row includes its schedule (rolling `run_interval_minutes`, or a project-local `run_cron_schedule` when set), `enabled`, and `emit` posture. A freshly authored scout skill appears here once its config is registered, either explicitly via create or by the coordinator's next tick.
* @summary List scout configs
@@ -410,8 +536,6 @@ export const SignalsScoutConfigCreateParams = /* @__PURE__ */ zod.object({
),
})
-export const signalsScoutConfigCreateBodySkillNameMax = 200
-
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
@@ -419,14 +543,10 @@ export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
+export const signalsScoutConfigCreateBodySkillNameMax = 200
+
export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.object({
- skill_name: zod
- .string()
- .max(signalsScoutConfigCreateBodySkillNameMax)
- .describe(
- 'The `signals-scout-\*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.'
- ),
enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),
emit: zod
.boolean()
@@ -475,6 +595,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.describe(
"Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."
),
+ skill_name: zod
+ .string()
+ .max(signalsScoutConfigCreateBodySkillNameMax)
+ .describe(
+ 'The `signals-scout-\*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.'
+ ),
})
.describe(
'Request body for registering a scout config without waiting for the coordinator tick.\n\nUpsert keyed on `skill_name`: if the coordinator (or a concurrent caller) already\nregistered the row, the provided tunables are applied to it instead.'
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 3cb643d1070c..91d28df1f609 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -23,6 +23,7 @@ import {
SignalsScoutConfigRunParams,
SignalsScoutConfigUpdateBody,
SignalsScoutConfigUpdateParams,
+ SignalsScoutCreateBody,
SignalsScoutEditReportBody,
SignalsScoutEditReportParams,
SignalsScoutEmitReportBody,
@@ -50,6 +51,12 @@ import {
SignalsSourceConfigsUpdateBody,
SignalsSourceConfigsUpdateParams,
} from '@/generated/signals/api'
+import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'
+import {
+ executeConfirmedAction,
+ prepareConfirmedAction,
+ type PrepareConfirmedActionResult,
+} from '@/tools/confirmed-action-runtime'
import {
withPostHogUrl,
withAgentNote,
@@ -506,9 +513,6 @@ const scoutConfigCreate = (): ToolBase<typeof ScoutConfigCreateSchema, Schemas.S
handler: async (context: Context, params: z.infer<typeof ScoutConfigCreateSchema>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
- if (params.skill_name !== undefined) {
- body['skill_name'] = params.skill_name
- }
if (params.enabled !== undefined) {
body['enabled'] = params.enabled
}
@@ -524,6 +528,9 @@ const scoutConfigCreate = (): ToolBase<typeof ScoutConfigCreateSchema, Schemas.S
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
+ if (params.skill_name !== undefined) {
+ body['skill_name'] = params.skill_name
+ }
const result = await context.api.request<Schemas.SignalScoutConfig>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/`,
@@ -614,6 +621,76 @@ const scoutConfigUpdate = (): ToolBase<typeof ScoutConfigUpdateSchema, WithPostH
},
})
+const ScoutCreateSchema = SignalsScoutCreateBody
+
+const ScoutCreateSchemaExecute = z.strictObject({
+ confirmation_hash: z
+ .string()
+ .describe('The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.'),
+ confirmation: z.string().describe('The literal string "confirm", typed by the user in chat. Required to proceed.'),
+})
+
+const scoutCreatePrepare = (): ToolBase<typeof ScoutCreateSchema, PrepareConfirmedActionResult> => ({
+ name: 'scout-create-prepare',
+ schema: ScoutCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof ScoutCreateSchema>) => {
+ const __runtime = getConfirmedActionRuntime()
+ const __scopeProjectId = await context.stateManager.getProjectId()
+ return await prepareConfirmedAction(context, {
+ args: params,
+ purpose: 'scout-create',
+ actionLabel: 'create scout',
+ messageTemplate:
+ "About to create scout '{name}', a persistent automation that can run unattended on its configured schedule and write reports to the inbox when enabled with emit on. Reply 'confirm' to create it.\n",
+ codec: __runtime.codec,
+ boundScope: { projectId: String(__scopeProjectId) },
+ })
+ },
+})
+
+const scoutCreateExecute = (): ToolBase<typeof ScoutCreateSchemaExecute, Schemas.SignalScoutCreateResponse> => ({
+ name: 'scout-create-execute',
+ schema: ScoutCreateSchemaExecute,
+ handler: async (context: Context, confirmationParams: z.infer<typeof ScoutCreateSchemaExecute>) => {
+ const __runtime = getConfirmedActionRuntime()
+ const __scopeProjectId = await context.stateManager.getProjectId()
+ const __guard = await executeConfirmedAction<z.infer<typeof ScoutCreateSchema>>(context, {
+ incomingArgs: confirmationParams,
+ purpose: 'scout-create',
+ codec: __runtime.codec,
+ ledger: __runtime.ledger,
+ expectedScope: { projectId: String(__scopeProjectId) },
+ })
+ if (!__guard.ok) {
+ return __guard.result as never
+ }
+ const params = __guard.verifiedArgs
+ const projectId = __scopeProjectId
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.body !== undefined) {
+ body['body'] = params.body
+ }
+ if (params.files !== undefined) {
+ body['files'] = params.files
+ }
+ if (params.config !== undefined) {
+ body['config'] = params.config
+ }
+ const result = await context.api.request<Schemas.SignalScoutCreateResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/`,
+ body,
+ })
+ return result
+ },
+})
+
const ScoutEditReportSchema = SignalsScoutEditReportParams.omit({ project_id: true }).extend(
SignalsScoutEditReportBody.shape
)
@@ -1065,9 +1142,6 @@ const signalsScoutConfigCreate = (): ToolBase<typeof SignalsScoutConfigCreateSch
handler: async (context: Context, params: z.infer<typeof SignalsScoutConfigCreateSchema>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
- if (params.skill_name !== undefined) {
- body['skill_name'] = params.skill_name
- }
if (params.enabled !== undefined) {
body['enabled'] = params.enabled
}
@@ -1083,6 +1157,9 @@ const signalsScoutConfigCreate = (): ToolBase<typeof SignalsScoutConfigCreateSch
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
+ if (params.skill_name !== undefined) {
+ body['skill_name'] = params.skill_name
+ }
const result = await context.api.request<Schemas.SignalScoutConfig>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/`,
@@ -1573,6 +1650,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'scout-config-list': scoutConfigList,
'scout-config-sync': scoutConfigSync,
'scout-config-update': scoutConfigUpdate,
+ 'scout-create-prepare': scoutCreatePrepare,
+ 'scout-create-execute': scoutCreateExecute,
'scout-edit-report': scoutEditReport,
'scout-emit-report': scoutEmitReport,
'scout-emit-signal': scoutEmitSignal,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-execute.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-execute.json
new file mode 100644
index 000000000000..f9e863b2ae53
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-execute.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
+ "properties": {
+ "confirmation": {
+ "description": "The literal string \"confirm\", typed by the user in chat. Required to proceed.",
+ "type": "string"
+ },
+ "confirmation_hash": {
+ "description": "The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.",
+ "type": "string"
+ }
+ },
+ "required": ["confirmation_hash", "confirmation"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json
new file mode 100644
index 000000000000..6d0d6d7a4f15
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json
@@ -0,0 +1,116 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "description": "Create a runnable custom scout and its config in one atomic request.",
+ "properties": {
+ "body": {
+ "description": "Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here.",
+ "type": "string"
+ },
+ "config": {
+ "description": "Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination.",
+ "properties": {
+ "emit": {
+ "description": "Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true.",
+ "type": "boolean"
+ },
+ "enabled": {
+ "description": "Whether this scout runs on its schedule. Defaults to true.",
+ "type": "boolean"
+ },
+ "output_destinations": {
+ "description": "Destinations that receive each finding or report this scout emits. Empty by default.",
+ "properties": {
+ "slack": {
+ "anyOf": [
+ {
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ },
+ "integration_id": {
+ "description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["integration_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery."
+ }
+ },
+ "type": "object"
+ },
+ "run_cron_schedule": {
+ "anyOf": [
+ {
+ "maxLength": 100,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."
+ },
+ "run_interval_minutes": {
+ "description": "Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).",
+ "maximum": 43200,
+ "minimum": 30,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "description": {
+ "description": "Short description of the signal or behavior this scout investigates.",
+ "maxLength": 4096,
+ "type": "string"
+ },
+ "files": {
+ "description": "Optional reference files bundled with the scout prompt.",
+ "items": {
+ "properties": {
+ "content": {
+ "description": "Text content of the file.",
+ "type": "string"
+ },
+ "content_type": {
+ "default": "text/plain",
+ "description": "MIME type of the file content.",
+ "maxLength": 100,
+ "type": "string"
+ },
+ "path": {
+ "description": "File path relative to skill root, e.g. 'scripts/setup.sh' or 'references/guide.md'.",
+ "maxLength": 500,
+ "type": "string"
+ }
+ },
+ "required": ["path", "content"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "name": {
+ "description": "Unique scout name. Must start with `signals-scout-` and contain only lowercase letters, numbers, and hyphens.",
+ "maxLength": 64,
+ "type": "string"
+ }
+ },
+ "required": ["name", "description", "body"],
+ "type": "object"
+}