: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(mcp): data catalog tools with typed-confirm promotion (#69541)
Thiago Salvatore492ad4ae407b
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 18bbd733e0a3..fcf11d329288 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -280,7 +280,7 @@ Product teams own their definitions and control which operations are exposed asFor destructive or security-sensitive tools (account changes, key revocation, bulk deletes),declare `confirmed_action` in the YAML config. The codegen emits two tools instead of one:- `<name>-prepare` – validates the arguments and returns a signed `confirmation_hash` plus a message for the user.- - `<name>-execute` – verifies the hash and the literal word "confirm" typed by the user, then performs the action.+ - `<name>-execute` – accepts only the hash and the literal word "confirm" typed by the user, then performs the signed action.The model calls them in sequence: prepare → surface the message to the user → wait for "confirm" → execute.@@ -303,9 +303,12 @@ Product teams own their definitions and control which operations are exposed as- `message` (required) – prompt text shown to the user. Supports `{paramName}` placeholders interpolated from the validated tool args at runtime.- `action_label` (optional) – short human-readable label for the action (e.g. "delete project"). Surfaced in refusal messages. Defaults to the tool's title.- **Security model:** the prepare step signs the validated args, user identity, tool purpose, a TTL, and a single-use nonce into an HMAC-SHA256 token. The execute step verifies the signature, burns the nonce, and only then runs the original handler with the signed payload. Args the model adds at execute time can't survive into the request.+ **Security model:** the prepare step signs the validated args, user identity, tool purpose, the active project/organization scope, a TTL, and a single-use nonce into an HMAC-SHA256 token. The execute step has a strict confirmation-only schema, verifies the signature, re-checks that the active scope still matches the one signed at prepare time, burns the nonce, and only then runs the original handler with the signed payload. Action args belong only on prepare; extra execute-time fields are rejected, and a confirmation prepared while one project was active can't be replayed against another after `switch-project`.++ The confirmation word is supplied through model-authored tool arguments. This is an instruction-backed workflow guard, not client-attested proof that the human typed the word. API scopes remain the authorization boundary.**Constraints:**+ - Cannot combine `confirmed_action` with `input_schema` – custom input schemas do not use the confirmed-action codegen path yet.- Cannot combine `confirmed_action` with `ui_app` – the codegen doesn't wrap the execute factory with `withUiApp` yet.- Requires the `MCP_SIGNED_STATE_KEY` environment variable (≥32 bytes) on every environment running the MCP Hono server. A missing or short key disables the paradigm at boot (non-`confirmed_action` tools keep working), and `-prepare`/`-execute` calls fail at request time with a message pointing at the env var.diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.tsindex a1169480c326..a8032ecd0153 100644--- a/frontend/src/lib/agentScopes.generated.ts+++ b/frontend/src/lib/agentScopes.generated.ts@@ -26,6 +26,9 @@ export const AGENT_USE_CASE_SCOPES = ['cohort:read','cohort:write','comment:read',+ 'data_catalog:read',+ 'data_catalog:write',+ 'data_catalog_approval:write','dashboard:read','dashboard:write','dashboard_template:read',diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex 3d548c14a1fd..17711971a080 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -16,6 +16,7 @@ from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERRORfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.filters import replace_filters+from posthog.hogql.metadata import get_table_namesfrom posthog.hogql.parser import CacheOrigin, parse_selectfrom posthog.hogql.placeholders import find_placeholders, replace_placeholdersfrom posthog.hogql.query import execute_hogql_query@@ -30,6 +31,8 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom products.warehouse_sources.backend.facade.models import get_direct_external_data_source_for_connection+_INFORMATION_SCHEMA_PREFIX = "system.information_schema."+class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):query: HogQLQuery@@ -51,6 +54,19 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):return Nonereturn last_refresh + staleness_threshold_map[ThresholdMode.LAZY if lazy else ThresholdMode.DEFAULT]["day"]+ def requires_fresh_calculation(self) -> bool:+ # system.information_schema.* mirrors mutable data-catalog state (metric approval, relationship+ # acceptance, source certification). A cached row keeps reporting the pre-change status after a+ # catalog write, so recompute these queries rather than trust the query cache. Cheap to detect:+ # the schema metadata itself is fast to compute. External-connection queries never touch it.+ if self.query.connectionId:+ return False+ try:+ table_names = get_table_names(parse_select(self.query.query))+ except Exception:+ return False+ return any(name.lower().startswith(_INFORMATION_SCHEMA_PREFIX) for name in table_names)+def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:values: Optional[dict[str, ast.Expr]] = ({key: ast.Constant(value=value) for key, value in self.query.values.items()} if self.query.values else Nonediff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex c8eecb71fc33..a41fe281475c 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -1682,6 +1682,18 @@ class QueryRunner(ABC, Generic[Q, R, CR]):self.query_id = query_id or self.query_idself._cache_age_override = cache_age_seconds+ # Some queries read live, mutable state that must never be served stale — e.g. HogQL against+ # system.information_schema.*, which mirrors data-catalog approval/certification status, so a+ # cached row keeps reporting the pre-change value after a catalog write. Such runners force a+ # blocking recompute here so every entry point (SQL editor, insights, PostHog AI, MCP) sees the+ # current state. Async-only and cache-only modes are left as requested — they explicitly opt+ # out of returning a fresh synchronous result.+ if (+ execution_mode not in (ExecutionMode.CALCULATE_ASYNC_ALWAYS, ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)+ and self.requires_fresh_calculation()+ ):+ execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS+# capture_exceptions=False: we capture explicitly at the except boundary below, so benign# user-input query errors (USER_ERROR / cancelled / rate-limited) are returned to the user# as 4xx without also polluting error tracking with server-side exception noise.@@ -2306,6 +2318,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):def _refresh_frequency(self) -> timedelta:return timedelta(minutes=1)+ def requires_fresh_calculation(self) -> bool:+ """Runners whose results reflect live, mutable state that must never be served stale+ override this to force a blocking recompute, bypassing cached results. See+ `HogQLQueryRunner` for the `system.information_schema.*` (data-catalog) case."""+ return False+def apply_variable_overrides(self, variable_overrides: list[HogQLVariable]):"""Irreversibly update self.query with provided variable overrides."""if not hasattr(self.query, "variables") or not self.query.kind == "HogQLQuery" or len(variable_overrides) == 0:diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.pyindex ce794e7398ea..8a10e02694b7 100644--- a/posthog/hogql_queries/test/test_hogql_query_runner.py+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py@@ -143,6 +143,31 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertIsNotNone(response.cache_target_age)self.assertEqual(response.cache_target_age, expected_target_age)+ @parameterized.expand(+ [+ # system.information_schema.* mirrors mutable data-catalog state, so it must never be+ # served from the query cache — recompute every time regardless of the caller's mode.+ ("metrics", "select name, status from system.information_schema.metrics", True),+ ("tables", "select * from system.information_schema.tables", True),+ ("relationships", "select * from system.information_schema.relationships", True),+ ("columns", "select * from system.information_schema.columns", True),+ ("other_system_table", "select id, name from system.insights", False),+ ("events", "select count(event) from events", False),+ ("unparseable", "INVALID SQL SYNTAX", False),+ ]+ )+ def test_requires_fresh_calculation(self, _name: str, query: str, expected: bool):+ runner = self._create_runner(HogQLQuery(query=query))+ self.assertEqual(runner.requires_fresh_calculation(), expected)++ def test_requires_fresh_calculation_false_for_external_connection(self):+ # External-connection queries run against an upstream source, never the ClickHouse catalog,+ # so they keep normal caching even if the text happens to reference information_schema.+ runner = self._create_runner(+ HogQLQuery(query="select * from system.information_schema.metrics", connectionId="conn-123")+ )+ self.assertFalse(runner.requires_fresh_calculation())+def test_variables_in_hog_expression(self):variable = InsightVariable.objects.create(team=self.team, name="Foo", code_name="foo", type="Boolean")variable_id = str(variable.id)diff --git a/products/data_catalog/backend/logic/certifications.py b/products/data_catalog/backend/logic/certifications.pyindex 18f8a03d3ac9..a78316f9d87c 100644--- a/products/data_catalog/backend/logic/certifications.py+++ b/products/data_catalog/backend/logic/certifications.py@@ -60,7 +60,7 @@ def _capture(user: Optional[User], team: Team, event: str, cert: TableCertificatdef _duplicate_target_conflict(certification: TableCertification) -> CatalogConflict:- return CatalogConflict(detail={"error": f"This target is already marked '{certification.status}'."})+ return CatalogConflict(detail=f"This target is already marked '{certification.status}'.")def _resolve_table(team: Team, table_id: str | UUID | None, table_name: str | None) -> DataWarehouseTable:@@ -76,10 +76,8 @@ def _resolve_table(team: Team, table_id: str | UUID | None, table_name: str | Noraise ValidationError({"table_name": f"No table named '{table_name}'."})if len(matches) > 1:raise CatalogConflict(- detail={- "error": f"Multiple tables named '{table_name}'. Pass table_id to disambiguate.",- "candidates": [{"id": str(t.id), "created_at": t.created_at.isoformat()} for t in matches],- }+ detail=f"Multiple tables named '{table_name}'. Pass table_id to disambiguate.",+ extra={"candidates": [{"id": str(t.id), "created_at": t.created_at.isoformat()} for t in matches]},)return matches[0]@@ -98,10 +96,8 @@ def _resolve_saved_query(raise ValidationError({"view_name": f"No view named '{view_name}'."})if len(matches) > 1:raise CatalogConflict(- detail={- "error": f"Multiple views named '{view_name}'. Pass saved_query_id to disambiguate.",- "candidates": [{"id": str(v.id), "created_at": v.created_at.isoformat()} for v in matches],- }+ detail=f"Multiple views named '{view_name}'. Pass saved_query_id to disambiguate.",+ extra={"candidates": [{"id": str(v.id), "created_at": v.created_at.isoformat()} for v in matches]},)return matches[0]diff --git a/products/data_catalog/backend/logic/exceptions.py b/products/data_catalog/backend/logic/exceptions.pyindex c1ded9c761e2..3e1007b3bcbc 100644--- a/products/data_catalog/backend/logic/exceptions.py+++ b/products/data_catalog/backend/logic/exceptions.py@@ -30,8 +30,18 @@ class MetricHasNoDefinition(APIException):class CatalogConflict(APIException):- """A 409 for catalog conflicts (duplicate certification, ambiguous table name, existing proposal)."""+ """A 409 for catalog conflicts (duplicate certification, ambiguous table name, existing proposal).++ ``detail`` must stay a plain string: the exceptions_hog handler cannot render dict details+ (it 500s). Machine-readable payloads (candidate ids, the existing proposal id) go in+ ``extra``, which the handler attaches to the response verbatim.+ """status_code = status.HTTP_409_CONFLICTdefault_detail = "This catalog entry conflicts with an existing one."default_code = "catalog_conflict"++ def __init__(self, detail: str | None = None, extra: dict | None = None) -> None:+ super().__init__(detail=detail)+ if extra is not None:+ self.extra = extradiff --git a/products/data_catalog/backend/logic/execution.py b/products/data_catalog/backend/logic/execution.pyindex 0587c34e0cf2..9eaad85bdb7d 100644--- a/products/data_catalog/backend/logic/execution.py+++ b/products/data_catalog/backend/logic/execution.py@@ -91,9 +91,8 @@ def run_metric(except (ExposedHogQLError, ExposedCHQueryError) as e:raise ValidationError({- "field": "definition",- "error": f"This metric could not run: {e}",- "hint": "A table or column it references may no longer exist. Check system.information_schema.tables.",+ "definition": f"This metric could not run: {e} "+ "A table or column it references may no longer exist. Check system.information_schema.tables."})except ConcurrencyLimitExceeded:@@ -111,9 +110,8 @@ def run_metric(# run that produced no results must not read as a success.raise ValidationError({- "field": "definition",- "error": f"This metric could not run: {payload['error']}",- "hint": "The definition (or a date/interval override) does not form a valid query.",+ "definition": f"This metric could not run: {payload['error']} "+ "The definition (or a date/interval override) does not form a valid query."})@@ -146,9 +144,8 @@ def _apply_date_params(query: dict, date_from: Optional[str], date_to: Optional[field = "date_from" if date_from is not None else ("date_to" if date_to is not None else "interval")raise ValidationError({- "field": field,- "error": "This metric's dates are fixed in its SQL and cannot be overridden at run time.",- "hint": "Report the definition's own window, or ask for a parameterized metric.",+ field: "This metric's dates are fixed in its SQL and cannot be overridden at run time. "+ "Report the definition's own window, or ask for a parameterized metric."})date_range = dict(query.get("dateRange") or {})diff --git a/products/data_catalog/backend/logic/relationships.py b/products/data_catalog/backend/logic/relationships.pyindex 07117b26b8a4..c288d816ccf9 100644--- a/products/data_catalog/backend/logic/relationships.py+++ b/products/data_catalog/backend/logic/relationships.py@@ -106,10 +106,8 @@ def propose_relationship(existing = RelationshipProposal.objects.for_team(team.id).filter(undirected_fingerprint=fingerprint).first()if existing is not None:raise CatalogConflict(- detail={- "error": f"A proposal for this join pair already exists (status: {existing.status}).",- "proposal_id": str(existing.id),- }+ detail=f"A proposal for this join pair already exists (status: {existing.status}).",+ extra={"proposal_id": str(existing.id)},)try:@@ -132,10 +130,8 @@ def propose_relationship(# race the logic check alone cannot).existing = RelationshipProposal.objects.for_team(team.id).filter(undirected_fingerprint=fingerprint).first()raise CatalogConflict(- detail={- "error": "A proposal for this join pair already exists.",- "proposal_id": str(existing.id) if existing else None,- }+ detail="A proposal for this join pair already exists.",+ extra={"proposal_id": str(existing.id) if existing else None},)_capture(user, team, "data catalog relationship proposed", proposal)diff --git a/products/data_catalog/backend/logic/validation.py b/products/data_catalog/backend/logic/validation.pyindex 63a26cf550b2..728d4ae9734c 100644--- a/products/data_catalog/backend/logic/validation.py+++ b/products/data_catalog/backend/logic/validation.py@@ -57,13 +57,16 @@ class _TableReferenceCollector(TraversingVisitor):def _fail(error: str, hint: str) -> NoReturn:- raise ValidationError({"field": "definition", "error": error, "hint": hint})+ # Keyed by the offending field with a single string message: the exceptions_hog handler+ # renders that as attr="definition" + the full text; any richer dict shape strips the+ # message (or 500s) on its way through the HTTP envelope.+ raise ValidationError({"definition": f"{error} {hint}"})def validate_metric_definition(definition: dict, team: Team, user: Optional[User] = None) -> tuple[dict, list[str]]:"""Validate a metric definition and return ``(canonical_definition, referenced_table_names)``.- Raises :class:`ValidationError` with a structured ``{field, error, hint}`` body on any problem.+ Raises :class:`ValidationError` keyed by the ``definition`` field on any problem."""if not isinstance(definition, dict) or not definition.get("kind"):_fail("A definition must be a query object with a 'kind'.", "Provide a HogQLQuery, TrendsQuery, or event node.")diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.pyindex 26b16f12c1be..d4772ada4a37 100644--- a/products/data_catalog/backend/presentation/serializers.py+++ b/products/data_catalog/backend/presentation/serializers.py@@ -161,7 +161,11 @@ class MetricSerializer(serializers.ModelSerializer):"description": {"help_text": "What the metric means and how to interpret it."},"unit": {"help_text": "Unit of the result, e.g. usd, percent, cents."},"ai_model": {"help_text": "Model that generated the metric, if AI-authored."},- "confidence": {"help_text": "AI author's confidence in the proposal, 0-1."},+ "confidence": {+ "help_text": "AI author's confidence in the proposal, 0-1.",+ "min_value": 0.0,+ "max_value": 1.0,+ },"reasoning": {"help_text": "AI author's reasoning, surfaced as review context."},}diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.pyindex bcdba9897922..0ed932810aa6 100644--- a/products/data_catalog/backend/tests/test_api.py+++ b/products/data_catalog/backend/tests/test_api.py@@ -19,7 +19,11 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, HogQLQueryThrottlefrom products.data_catalog.backend.facade.enums import MetricStatusfrom products.data_catalog.backend.logic.metrics import upsert_metricfrom products.data_catalog.backend.models import Metric-from products.data_catalog.backend.presentation.serializers import MetricRunQuerySerializer, MetricRunRequestSerializer+from products.data_catalog.backend.presentation.serializers import (+ MetricRunQuerySerializer,+ MetricRunRequestSerializer,+ MetricSerializer,+)from products.product_analytics.backend.models.insight import Insightfrom ee.models.rbac.access_control import AccessControl@@ -91,6 +95,10 @@ class TestMetricAPI(APIBaseTest):format="json",)assert response.status_code == status.HTTP_400_BAD_REQUEST+ # The agent-facing envelope must carry the actual problem, not just the field name.+ body = response.json()+ assert body["attr"] == "definition"+ assert "Unsupported definition kind" in body["detail"]def test_markdown_definition_accepted(self) -> None:response = self.client.post(@@ -252,6 +260,9 @@ class TestMetricLifecycleAPI(APIBaseTest):upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)response = self.client.post(f"{self.url}mrr/run/", {"date_from": "-7d"}, format="json")assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ assert body["attr"] == "date_from"+ assert "fixed in its SQL" in body["detail"]def test_run_requires_query_read_scope(self) -> None:upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)@@ -401,3 +412,10 @@ class TestMetricRunInputValidation(SimpleTestCase):assert serializer.is_valid() is validif not valid:assert "refresh" in serializer.errors++ @parameterized.expand([(0.0, True), (1.0, True), (-0.5, False), (1.5, False)])+ def test_confidence_bounds(self, value: float, valid: bool) -> None:+ serializer = MetricSerializer(data={"name": "mrr", "description": "d", "confidence": value})+ assert serializer.is_valid() is valid, serializer.errors+ if not valid:+ assert "confidence" in serializer.errorsdiff --git a/products/data_catalog/backend/tests/test_certifications.py b/products/data_catalog/backend/tests/test_certifications.pyindex b5e772be9009..093ba69e7c92 100644--- a/products/data_catalog/backend/tests/test_certifications.py+++ b/products/data_catalog/backend/tests/test_certifications.py@@ -239,6 +239,28 @@ class TestCertificationAPI(APIBaseTest):assert certified.status_code == status.HTTP_200_OKassert certified.json()["status"] == CertificationStatus.CERTIFIED+ def test_ambiguous_table_name_returns_409_with_candidates(self) -> None:+ # The conflict must render through the HTTP exception handler — a shape it can't+ # serialize turns every ambiguous propose into a 500 and hides the candidate ids+ # the caller needs to disambiguate.+ first = _table(self.team, name="dupe")+ second = _table(self.team, name="dupe")+ response = self.client.post(self.url, {"table_name": "dupe"}, format="json")+ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ body = response.json()+ assert body["code"] == "catalog_conflict"+ assert "Multiple tables named 'dupe'" in body["detail"]+ assert {c["id"] for c in body["extra"]["candidates"]} == {str(first.id), str(second.id)}++ def test_duplicate_target_returns_409(self) -> None:+ table = _table(self.team)+ assert self.client.post(self.url, {"table_id": str(table.id)}, format="json").status_code == 201+ response = self.client.post(self.url, {"table_id": str(table.id)}, format="json")+ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ body = response.json()+ assert body["code"] == "catalog_conflict"+ assert "already marked" in body["detail"]+def test_certify_requires_approval_scope(self) -> None:table = _table(self.team)cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))diff --git a/products/data_catalog/backend/tests/test_execution.py b/products/data_catalog/backend/tests/test_execution.pyindex ac34b4d1bd61..79d4e77bd140 100644--- a/products/data_catalog/backend/tests/test_execution.py+++ b/products/data_catalog/backend/tests/test_execution.py@@ -172,7 +172,7 @@ class TestMetricRunPreparation(APIBaseTest):with self.assertRaises(ValidationError) as ctx:prepare_execution_query(_HOGQL, **params)detail = cast(dict, ctx.exception.detail)- assert str(detail["field"]) == expected_field+ assert expected_field in detailclass TestMetricRunAttribution(APIBaseTest):diff --git a/products/data_catalog/backend/tests/test_relationships.py b/products/data_catalog/backend/tests/test_relationships.pyindex 39e3fe85a88f..c89e16718c8c 100644--- a/products/data_catalog/backend/tests/test_relationships.py+++ b/products/data_catalog/backend/tests/test_relationships.py@@ -259,6 +259,25 @@ class TestRelationshipAPI(APIBaseTest):assert response.status_code == status.HTTP_201_CREATED, response.json()assert response.json()["status"] == RelationshipStatus.PROPOSED+ def test_duplicate_pair_returns_409_with_proposal_id(self) -> None:+ # The dedupe conflict must render through the HTTP exception handler and hand back the+ # existing proposal's id — it's what lets an agent link to the proposal instead of retrying.+ first = self.client.post(self.url, _JOIN, format="json")+ assert first.status_code == status.HTTP_201_CREATED, first.json()+ reversed_join = {+ **_JOIN,+ "source_table_name": _JOIN["joining_table_name"],+ "source_table_key": _JOIN["joining_table_key"],+ "joining_table_name": _JOIN["source_table_name"],+ "joining_table_key": _JOIN["source_table_key"],+ }+ response = self.client.post(self.url, reversed_join, format="json")+ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ body = response.json()+ assert body["code"] == "catalog_conflict"+ assert "already exists" in body["detail"]+ assert body["extra"]["proposal_id"] == first.json()["id"]+def test_create_proposal_rejects_invalid_confidence(self) -> None:response = self.client.post(self.url, {**_JOIN, "confidence": 1.01}, format="json")assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.tsindex 3306380145ec..51545bdf86a0 100644--- a/products/data_catalog/frontend/generated/api.schemas.ts+++ b/products/data_catalog/frontend/generated/api.schemas.ts@@ -201,6 +201,8 @@ export interface DataCatalogMetricApi {ai_model?: string/*** AI author's confidence in the proposal, 0-1.+ * @minimum 0+ * @maximum 1* @nullable*/confidence?: number | null@@ -296,6 +298,8 @@ export interface PatchedDataCatalogMetricApi {ai_model?: string/*** AI author's confidence in the proposal, 0-1.+ * @minimum 0+ * @maximum 1* @nullable*/confidence?: number | nulldiff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.tsindex f80a46c0e329..1d5021fa1ae3 100644--- a/products/data_catalog/frontend/generated/api.zod.ts+++ b/products/data_catalog/frontend/generated/api.zod.ts@@ -36,6 +36,9 @@ export const dataCatalogMetricsCreateBodySourceInsightShortIdMax = 12export const dataCatalogMetricsCreateBodyAiModelMax = 128+export const dataCatalogMetricsCreateBodyConfidenceMin = 0+export const dataCatalogMetricsCreateBodyConfidenceMax = 1+export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -76,7 +79,12 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({.max(dataCatalogMetricsCreateBodyAiModelMax).optional().describe('Model that generated the metric, if AI-authored.'),- confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ confidence: zod+ .number()+ .min(dataCatalogMetricsCreateBodyConfidenceMin)+ .max(dataCatalogMetricsCreateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the proposal, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})@@ -94,6 +102,9 @@ export const dataCatalogMetricsUpdateBodySourceInsightShortIdMax = 12export const dataCatalogMetricsUpdateBodyAiModelMax = 128+export const dataCatalogMetricsUpdateBodyConfidenceMin = 0+export const dataCatalogMetricsUpdateBodyConfidenceMax = 1+export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -134,7 +145,12 @@ export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({.max(dataCatalogMetricsUpdateBodyAiModelMax).optional().describe('Model that generated the metric, if AI-authored.'),- confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ confidence: zod+ .number()+ .min(dataCatalogMetricsUpdateBodyConfidenceMin)+ .max(dataCatalogMetricsUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the proposal, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})@@ -152,6 +168,9 @@ export const dataCatalogMetricsPartialUpdateBodySourceInsightShortIdMax = 12export const dataCatalogMetricsPartialUpdateBodyAiModelMax = 128+export const dataCatalogMetricsPartialUpdateBodyConfidenceMin = 0+export const dataCatalogMetricsPartialUpdateBodyConfidenceMax = 1+export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -193,7 +212,12 @@ export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({.max(dataCatalogMetricsPartialUpdateBodyAiModelMax).optional().describe('Model that generated the metric, if AI-authored.'),- confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ confidence: zod+ .number()+ .min(dataCatalogMetricsPartialUpdateBodyConfidenceMin)+ .max(dataCatalogMetricsPartialUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the proposal, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})diff --git a/products/data_catalog/mcp/tools.yaml b/products/data_catalog/mcp/tools.yamlnew file mode 100644index 000000000000..2070528e4135--- /dev/null+++ b/products/data_catalog/mcp/tools.yaml@@ -0,0 +1,231 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Data catalog+feature: data_catalog+url_prefix: /data-catalog+ui_apps: {}+tools:+ data-catalog-certification-certify:+ operation: data_catalog_certifications_certify_create+ enabled: true+ scopes:+ - data_catalog_approval:write+ - data_catalog:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Certify a table/view+ description: |+ Mark a table or view as certified (prefer this source). Requires human typed confirmation.+ feature_flag: product-data-catalog+ confirmed_action:+ message: >+ About to mark certification '{id}' as certified (agents should prefer this source). Reply 'confirm' to+ proceed.+ action_label: certify source+ data-catalog-certification-deprecate:+ operation: data_catalog_certifications_deprecate_create+ enabled: true+ scopes:+ - data_catalog_approval:write+ - data_catalog:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Deprecate a table/view+ description: |+ Mark a table or view as deprecated (avoid this source). Requires human typed confirmation.+ feature_flag: product-data-catalog+ confirmed_action:+ message: >+ About to mark certification '{id}' as deprecated (agents should avoid this source). Reply 'confirm' to+ proceed.+ action_label: deprecate source+ data-catalog-certification-propose:+ operation: data_catalog_certifications_create+ enabled: true+ scopes:+ - data_catalog:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Propose a table/view certification+ description: >+ Propose a trust mark on a warehouse table or view. Address the target by id, or by name (an ambiguous name+ returns the candidate ids to pick from).+ feature_flag: product-data-catalog+ data-catalog-certifications-destroy:+ operation: data_catalog_certifications_destroy+ enabled: false+ data-catalog-certifications-list:+ operation: data_catalog_certifications_list+ enabled: false+ data-catalog-certifications-retrieve:+ operation: data_catalog_certifications_retrieve+ enabled: false+ data-catalog-metric-approve:+ operation: data_catalog_metrics_approve_create+ enabled: true+ scopes:+ - data_catalog_approval:write+ - data_catalog:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Approve a catalog metric+ description: >+ Bless a metric as canonical. Blocked while the metric is drifted from its source insight (refresh or unlink+ it first). The MCP workflow requires the user to reply with the literal word 'confirm' before execution.+ feature_flag: product-data-catalog+ confirmed_action:+ message: |+ About to approve metric '{name}' as a canonical, human-vouched metric. Reply 'confirm' to proceed.+ action_label: approve metric+ data-catalog-metric-create:+ operation: data_catalog_metrics_create+ enabled: true+ scopes:+ - data_catalog:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Create or refine a catalog metric+ description: >+ Create a canonical metric, or refine the one already holding this name (upsert on name; always lands+ 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event+ node) that the query runner computes, OR an agent-calculated markdown definition - {"kind":+ "MarkdownDefinition", "markdown": "<numbered steps to calculate the metric>"} - which an agent follows to+ produce the number. Prefer an executable definition when the metric is deterministic; use a markdown+ definition when the calculation needs judgment or multiple steps. Only propose a definition that was+ explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off+ queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed+ metric. There is no list tool: discover existing metrics with execute-sql over+ system.information_schema.metrics.+ exclude_params:+ - created_source+ inject_body:+ created_source: ai_generated+ feature_flag: product-data-catalog+ data-catalog-metric-run:+ operation: data_catalog_metrics_run_create+ enabled: true+ scopes:+ - data_catalog:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Run a catalog metric+ description: >+ Run a metric's definition. For an executable metric, returns the results plus a deep link (posthog_url). For+ an agent-calculated markdown metric, returns the calculation steps in 'instructions' (with 'results' null)+ for you to follow. Prefer running the canonical metric over re-deriving the number yourself. A result is+ canonical only when the response has status 'approved' AND is_drifted false - never present a 'proposed' or+ drifted metric's result as canonical.+ feature_flag: product-data-catalog+ data-catalog-metric-update:+ operation: data_catalog_metrics_partial_update+ enabled: true+ scopes:+ - data_catalog:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update a catalog metric+ description: >+ Update a metric's fields. Editing the definition of an approved metric resets it to 'proposed' (it must be+ re-approved by a human).+ exclude_params:+ - created_source+ inject_body:+ created_source: ai_generated+ feature_flag: product-data-catalog+ data-catalog-metrics-destroy:+ operation: data_catalog_metrics_destroy+ enabled: false+ data-catalog-metrics-list:+ operation: data_catalog_metrics_list+ enabled: false+ data-catalog-metrics-refresh-from-insight-create:+ operation: data_catalog_metrics_refresh_from_insight_create+ enabled: false+ data-catalog-metrics-retrieve:+ operation: data_catalog_metrics_retrieve+ enabled: false+ data-catalog-metrics-update:+ operation: data_catalog_metrics_update+ enabled: false+ data-catalog-relationship-accept:+ operation: data_catalog_relationship_proposals_accept_create+ enabled: true+ scopes:+ - data_catalog_approval:write+ - data_catalog:read+ - query:read+ - warehouse_view:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Accept a relationship proposal+ description: >+ Promote a relationship proposal to a real warehouse join after re-validating and probing it. Requires human+ typed confirmation.+ feature_flag: product-data-catalog+ confirmed_action:+ message: >+ About to accept relationship proposal '{id}', promoting it to a real warehouse join. Reply 'confirm' to+ proceed.+ action_label: accept relationship+ data-catalog-relationship-proposals-list:+ operation: data_catalog_relationship_proposals_list+ enabled: false+ data-catalog-relationship-proposals-retrieve:+ operation: data_catalog_relationship_proposals_retrieve+ enabled: false+ data-catalog-relationship-propose:+ operation: data_catalog_relationship_proposals_create+ enabled: true+ scopes:+ - data_catalog:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Propose a table relationship+ description: >+ Propose a reviewed join between two warehouse tables, with confidence and sampling evidence (match rates,+ sample values). Both tables must exist. Proposals are deduped undirected, so do not propose the reverse of+ an existing pair.+ feature_flag: product-data-catalog+ data-catalog-relationship-reject:+ operation: data_catalog_relationship_proposals_reject_create+ enabled: true+ scopes:+ - data_catalog_approval:write+ - data_catalog:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Reject a relationship proposal+ description: >+ Reject a relationship proposal. Persists forever so the pair is never re-proposed. Requires human typed+ confirmation.+ feature_flag: product-data-catalog+ confirmed_action:+ message: >+ About to reject relationship proposal '{id}'. This permanently suppresses re-proposing the pair. Reply+ 'confirm' to proceed.+ action_label: reject relationshipdiff --git a/services/mcp/definitions/README.md b/services/mcp/definitions/README.mdindex 369e65895620..f7bc187a8a3b 100644--- a/services/mcp/definitions/README.md+++ b/services/mcp/definitions/README.md@@ -190,7 +190,7 @@ to require explicit user confirmation. When this field is present, codegen emitsinstead of one:- `<name>-prepare` — validates args, returns a signed confirmation hash and a message to surface to the user-- `<name>-execute` — verifies the hash plus the literal "confirm" string from the user, then executes the action+- `<name>-execute` — accepts only the hash plus the literal "confirm" string from the user, then executes the signed actionThe model calls them in sequence: prepare → surface message → wait for user to type "confirm" → execute.@@ -216,7 +216,13 @@ tools:| `message` | Yes | Prompt shown to the user. Supports `{paramName}` placeholders interpolated from the validated tool args. || `action_label` | No | Short label for the action (e.g. "delete project"). Defaults to the tool's title. |+The prepare step also signs the active project/organization scope into the hash, and execute refuses if the active scope has changed since prepare — so a confirmation prepared in one project can't be replayed against another after `switch-project`.+Action arguments belong only on the prepare call. The execute schema is strict: it rejects extra action fields and recovers the original validated arguments from the signed hash.++The confirmation word is supplied through model-authored tool arguments. This is an instruction-backed workflow guard, not client-attested proof that the human typed the word. API scopes remain the authorization boundary.+Requirements:- The `MCP_SIGNED_STATE_KEY` environment variable (≥32 bytes) must be set on the MCP Hono server+- Cannot be combined with `input_schema` (codegen limitation)- Cannot be combined with `ui_app` (codegen limitation)diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9fe599ec0277..25354b723eb1 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2257,6 +2257,231 @@"readOnlyHint": false}},+ "data-catalog-certification-certify-execute": {+ "description": "Step 2 of 2 for certify source. 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: Mark a table or view as certified (prefer this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Certify a table/view (execute)",+ "title": "Certify a table/view (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-certify-prepare": {+ "description": "Step 1 of 2 for certify source. 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: Mark a table or view as certified (prefer this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Certify a table/view (prepare)",+ "title": "Certify a table/view (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-deprecate-execute": {+ "description": "Step 2 of 2 for deprecate source. 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: Mark a table or view as deprecated (avoid this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Deprecate a table/view (execute)",+ "title": "Deprecate a table/view (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-deprecate-prepare": {+ "description": "Step 1 of 2 for deprecate source. 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: Mark a table or view as deprecated (avoid this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Deprecate a table/view (prepare)",+ "title": "Deprecate a table/view (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-propose": {+ "description": "Propose a trust mark on a warehouse table or view. Address the target by id, or by name (an ambiguous name returns the candidate ids to pick from).",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Propose a table/view certification",+ "title": "Propose a table/view certification",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-approve-execute": {+ "description": "Step 2 of 2 for approve metric. 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: Bless a metric as canonical. Blocked while the metric is drifted from its source insight (refresh or unlink it first). The MCP workflow requires the user to reply with the literal word 'confirm' before execution.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Approve a catalog metric (execute)",+ "title": "Approve a catalog metric (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-approve-prepare": {+ "description": "Step 1 of 2 for approve metric. 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: Bless a metric as canonical. Blocked while the metric is drifted from its source insight (refresh or unlink it first). The MCP workflow requires the user to reply with the literal word 'confirm' before execution.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Approve a catalog metric (prepare)",+ "title": "Approve a catalog metric (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-create": {+ "description": "Create a canonical metric, or refine the one already holding this name (upsert on name; always lands 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Create or refine a catalog metric",+ "title": "Create or refine a catalog metric",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-run": {+ "description": "Run a metric's definition. For an executable metric, returns the results plus a deep link (posthog_url). For an agent-calculated markdown metric, returns the calculation steps in 'instructions' (with 'results' null) for you to follow. Prefer running the canonical metric over re-deriving the number yourself. A result is canonical only when the response has status 'approved' AND is_drifted false - never present a 'proposed' or drifted metric's result as canonical.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Run a catalog metric",+ "title": "Run a catalog metric",+ "required_scopes": ["data_catalog:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-update": {+ "description": "Update a metric's fields. Editing the definition of an approved metric resets it to 'proposed' (it must be re-approved by a human).",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Update a catalog metric",+ "title": "Update a catalog metric",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-accept-execute": {+ "description": "Step 2 of 2 for accept relationship. 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: Promote a relationship proposal to a real warehouse join after re-validating and probing it. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Accept a relationship proposal (execute)",+ "title": "Accept a relationship proposal (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read", "query:read", "warehouse_view:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-accept-prepare": {+ "description": "Step 1 of 2 for accept relationship. 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: Promote a relationship proposal to a real warehouse join after re-validating and probing it. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Accept a relationship proposal (prepare)",+ "title": "Accept a relationship proposal (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read", "query:read", "warehouse_view:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-propose": {+ "description": "Propose a reviewed join between two warehouse tables, with confidence and sampling evidence (match rates, sample values). Both tables must exist. Proposals are deduped undirected, so do not propose the reverse of an existing pair.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Propose a table relationship",+ "title": "Propose a table relationship",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-reject-execute": {+ "description": "Step 2 of 2 for reject relationship. 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: Reject a relationship proposal. Persists forever so the pair is never re-proposed. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Reject a relationship proposal (execute)",+ "title": "Reject a relationship proposal (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-reject-prepare": {+ "description": "Step 1 of 2 for reject relationship. 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: Reject a relationship proposal. Persists forever so the pair is never re-proposed. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Reject a relationship proposal (prepare)",+ "title": "Reject a relationship proposal (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },"data-warehouse-source-connect-link": {"description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.","category": "Warehouse sources",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 56e052daaa34..a5937e2b9ee8 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2286,6 +2286,231 @@"readOnlyHint": false}},+ "data-catalog-certification-certify-execute": {+ "description": "Step 2 of 2 for certify source. 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: Mark a table or view as certified (prefer this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Certify a table/view (execute)",+ "title": "Certify a table/view (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-certify-prepare": {+ "description": "Step 1 of 2 for certify source. 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: Mark a table or view as certified (prefer this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Certify a table/view (prepare)",+ "title": "Certify a table/view (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-deprecate-execute": {+ "description": "Step 2 of 2 for deprecate source. 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: Mark a table or view as deprecated (avoid this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Deprecate a table/view (execute)",+ "title": "Deprecate a table/view (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-deprecate-prepare": {+ "description": "Step 1 of 2 for deprecate source. 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: Mark a table or view as deprecated (avoid this source). Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Deprecate a table/view (prepare)",+ "title": "Deprecate a table/view (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-certification-propose": {+ "description": "Propose a trust mark on a warehouse table or view. Address the target by id, or by name (an ambiguous name returns the candidate ids to pick from).",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Propose a table/view certification",+ "title": "Propose a table/view certification",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-approve-execute": {+ "description": "Step 2 of 2 for approve metric. 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: Bless a metric as canonical. Blocked while the metric is drifted from its source insight (refresh or unlink it first). The MCP workflow requires the user to reply with the literal word 'confirm' before execution.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Approve a catalog metric (execute)",+ "title": "Approve a catalog metric (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-approve-prepare": {+ "description": "Step 1 of 2 for approve metric. 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: Bless a metric as canonical. Blocked while the metric is drifted from its source insight (refresh or unlink it first). The MCP workflow requires the user to reply with the literal word 'confirm' before execution.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Approve a catalog metric (prepare)",+ "title": "Approve a catalog metric (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-create": {+ "description": "Create a canonical metric, or refine the one already holding this name (upsert on name; always lands 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Create or refine a catalog metric",+ "title": "Create or refine a catalog metric",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-run": {+ "description": "Run a metric's definition. For an executable metric, returns the results plus a deep link (posthog_url). For an agent-calculated markdown metric, returns the calculation steps in 'instructions' (with 'results' null) for you to follow. Prefer running the canonical metric over re-deriving the number yourself. A result is canonical only when the response has status 'approved' AND is_drifted false - never present a 'proposed' or drifted metric's result as canonical.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Run a catalog metric",+ "title": "Run a catalog metric",+ "required_scopes": ["data_catalog:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-metric-update": {+ "description": "Update a metric's fields. Editing the definition of an approved metric resets it to 'proposed' (it must be re-approved by a human).",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Update a catalog metric",+ "title": "Update a catalog metric",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-accept-execute": {+ "description": "Step 2 of 2 for accept relationship. 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: Promote a relationship proposal to a real warehouse join after re-validating and probing it. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Accept a relationship proposal (execute)",+ "title": "Accept a relationship proposal (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read", "query:read", "warehouse_view:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-accept-prepare": {+ "description": "Step 1 of 2 for accept relationship. 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: Promote a relationship proposal to a real warehouse join after re-validating and probing it. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Accept a relationship proposal (prepare)",+ "title": "Accept a relationship proposal (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read", "query:read", "warehouse_view:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-propose": {+ "description": "Propose a reviewed join between two warehouse tables, with confidence and sampling evidence (match rates, sample values). Both tables must exist. Proposals are deduped undirected, so do not propose the reverse of an existing pair.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Propose a table relationship",+ "title": "Propose a table relationship",+ "required_scopes": ["data_catalog:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-reject-execute": {+ "description": "Step 2 of 2 for reject relationship. 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: Reject a relationship proposal. Persists forever so the pair is never re-proposed. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Reject a relationship proposal (execute)",+ "title": "Reject a relationship proposal (execute)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-data-catalog"+ },+ "data-catalog-relationship-reject-prepare": {+ "description": "Step 1 of 2 for reject relationship. 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: Reject a relationship proposal. Persists forever so the pair is never re-proposed. Requires human typed confirmation.",+ "category": "Data catalog",+ "feature": "data_catalog",+ "summary": "Reject a relationship proposal (prepare)",+ "title": "Reject a relationship proposal (prepare)",+ "required_scopes": ["data_catalog_approval:write", "data_catalog:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-data-catalog"+ },"data-warehouse-source-connect-link": {"description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.","category": "Warehouse sources",diff --git a/services/mcp/scripts/dev-hono-env.ts b/services/mcp/scripts/dev-hono-env.tsnew file mode 100644index 000000000000..0f091413a745--- /dev/null+++ b/services/mcp/scripts/dev-hono-env.ts@@ -0,0 +1,9 @@+type RuntimeEnvironment = Record<string, string | undefined>++export function createDevHonoChildEnv(parentEnv: RuntimeEnvironment): RuntimeEnvironment {+ return {+ ...parentEnv,+ NODE_ENV: parentEnv.NODE_ENV ?? 'development',+ SHUTDOWN_PRESTOP_DELAY_MS: '0',+ }+}diff --git a/services/mcp/scripts/dev-hono.ts b/services/mcp/scripts/dev-hono.tsindex 92259ba52876..83dde7ec8537 100644--- a/services/mcp/scripts/dev-hono.ts+++ b/services/mcp/scripts/dev-hono.ts@@ -7,6 +7,7 @@ import { existsSync } from 'fs'import { resolve } from 'path'import { copyInstructions } from './copy-instructions'+import { createDevHonoChildEnv } from './dev-hono-env'import { honoEsbuildOptions, honoOutfile } from './hono-esbuild-config'// `.env` is the single local-dev env file (see .env.example). Wrangler reads@@ -57,7 +58,7 @@ const launch = async (): Promise<void> => {await killChild()child = spawn(process.execPath, [honoOutfile], {stdio: 'inherit',- env: { ...process.env, SHUTDOWN_PRESTOP_DELAY_MS: '0' },+ env: createDevHonoChildEnv(process.env),})child.on('exit', (code, signal) => {if (signal === 'SIGTERM') {diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 94d19df03cf7..b9506bdbf904 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1195,6 +1195,8 @@ function generateToolCode(schemaDecl,originalHandlerBody: handlerBody,resultType,+ needsProjectId,+ needsOrgId,})return {code: wrapped.code,@@ -1254,8 +1256,8 @@ const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${resultType}> => ${fa/*** Emit prepare + execute factories for a tool that declares `confirmed_action`.- * Returns the combined `code` block — the two factories plus the extended- * schema used by `-execute`. The base schema is emitted exactly as the+ * Returns the combined `code` block — the two factories plus the strict+ * confirmation schema used by `-execute`. The base schema is emitted exactly as the* non-confirmed path does it, so the prepare variant reuses it directly.*/function buildConfirmedActionFactories(args: {@@ -1265,8 +1267,11 @@ function buildConfirmedActionFactories(args: {schemaDecl: stringoriginalHandlerBody: stringresultType: string+ needsProjectId: boolean+ needsOrgId: boolean}): { code: string } {- const { toolName, config, schemaName, schemaDecl, originalHandlerBody, resultType } = args+ const { toolName, config, schemaName, schemaDecl, originalHandlerBody, resultType, needsProjectId, needsOrgId } =+ argsconst baseFactory = toCamelCase(toolName)const prepareName = `${toolName}-prepare`const executeName = `${toolName}-execute`@@ -1276,52 +1281,89 @@ function buildConfirmedActionFactories(args: {const actionLabel = config.confirmed_action?.action_label ?? config.title ?? toolNameconst messageTemplate = config.confirmed_action?.message ?? `Confirm ${actionLabel}?`- // Execute schema = base schema extended with the two framework fields.+ // Execute accepts only the two framework fields. The action arguments+ // were validated and signed at prepare time; accepting them again would+ // advertise mutable inputs that the runtime intentionally discards.// `confirmation` is z.string() not z.literal('confirm') on purpose: the// runtime checks the value and refuses with a structured tool-call// result + metric counter. A literal would raise a generic zod parse// error before our guard runs, losing the metric and the// user-targetted refusal text.- const executeSchemaDecl = `const ${executeSchemaName} = ${schemaName}.extend({+ const executeSchemaDecl = `const ${executeSchemaName} = 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.'),})`+ // Bound scope: the active project/org is signed at prepare time and+ // re-checked at execute time so a confirmation can't be replayed against+ // a different project after `switch-project`. Resolved into locally-named+ // consts so the `-execute` variant never collides with the `projectId`+ // the original handler body declares.+ const scopeResolveLines: string[] = []+ const scopeParts: string[] = []+ if (needsOrgId) {+ scopeResolveLines.push(` const __scopeOrgId = await context.stateManager.getOrgID()`)+ scopeParts.push('orgId: String(__scopeOrgId)')+ }+ if (needsProjectId) {+ scopeResolveLines.push(` const __scopeProjectId = await context.stateManager.getProjectId()`)+ scopeParts.push('projectId: String(__scopeProjectId)')+ }+ const hasScope = scopeParts.length > 0+ const scopeResolveBlock = hasScope ? scopeResolveLines.join('\n') + '\n' : ''+ const prepareScopeField = hasScope ? ` boundScope: { ${scopeParts.join(', ')} },\n` : ''+ const executeScopeField = hasScope ? ` expectedScope: { ${scopeParts.join(', ')} },\n` : ''++ // The original handler body re-reads project/org from state to build the+ // API path. In the execute variant that would be a second, independent+ // read after the scope check — MCP handles batched requests concurrently,+ // so a `switch-project` racing between the scope check and the path build+ // could retarget the request at a different project than the one the+ // confirmation was bound to. Alias the path IDs to the scope values we+ // captured once (and verified against `expectedScope`) so the check and+ // the request always agree.+ let executeHandlerBody = originalHandlerBody+ if (needsOrgId) {+ executeHandlerBody = executeHandlerBody.replace(+ ' const orgId = await context.stateManager.getOrgID()\n',+ ' const orgId = __scopeOrgId\n'+ )+ }+ if (needsProjectId) {+ executeHandlerBody = executeHandlerBody.replace(+ ' const projectId = await context.stateManager.getProjectId()\n',+ ' const projectId = __scopeProjectId\n'+ )+ }+// Prepare handler: validate args via the base schema (already happens// before our handler runs) and call into the runtime. Args are signed- // verbatim — bound to user identity + purpose.+ // verbatim — bound to user identity + purpose (+ active scope).const prepareHandler = ` const __runtime = getConfirmedActionRuntime()- return await prepareConfirmedAction(context, {+${scopeResolveBlock} return await prepareConfirmedAction(context, {args: params,purpose: ${JSON.stringify(toolName)},actionLabel: ${JSON.stringify(actionLabel)},messageTemplate: ${JSON.stringify(messageTemplate)},codec: __runtime.codec,- })+${prepareScopeField} })`// Execute handler: guard, then re-run the original handler body with- // the verified args. `params` is reassigned to the verified payload so- // the rest of the original code path (which reads from `params.*`)- // works unchanged. The cast pins the type so TS knows the original- // shape survives.+ // the signed, verified args under the same `params` name the generated+ // request code expects.const executeHandler = ` const __runtime = getConfirmedActionRuntime()- const __guard = await executeConfirmedAction(context, {- incomingArgs: params,+${scopeResolveBlock} const __guard = await executeConfirmedAction<z.infer<typeof ${schemaName}>>(context, {+ incomingArgs: confirmationParams,purpose: ${JSON.stringify(toolName)},codec: __runtime.codec,ledger: __runtime.ledger,- })+${executeScopeField} })if (!__guard.ok) {return __guard.result as never}- // Replace, do NOT merge: only signed fields are authorized. Any- // base-schema field the model slipped into the execute call- // (e.g. an unsigned 'name' alongside the signed 'enforce_2fa')- // would otherwise survive into the downstream API body.- // eslint-disable-next-line no-param-reassign- params = { ...__guard.verifiedArgs } as typeof params-${originalHandlerBody}`+ const params = __guard.verifiedArgs+${executeHandlerBody}`const prepareBody = `{name: '${prepareName}',@@ -1333,7 +1375,7 @@ ${prepareHandler} },const executeBody = `{name: '${executeName}',schema: ${executeSchemaName},- handler: async (context: Context, params: z.infer<typeof ${executeSchemaName}>) => {+ handler: async (context: Context, confirmationParams: z.infer<typeof ${executeSchemaName}>) => {${executeHandler} },}`diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.tsindex 649cf7bc8801..04c3774c8719 100644--- a/services/mcp/scripts/yaml-config-schema.ts+++ b/services/mcp/scripts/yaml-config-schema.ts@@ -250,6 +250,11 @@ export const ToolConfigSchema = z'input_schema replaces the entire schema, so include_params, exclude_params, and param_overrides have no effect and should be removed',})+ .refine((data) => !(data.confirmed_action && data.input_schema), {+ message:+ '`confirmed_action` cannot be combined with `input_schema` yet because custom input schemas bypass the confirmed-action prepare/execute codegen path. Remove `input_schema` or extend custom-schema codegen to support confirmed actions.',+ path: ['confirmed_action'],+ }).refine((data) => !(data.description && data.description_file), {message: 'description and description_file are mutually exclusive',})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 061c40b55260..9310ed87fa1e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16728,6 +16728,8 @@ export namespace Schemas {ai_model?: string;/*** AI author's confidence in the proposal, 0-1.+ * @minimum 0+ * @maximum 1* @nullable*/confidence?: number | null;@@ -43627,6 +43629,8 @@ export namespace Schemas {ai_model?: string;/*** AI author's confidence in the proposal, 0-1.+ * @minimum 0+ * @maximum 1* @nullable*/confidence?: number | null;diff --git a/services/mcp/src/generated/data_catalog/api.ts b/services/mcp/src/generated/data_catalog/api.tsnew file mode 100644index 000000000000..2e017ed83faf--- /dev/null+++ b/services/mcp/src/generated/data_catalog/api.ts@@ -0,0 +1,332 @@+/**+ * 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 10 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.+ */+export const DataCatalogCertificationsCreateParams = /* @__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 DataCatalogCertificationsCreateBody = /* @__PURE__ */ zod+ .object({+ table_id: zod.string().optional().describe('Warehouse table id to certify (XOR the other targets).'),+ saved_query_id: zod.string().optional().describe('Warehouse view (saved query) id to certify.'),+ table_name: zod.string().optional().describe('Table name; 409 with candidates if ambiguous.'),+ view_name: zod.string().optional().describe('View name; 409 with candidates if ambiguous.'),+ notes: zod.string().optional().describe('Why this mark exists.'),+ })+ .describe('Input for proposing a certification: address the target by id or (convenience) by name.')++/**+ * Mark the target as certified (prefer this source).+ */+export const DataCatalogCertificationsCertifyCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this table certification.'),+ 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/."+ ),+})++/**+ * Mark the target as deprecated (avoid this source).+ */+export const DataCatalogCertificationsDeprecateCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this table certification.'),+ 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/."+ ),+})++/**+ * Create a metric, or refine the one already holding this name for the team.+ */+export const DataCatalogMetricsCreateParams = /* @__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 dataCatalogMetricsCreateBodyNameMax = 128++export const dataCatalogMetricsCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]*$')+export const dataCatalogMetricsCreateBodyDisplayNameMax = 255++export const dataCatalogMetricsCreateBodyUnitMax = 64++export const dataCatalogMetricsCreateBodySourceInsightShortIdMax = 12++export const dataCatalogMetricsCreateBodyAiModelMax = 128++export const dataCatalogMetricsCreateBodyConfidenceMin = 0+export const dataCatalogMetricsCreateBodyConfidenceMax = 1++export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataCatalogMetricsCreateBodyNameMax)+ .regex(dataCatalogMetricsCreateBodyNameRegExp)+ .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ display_name: zod+ .string()+ .max(dataCatalogMetricsCreateBodyDisplayNameMax)+ .optional()+ .describe('Human-friendly label. Mutable, unlike name.'),+ description: zod.string().describe('What the metric means and how to interpret it.'),+ unit: zod+ .string()+ .max(dataCatalogMetricsCreateBodyUnitMax)+ .optional()+ .describe('Unit of the result, e.g. usd, percent, cents.'),+ definition: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ source_insight_short_id: zod+ .string()+ .max(dataCatalogMetricsCreateBodySourceInsightShortIdMax)+ .nullish()+ .describe(+ "Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition."+ ),+ ai_model: zod+ .string()+ .max(dataCatalogMetricsCreateBodyAiModelMax)+ .optional()+ .describe('Model that generated the metric, if AI-authored.'),+ confidence: zod+ .number()+ .min(dataCatalogMetricsCreateBodyConfidenceMin)+ .max(dataCatalogMetricsCreateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the proposal, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const DataCatalogMetricsPartialUpdateParams = /* @__PURE__ */ zod.object({+ name: 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 dataCatalogMetricsPartialUpdateBodyNameMax = 128++export const dataCatalogMetricsPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]*$')+export const dataCatalogMetricsPartialUpdateBodyDisplayNameMax = 255++export const dataCatalogMetricsPartialUpdateBodyUnitMax = 64++export const dataCatalogMetricsPartialUpdateBodySourceInsightShortIdMax = 12++export const dataCatalogMetricsPartialUpdateBodyAiModelMax = 128++export const dataCatalogMetricsPartialUpdateBodyConfidenceMin = 0+export const dataCatalogMetricsPartialUpdateBodyConfidenceMax = 1++export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyNameMax)+ .regex(dataCatalogMetricsPartialUpdateBodyNameRegExp)+ .optional()+ .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ display_name: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyDisplayNameMax)+ .optional()+ .describe('Human-friendly label. Mutable, unlike name.'),+ description: zod.string().optional().describe('What the metric means and how to interpret it.'),+ unit: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyUnitMax)+ .optional()+ .describe('Unit of the result, e.g. usd, percent, cents.'),+ definition: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ source_insight_short_id: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodySourceInsightShortIdMax)+ .nullish()+ .describe(+ "Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition."+ ),+ ai_model: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the metric, if AI-authored.'),+ confidence: zod+ .number()+ .min(dataCatalogMetricsPartialUpdateBodyConfidenceMin)+ .max(dataCatalogMetricsPartialUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the proposal, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * Bless a metric as canonical. Returns 409 while the metric is drifted from its insight.+ */+export const DataCatalogMetricsApproveCreateParams = /* @__PURE__ */ zod.object({+ name: 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/."+ ),+})++/**+ * Execute the metric's definition and return the normalized result envelope.+ */+export const DataCatalogMetricsRunCreateParams = /* @__PURE__ */ zod.object({+ name: 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 DataCatalogMetricsRunCreateQueryParams = /* @__PURE__ */ zod.object({+ refresh: zod+ .enum(['blocking', 'async', 'lazy_async', 'force_blocking', 'force_async', 'force_cache'])+ .optional()+ .describe(+ 'Cache/execution behavior, same semantics as /query/. Omit to serve a fresh cache hit and calculate blocking when stale.\n\n* `blocking` - blocking\n* `async` - async\n* `lazy_async` - lazy_async\n* `force_blocking` - force_blocking\n* `force_async` - force_async\n* `force_cache` - force_cache'+ ),+})++export const DataCatalogMetricsRunCreateBody = /* @__PURE__ */ zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe(+ "Override the start of the query window (e.g. '-7d'). Rejected for HogQLQuery metrics, whose window is fixed in SQL."+ ),+ date_to: zod.string().optional().describe('Override the end of the query window.'),+ interval: zod+ .enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'])+ .describe(+ '* `second` - second\n* `minute` - minute\n* `hour` - hour\n* `day` - day\n* `week` - week\n* `month` - month\n* `quarter` - quarter\n* `year` - year'+ )+ .optional()+ .describe(+ 'Override the bucket interval. Rejected for HogQLQuery metrics.\n\n* `second` - second\n* `minute` - minute\n* `hour` - hour\n* `day` - day\n* `week` - week\n* `month` - month\n* `quarter` - quarter\n* `year` - year'+ ),+ query_id: zod.string().optional().describe('Client-supplied id to correlate or cancel the run.'),+ })+ .describe('Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.')++/**+ * Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.+ */+export const DataCatalogRelationshipProposalsCreateParams = /* @__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 dataCatalogRelationshipProposalsCreateBodySourceTableNameMax = 400++export const dataCatalogRelationshipProposalsCreateBodySourceTableKeyMax = 400++export const dataCatalogRelationshipProposalsCreateBodyJoiningTableNameMax = 400++export const dataCatalogRelationshipProposalsCreateBodyJoiningTableKeyMax = 400++export const dataCatalogRelationshipProposalsCreateBodyFieldNameMax = 400++export const dataCatalogRelationshipProposalsCreateBodyConfidenceMin = 0+export const dataCatalogRelationshipProposalsCreateBodyConfidenceMax = 1++export const DataCatalogRelationshipProposalsCreateBody = /* @__PURE__ */ zod.object({+ source_table_name: zod+ .string()+ .max(dataCatalogRelationshipProposalsCreateBodySourceTableNameMax)+ .describe('Name of the table the join starts from.'),+ source_table_key: zod+ .string()+ .max(dataCatalogRelationshipProposalsCreateBodySourceTableKeyMax)+ .describe('HogQL key expression on the source table (casts allowed).'),+ joining_table_name: zod+ .string()+ .max(dataCatalogRelationshipProposalsCreateBodyJoiningTableNameMax)+ .describe('Name of the table being joined in.'),+ joining_table_key: zod+ .string()+ .max(dataCatalogRelationshipProposalsCreateBodyJoiningTableKeyMax)+ .describe('HogQL key expression on the joining table (casts allowed).'),+ field_name: zod+ .string()+ .max(dataCatalogRelationshipProposalsCreateBodyFieldNameMax)+ .describe('Accessor the join adds to the source table.'),+ configuration: zod.unknown().optional().describe('Extra join configuration, e.g. a field mapping.'),+ confidence: zod+ .number()+ .min(dataCatalogRelationshipProposalsCreateBodyConfidenceMin)+ .max(dataCatalogRelationshipProposalsCreateBodyConfidenceMax)+ .nullish()+ .describe('Discovery confidence in this join, 0-1.'),+ reasoning: zod.string().optional().describe('Why this join is proposed.'),+ evidence: zod.unknown().optional().describe('Sampling evidence: match rates, sample values.'),+})++/**+ * Promote the proposal to a real warehouse join after re-validating and probing it.+ */+export const DataCatalogRelationshipProposalsAcceptCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this relationship proposal.'),+ 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/."+ ),+})++/**+ * Reject the proposal. Persists forever so the pair is never re-proposed.+ */+export const DataCatalogRelationshipProposalsRejectCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this relationship proposal.'),+ 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 DataCatalogRelationshipProposalsRejectCreateBody = /* @__PURE__ */ zod.object({+ rejection_reason: zod+ .string()+ .optional()+ .describe('Why the proposal is rejected. Persisted so it is never re-proposed.'),+})diff --git a/services/mcp/src/tools/confirmed-action-runtime.ts b/services/mcp/src/tools/confirmed-action-runtime.tsindex acba5bd70645..6387d1628f49 100644--- a/services/mcp/src/tools/confirmed-action-runtime.ts+++ b/services/mcp/src/tools/confirmed-action-runtime.ts@@ -55,6 +55,13 @@ export const CONFIRMATION_WORD = 'confirm'export const CONFIRMATION_HASH_ARG = 'confirmation_hash'export const CONFIRMATION_WORD_ARG = 'confirmation'+/**+ * Ambient scope (active project / organization) an action targets. Signed+ * at prepare time and re-checked at execute time so a confirmation issued+ * while one project was active can't be replayed against a different one.+ */+export type ConfirmedActionScope = Record<string, string>+export interface PrepareConfirmedActionOptions<P extends Record<string, unknown>> {/** The validated tool args. Signed into the hash so they can't be tampered with between prepare and execute. */args: P@@ -70,6 +77,23 @@ export interface PrepareConfirmedActionOptions<P extends Record<string, unknown>messageTemplate: string/** Codec — instantiated once at startup, reused across requests. */codec: SignedStateCodec+ /**+ * Ambient scope resolved from current state at prepare time (e.g. the+ * active project the action targets). Signed into the hash; `execute`+ * refuses if the scope active at execute time no longer matches. Omit+ * for actions with no project/org scope.+ */+ boundScope?: ConfirmedActionScope+}++/**+ * Shape of the signed payload. The runtime wraps the caller's args+ * together with the bound scope so both travel — and are tamper-checked —+ * inside the single opaque `payload` claim the codec signs.+ */+interface SignedConfirmedActionPayload {+ args: Record<string, unknown>+ scope: ConfirmedActionScope | null}export interface PrepareConfirmedActionResult {@@ -90,10 +114,14 @@ export async function prepareConfirmedAction<P extends Record<string, unknown>>(options: PrepareConfirmedActionOptions<P>): Promise<PrepareConfirmedActionResult> {const sub = await context.getDistinctId()+ const payload: SignedConfirmedActionPayload = {+ args: options.args,+ scope: options.boundScope ?? null,+ }const { token } = await options.codec.encode({sub,purpose: options.purpose,- payload: options.args,+ payload,})confirmedActionPreparesTotal.inc({ tool: options.purpose, status: 'ok' })return {@@ -104,19 +132,25 @@ export async function prepareConfirmedAction<P extends Record<string, unknown>>(next_steps:`Surface the message above to the user. Wait for them to reply with the literal word "${CONFIRMATION_WORD}". ` +`Then call the matching \`-execute\` tool with \`${CONFIRMATION_HASH_ARG}\` set to the confirmation_hash from this result, ` +- `\`${CONFIRMATION_WORD_ARG}\` set to the user's literal reply, and the same arguments you used here. ` ++ `and \`${CONFIRMATION_WORD_ARG}\` set to the user's literal reply. The signed hash already contains the action arguments. ` +`If the user does not reply with "${CONFIRMATION_WORD}", do not call the execute tool.`,}}-export interface ExecuteConfirmedActionOptions<P extends Record<string, unknown>> {- /** The full incoming args object — includes `confirmation_hash`, `confirmation`, and the original tool args. */- incomingArgs: P & { [CONFIRMATION_HASH_ARG]: string; [CONFIRMATION_WORD_ARG]: string }+export interface ExecuteConfirmedActionOptions {+ /** The execute tool accepts only the signed hash and the user's confirmation word. */+ incomingArgs: { [CONFIRMATION_HASH_ARG]: string; [CONFIRMATION_WORD_ARG]: string }/** Same `purpose` value used at prepare time. */purpose: string/** Codec + ledger; both single instances reused across requests. */codec: SignedStateCodecledger: NonceLedger+ /**+ * Scope resolved from *current* state at execute time. Compared against+ * the scope signed at prepare time; any mismatch refuses. Omit for+ * actions prepared without a `boundScope`.+ */+ expectedScope?: ConfirmedActionScope}export type ExecuteConfirmedActionOutcome<P> = { ok: true; verifiedArgs: P } | { ok: false; result: ToolErrorResult }@@ -134,7 +168,7 @@ interface ToolErrorResult {*/export async function executeConfirmedAction<P extends Record<string, unknown>>(context: Context,- options: ExecuteConfirmedActionOptions<P>+ options: ExecuteConfirmedActionOptions): Promise<ExecuteConfirmedActionOutcome<P>> {const sub = await context.getDistinctId()@@ -179,8 +213,8 @@ export async function executeConfirmedAction<P extends Record<string, unknown>>(}// The payload was signed at prepare time; treat it as untrusted JSON- // and shape-check before returning. The caller already knows the- // expected shape via its tool schema.+ // and shape-check before returning. The runtime wraps `{ args, scope }`,+ // so validate the wrapper and the args object it carries.const verified = claims.payloadif (verified === null || typeof verified !== 'object' || Array.isArray(verified)) {return refuse(@@ -189,9 +223,47 @@ export async function executeConfirmedAction<P extends Record<string, unknown>>(`${options.purpose} was not executed — confirmation payload is malformed.`)}+ const wrapper = verified as Partial<SignedConfirmedActionPayload>+ const args = wrapper.args+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {+ return refuse(+ options.purpose,+ 'malformed_payload',+ `${options.purpose} was not executed — confirmation payload is malformed.`+ )+ }++ // Scope binding: the project/org that was active at prepare time is+ // signed into the token. If the active scope has since changed (e.g. the+ // agent ran `switch-project` after the user confirmed), the same+ // confirmation must not authorize the action against a different target.+ if (!scopesMatch(wrapper.scope ?? null, options.expectedScope ?? null)) {+ return refuse(+ options.purpose,+ 'scope_mismatch',+ `${options.purpose} was not executed — the confirmation was issued for a different project or organization than the one currently active. Switch back to the project the action was prepared in, or run the prepare step again in the current one.`+ )+ }confirmedActionExecutesTotal.inc({ tool: options.purpose, status: 'ok' })- return { ok: true, verifiedArgs: verified as P }+ return { ok: true, verifiedArgs: args as P }+}++/**+ * Compare the scope signed at prepare time against the scope active at+ * execute time. Both are shallow string maps (or `null` when the action is+ * unscoped). A mismatch on any key — or a differing key set — fails closed.+ */+function scopesMatch(signed: ConfirmedActionScope | null, expected: ConfirmedActionScope | null): boolean {+ const a = signed ?? {}+ const b = expected ?? {}+ const keys = new Set([...Object.keys(a), ...Object.keys(b)])+ for (const key of keys) {+ if (a[key] !== b[key]) {+ return false+ }+ }+ return true}function refuse(purpose: string, reason: string, message: string): { ok: false; result: ToolErrorResult } {diff --git a/services/mcp/src/tools/generated/data_catalog.ts b/services/mcp/src/tools/generated/data_catalog.tsnew file mode 100644index 000000000000..0863b51ac4c7--- /dev/null+++ b/services/mcp/src/tools/generated/data_catalog.ts@@ -0,0 +1,571 @@+// AUTO-GENERATED from products/data_catalog/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ DataCatalogCertificationsCertifyCreateParams,+ DataCatalogCertificationsCreateBody,+ DataCatalogCertificationsDeprecateCreateParams,+ DataCatalogMetricsApproveCreateParams,+ DataCatalogMetricsCreateBody,+ DataCatalogMetricsPartialUpdateBody,+ DataCatalogMetricsPartialUpdateParams,+ DataCatalogMetricsRunCreateBody,+ DataCatalogMetricsRunCreateParams,+ DataCatalogMetricsRunCreateQueryParams,+ DataCatalogRelationshipProposalsAcceptCreateParams,+ DataCatalogRelationshipProposalsCreateBody,+ DataCatalogRelationshipProposalsRejectCreateBody,+ DataCatalogRelationshipProposalsRejectCreateParams,+} from '@/generated/data_catalog/api'+import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'+import {+ executeConfirmedAction,+ prepareConfirmedAction,+ type PrepareConfirmedActionResult,+} from '@/tools/confirmed-action-runtime'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const DataCatalogCertificationCertifySchema = DataCatalogCertificationsCertifyCreateParams.omit({ project_id: true })++const DataCatalogCertificationCertifySchemaExecute = 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 dataCatalogCertificationCertifyPrepare = (): ToolBase<+ typeof DataCatalogCertificationCertifySchema,+ PrepareConfirmedActionResult+> => ({+ name: 'data-catalog-certification-certify-prepare',+ schema: DataCatalogCertificationCertifySchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogCertificationCertifySchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: 'data-catalog-certification-certify',+ actionLabel: 'certify source',+ messageTemplate:+ "About to mark certification '{id}' as certified (agents should prefer this source). Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ boundScope: { projectId: String(__scopeProjectId) },+ })+ },+})++const dataCatalogCertificationCertifyExecute = (): ToolBase<+ typeof DataCatalogCertificationCertifySchemaExecute,+ Schemas.DataCatalogCertification+> => ({+ name: 'data-catalog-certification-certify-execute',+ schema: DataCatalogCertificationCertifySchemaExecute,+ handler: async (+ context: Context,+ confirmationParams: z.infer<typeof DataCatalogCertificationCertifySchemaExecute>+ ) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ const __guard = await executeConfirmedAction<z.infer<typeof DataCatalogCertificationCertifySchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'data-catalog-certification-certify',+ 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 result = await context.api.request<Schemas.DataCatalogCertification>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/certifications/${encodeURIComponent(String(params.id))}/certify/`,+ })+ return result+ },+})++const DataCatalogCertificationDeprecateSchema = DataCatalogCertificationsDeprecateCreateParams.omit({+ project_id: true,+})++const DataCatalogCertificationDeprecateSchemaExecute = 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 dataCatalogCertificationDeprecatePrepare = (): ToolBase<+ typeof DataCatalogCertificationDeprecateSchema,+ PrepareConfirmedActionResult+> => ({+ name: 'data-catalog-certification-deprecate-prepare',+ schema: DataCatalogCertificationDeprecateSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogCertificationDeprecateSchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: 'data-catalog-certification-deprecate',+ actionLabel: 'deprecate source',+ messageTemplate:+ "About to mark certification '{id}' as deprecated (agents should avoid this source). Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ boundScope: { projectId: String(__scopeProjectId) },+ })+ },+})++const dataCatalogCertificationDeprecateExecute = (): ToolBase<+ typeof DataCatalogCertificationDeprecateSchemaExecute,+ Schemas.DataCatalogCertification+> => ({+ name: 'data-catalog-certification-deprecate-execute',+ schema: DataCatalogCertificationDeprecateSchemaExecute,+ handler: async (+ context: Context,+ confirmationParams: z.infer<typeof DataCatalogCertificationDeprecateSchemaExecute>+ ) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ const __guard = await executeConfirmedAction<z.infer<typeof DataCatalogCertificationDeprecateSchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'data-catalog-certification-deprecate',+ 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 result = await context.api.request<Schemas.DataCatalogCertification>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/certifications/${encodeURIComponent(String(params.id))}/deprecate/`,+ })+ return result+ },+})++const DataCatalogCertificationProposeSchema = DataCatalogCertificationsCreateBody++const dataCatalogCertificationPropose = (): ToolBase<+ typeof DataCatalogCertificationProposeSchema,+ Schemas.DataCatalogCertification+> => ({+ name: 'data-catalog-certification-propose',+ schema: DataCatalogCertificationProposeSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogCertificationProposeSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.table_id !== undefined) {+ body['table_id'] = params.table_id+ }+ if (params.saved_query_id !== undefined) {+ body['saved_query_id'] = params.saved_query_id+ }+ if (params.table_name !== undefined) {+ body['table_name'] = params.table_name+ }+ if (params.view_name !== undefined) {+ body['view_name'] = params.view_name+ }+ if (params.notes !== undefined) {+ body['notes'] = params.notes+ }+ const result = await context.api.request<Schemas.DataCatalogCertification>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/certifications/`,+ body,+ })+ return result+ },+})++const DataCatalogMetricApproveSchema = DataCatalogMetricsApproveCreateParams.omit({ project_id: true })++const DataCatalogMetricApproveSchemaExecute = 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 dataCatalogMetricApprovePrepare = (): ToolBase<+ typeof DataCatalogMetricApproveSchema,+ PrepareConfirmedActionResult+> => ({+ name: 'data-catalog-metric-approve-prepare',+ schema: DataCatalogMetricApproveSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogMetricApproveSchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: 'data-catalog-metric-approve',+ actionLabel: 'approve metric',+ messageTemplate:+ "About to approve metric '{name}' as a canonical, human-vouched metric. Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ boundScope: { projectId: String(__scopeProjectId) },+ })+ },+})++const dataCatalogMetricApproveExecute = (): ToolBase<+ typeof DataCatalogMetricApproveSchemaExecute,+ Schemas.DataCatalogMetric+> => ({+ name: 'data-catalog-metric-approve-execute',+ schema: DataCatalogMetricApproveSchemaExecute,+ handler: async (context: Context, confirmationParams: z.infer<typeof DataCatalogMetricApproveSchemaExecute>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ const __guard = await executeConfirmedAction<z.infer<typeof DataCatalogMetricApproveSchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'data-catalog-metric-approve',+ 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 result = await context.api.request<Schemas.DataCatalogMetric>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/metrics/${encodeURIComponent(String(params.name))}/approve/`,+ })+ return result+ },+})++const DataCatalogMetricCreateSchema = DataCatalogMetricsCreateBody++const dataCatalogMetricCreate = (): ToolBase<typeof DataCatalogMetricCreateSchema, Schemas.DataCatalogMetric> => ({+ name: 'data-catalog-metric-create',+ schema: DataCatalogMetricCreateSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogMetricCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.display_name !== undefined) {+ body['display_name'] = params.display_name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.unit !== undefined) {+ body['unit'] = params.unit+ }+ if (params.definition !== undefined) {+ body['definition'] = params.definition+ }+ if (params.source_insight_short_id !== undefined) {+ body['source_insight_short_id'] = params.source_insight_short_id+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ body['created_source'] = 'ai_generated'+ const result = await context.api.request<Schemas.DataCatalogMetric>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/metrics/`,+ body,+ })+ return result+ },+})++const DataCatalogMetricRunSchema = DataCatalogMetricsRunCreateParams.omit({ project_id: true })+ .extend(DataCatalogMetricsRunCreateQueryParams.shape)+ .extend(DataCatalogMetricsRunCreateBody.shape)++const dataCatalogMetricRun = (): ToolBase<typeof DataCatalogMetricRunSchema, Schemas.DataCatalogMetricRun> => ({+ name: 'data-catalog-metric-run',+ schema: DataCatalogMetricRunSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogMetricRunSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.date_from !== undefined) {+ body['date_from'] = params.date_from+ }+ if (params.date_to !== undefined) {+ body['date_to'] = params.date_to+ }+ if (params.interval !== undefined) {+ body['interval'] = params.interval+ }+ if (params.query_id !== undefined) {+ body['query_id'] = params.query_id+ }+ const result = await context.api.request<Schemas.DataCatalogMetricRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/metrics/${encodeURIComponent(String(params.name))}/run/`,+ body,+ query: {+ refresh: params.refresh,+ },+ })+ return result+ },+})++const DataCatalogMetricUpdateSchema = DataCatalogMetricsPartialUpdateParams.omit({ project_id: true }).extend(+ DataCatalogMetricsPartialUpdateBody.shape+)++const dataCatalogMetricUpdate = (): ToolBase<typeof DataCatalogMetricUpdateSchema, Schemas.DataCatalogMetric> => ({+ name: 'data-catalog-metric-update',+ schema: DataCatalogMetricUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogMetricUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.display_name !== undefined) {+ body['display_name'] = params.display_name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.unit !== undefined) {+ body['unit'] = params.unit+ }+ if (params.definition !== undefined) {+ body['definition'] = params.definition+ }+ if (params.source_insight_short_id !== undefined) {+ body['source_insight_short_id'] = params.source_insight_short_id+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ body['created_source'] = 'ai_generated'+ const result = await context.api.request<Schemas.DataCatalogMetric>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/metrics/${encodeURIComponent(String(params.name))}/`,+ body,+ })+ return result+ },+})++const DataCatalogRelationshipAcceptSchema = DataCatalogRelationshipProposalsAcceptCreateParams.omit({+ project_id: true,+})++const DataCatalogRelationshipAcceptSchemaExecute = 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 dataCatalogRelationshipAcceptPrepare = (): ToolBase<+ typeof DataCatalogRelationshipAcceptSchema,+ PrepareConfirmedActionResult+> => ({+ name: 'data-catalog-relationship-accept-prepare',+ schema: DataCatalogRelationshipAcceptSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogRelationshipAcceptSchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: 'data-catalog-relationship-accept',+ actionLabel: 'accept relationship',+ messageTemplate:+ "About to accept relationship proposal '{id}', promoting it to a real warehouse join. Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ boundScope: { projectId: String(__scopeProjectId) },+ })+ },+})++const dataCatalogRelationshipAcceptExecute = (): ToolBase<+ typeof DataCatalogRelationshipAcceptSchemaExecute,+ Schemas.DataCatalogRelationshipProposal+> => ({+ name: 'data-catalog-relationship-accept-execute',+ schema: DataCatalogRelationshipAcceptSchemaExecute,+ handler: async (+ context: Context,+ confirmationParams: z.infer<typeof DataCatalogRelationshipAcceptSchemaExecute>+ ) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ const __guard = await executeConfirmedAction<z.infer<typeof DataCatalogRelationshipAcceptSchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'data-catalog-relationship-accept',+ 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 result = await context.api.request<Schemas.DataCatalogRelationshipProposal>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/relationship_proposals/${encodeURIComponent(String(params.id))}/accept/`,+ })+ return result+ },+})++const DataCatalogRelationshipProposeSchema = DataCatalogRelationshipProposalsCreateBody++const dataCatalogRelationshipPropose = (): ToolBase<+ typeof DataCatalogRelationshipProposeSchema,+ Schemas.DataCatalogRelationshipProposal+> => ({+ name: 'data-catalog-relationship-propose',+ schema: DataCatalogRelationshipProposeSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogRelationshipProposeSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.source_table_name !== undefined) {+ body['source_table_name'] = params.source_table_name+ }+ if (params.source_table_key !== undefined) {+ body['source_table_key'] = params.source_table_key+ }+ if (params.joining_table_name !== undefined) {+ body['joining_table_name'] = params.joining_table_name+ }+ if (params.joining_table_key !== undefined) {+ body['joining_table_key'] = params.joining_table_key+ }+ if (params.field_name !== undefined) {+ body['field_name'] = params.field_name+ }+ if (params.configuration !== undefined) {+ body['configuration'] = params.configuration+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ if (params.evidence !== undefined) {+ body['evidence'] = params.evidence+ }+ const result = await context.api.request<Schemas.DataCatalogRelationshipProposal>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/relationship_proposals/`,+ body,+ })+ return result+ },+})++const DataCatalogRelationshipRejectSchema = DataCatalogRelationshipProposalsRejectCreateParams.omit({+ project_id: true,+}).extend(DataCatalogRelationshipProposalsRejectCreateBody.shape)++const DataCatalogRelationshipRejectSchemaExecute = 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 dataCatalogRelationshipRejectPrepare = (): ToolBase<+ typeof DataCatalogRelationshipRejectSchema,+ PrepareConfirmedActionResult+> => ({+ name: 'data-catalog-relationship-reject-prepare',+ schema: DataCatalogRelationshipRejectSchema,+ handler: async (context: Context, params: z.infer<typeof DataCatalogRelationshipRejectSchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: 'data-catalog-relationship-reject',+ actionLabel: 'reject relationship',+ messageTemplate:+ "About to reject relationship proposal '{id}'. This permanently suppresses re-proposing the pair. Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ boundScope: { projectId: String(__scopeProjectId) },+ })+ },+})++const dataCatalogRelationshipRejectExecute = (): ToolBase<+ typeof DataCatalogRelationshipRejectSchemaExecute,+ Schemas.DataCatalogRelationshipProposal+> => ({+ name: 'data-catalog-relationship-reject-execute',+ schema: DataCatalogRelationshipRejectSchemaExecute,+ handler: async (+ context: Context,+ confirmationParams: z.infer<typeof DataCatalogRelationshipRejectSchemaExecute>+ ) => {+ const __runtime = getConfirmedActionRuntime()+ const __scopeProjectId = await context.stateManager.getProjectId()+ const __guard = await executeConfirmedAction<z.infer<typeof DataCatalogRelationshipRejectSchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'data-catalog-relationship-reject',+ 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.rejection_reason !== undefined) {+ body['rejection_reason'] = params.rejection_reason+ }+ const result = await context.api.request<Schemas.DataCatalogRelationshipProposal>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/relationship_proposals/${encodeURIComponent(String(params.id))}/reject/`,+ body,+ })+ return result+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'data-catalog-certification-certify-prepare': dataCatalogCertificationCertifyPrepare,+ 'data-catalog-certification-certify-execute': dataCatalogCertificationCertifyExecute,+ 'data-catalog-certification-deprecate-prepare': dataCatalogCertificationDeprecatePrepare,+ 'data-catalog-certification-deprecate-execute': dataCatalogCertificationDeprecateExecute,+ 'data-catalog-certification-propose': dataCatalogCertificationPropose,+ 'data-catalog-metric-approve-prepare': dataCatalogMetricApprovePrepare,+ 'data-catalog-metric-approve-execute': dataCatalogMetricApproveExecute,+ 'data-catalog-metric-create': dataCatalogMetricCreate,+ 'data-catalog-metric-run': dataCatalogMetricRun,+ 'data-catalog-metric-update': dataCatalogMetricUpdate,+ 'data-catalog-relationship-accept-prepare': dataCatalogRelationshipAcceptPrepare,+ 'data-catalog-relationship-accept-execute': dataCatalogRelationshipAcceptExecute,+ 'data-catalog-relationship-propose': dataCatalogRelationshipPropose,+ 'data-catalog-relationship-reject-prepare': dataCatalogRelationshipRejectPrepare,+ 'data-catalog-relationship-reject-execute': dataCatalogRelationshipRejectExecute,+}diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex a771e2752b80..c57811fbc76a 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -15,6 +15,7 @@ import { GENERATED_TOOLS as conversations } from './conversations'import { GENERATED_TOOLS as core } from './core'import { GENERATED_TOOLS as customer_analytics } from './customer_analytics'import { GENERATED_TOOLS as dashboards } from './dashboards'+import { GENERATED_TOOLS as data_catalog } from './data_catalog'import { GENERATED_TOOLS as data_management } from './data_management'import { GENERATED_TOOLS as data_warehouse } from './data_warehouse'import { GENERATED_TOOLS as docs } from './docs'@@ -72,6 +73,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...core,...customer_analytics,...dashboards,+ ...data_catalog,...data_management,...data_warehouse,...docs,diff --git a/services/mcp/tests/unit/confirmed-action-runtime.test.ts b/services/mcp/tests/unit/confirmed-action-runtime.test.tsindex c262801cb5f4..66bd6a107025 100644--- a/services/mcp/tests/unit/confirmed-action-runtime.test.ts+++ b/services/mcp/tests/unit/confirmed-action-runtime.test.ts@@ -125,7 +125,6 @@ describe('executeConfirmedAction', () => {incomingArgs: {[CONFIRMATION_HASH_ARG]: hash,[CONFIRMATION_WORD_ARG]: 'confirm',- orgId: 'acme',},purpose: 'enforce-2fa',codec,@@ -186,14 +185,14 @@ describe('executeConfirmedAction', () => {const { codec, ledger } = setup()const hash = await mintToken(codec, 'did-1', 'p', { orgId: 'x' })const first = await executeConfirmedAction(makeContext('did-1'), {- incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', orgId: 'x' },+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'p',codec,ledger,})expect(first.ok).toBe(true)const second = await executeConfirmedAction(makeContext('did-1'), {- incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', orgId: 'x' },+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'p',codec,ledger,@@ -204,6 +203,61 @@ describe('executeConfirmedAction', () => {}})+ it('refuses when the active scope no longer matches the scope bound at prepare time', async () => {+ // Cross-project replay: prepare while project A is active, then run+ // execute after switch-project made B active. The signed scope (A)+ // must not authorize the action against B.+ const { codec, ledger } = setup()+ const prep = await prepareConfirmedAction(makeContext('did-1'), {+ args: { name: 'mrr' },+ purpose: 'metric-approve',+ actionLabel: 'approve metric',+ messageTemplate: 'msg',+ codec,+ boundScope: { projectId: '1' },+ })+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: {+ [CONFIRMATION_HASH_ARG]: prep.confirmation_hash,+ [CONFIRMATION_WORD_ARG]: 'confirm',+ },+ purpose: 'metric-approve',+ codec,+ ledger,+ expectedScope: { projectId: '2' },+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('different project or organization')+ }+ })++ it('succeeds when the active scope still matches the scope bound at prepare time', async () => {+ const { codec, ledger } = setup()+ const prep = await prepareConfirmedAction(makeContext('did-1'), {+ args: { name: 'mrr' },+ purpose: 'metric-approve',+ actionLabel: 'approve metric',+ messageTemplate: 'msg',+ codec,+ boundScope: { projectId: '1' },+ })+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: {+ [CONFIRMATION_HASH_ARG]: prep.confirmation_hash,+ [CONFIRMATION_WORD_ARG]: 'confirm',+ },+ purpose: 'metric-approve',+ codec,+ ledger,+ expectedScope: { projectId: '1' },+ })+ expect(outcome.ok).toBe(true)+ if (outcome.ok) {+ expect(outcome.verifiedArgs).toEqual({ name: 'mrr' })+ }+ })+it('refuses on tampered signature', async () => {const { codec, ledger } = setup()const hash = await mintToken(codec, 'did-1', 'p', {})@@ -238,7 +292,7 @@ describe('executeConfirmedAction', () => {})const hash = await mintToken(codec, 'did-1', 'tool-A', { x: 1 })const outcome = await executeConfirmedAction(makeContext('did-1'), {- incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', x: 1 },+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'tool-A',codec,ledger,@@ -311,7 +365,6 @@ describe('confirmed-action metrics', () => {incomingArgs: {[CONFIRMATION_HASH_ARG]: prep.confirmation_hash,[CONFIRMATION_WORD_ARG]: 'confirm',- id: 'x',},purpose: 'tool-B',codec,diff --git a/services/mcp/tests/unit/data-catalog-confirmed-action.test.ts b/services/mcp/tests/unit/data-catalog-confirmed-action.test.tsnew file mode 100644index 000000000000..8ff2ac0c6099--- /dev/null+++ b/services/mcp/tests/unit/data-catalog-confirmed-action.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'++import { GENERATED_TOOLS } from '@/tools/generated/data_catalog'++describe('data catalog confirmed actions', () => {+ it('accepts only confirmation fields when executing a signed rejection', () => {+ const executeSchema = GENERATED_TOOLS['data-catalog-relationship-reject-execute']!().schema+ const confirmation = {+ confirmation_hash: 'signed-token',+ confirmation: 'confirm',+ }++ expect(executeSchema.safeParse(confirmation).success).toBe(true)+ expect(+ executeSchema.safeParse({+ ...confirmation,+ id: 'proposal-id',+ rejection_reason: 'duplicate relationship',+ }).success+ ).toBe(false)+ })+})diff --git a/services/mcp/tests/unit/dev-hono-env.test.ts b/services/mcp/tests/unit/dev-hono-env.test.tsnew file mode 100644index 000000000000..3175d85eb546--- /dev/null+++ b/services/mcp/tests/unit/dev-hono-env.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest'++import { createDevHonoChildEnv } from '../../scripts/dev-hono-env'++describe('createDevHonoChildEnv', () => {+ it.each([+ [{ API_URL: 'http://localhost:8000' }, 'development'],+ [{ API_URL: 'http://localhost:8000', NODE_ENV: 'production' }, 'production'],+ ])('sets the expected runtime environment for %o', (parentEnv, expectedNodeEnv) => {+ expect(createDevHonoChildEnv(parentEnv).NODE_ENV).toBe(expectedNodeEnv)+ })+})diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex 0fcf689647b7..6ec58dc0b885 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -1765,6 +1765,18 @@ describe('ToolConfigSchema confirmed_action', () => {}})+ it('rejects confirmed_action combined with a whole-tool input_schema', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ input_schema: 'OrganizationUpdateSchema',+ confirmed_action: { message: 'x' },+ })+ expect(result.success).toBe(false)+ if (!result.success) {+ expect(result.error.issues[0]!.message).toContain('input_schema')+ }+ })+it('rejects unknown keys inside the confirmed_action object', () => {const result = ToolConfigSchema.safeParse({...base,@@ -1815,7 +1827,7 @@ describe('generateToolCode with confirmed_action', () => {expect(result.code).not.toMatch(/const organizationEnforce2faUpdate\s*=/)})- it('extends the base schema for the execute variant with confirmation fields', () => {+ it('emits a strict confirmation-only schema for the execute variant', () => {const result = generateToolCode('organization-enforce-2fa-update',makeConfirmedConfig(),@@ -1826,7 +1838,8 @@ describe('generateToolCode with confirmed_action', () => {stubGetQuerySchema)expect(result.code).toContain('OrganizationEnforce2faUpdateSchemaExecute')- expect(result.code).toContain('.extend({')+ expect(result.code).toContain('z.strictObject({')+ expect(result.code).not.toContain('OrganizationEnforce2faUpdateSchema.extend({')expect(result.code).toContain('confirmation_hash')expect(result.code).toContain('confirmation:')})@@ -1864,12 +1877,7 @@ describe('generateToolCode with confirmed_action', () => {expect(result.code).toContain("method: 'PATCH'")})- it('REPLACES params with verifiedArgs (never merges) so unsigned extras cannot survive', () => {- // The generated handler must not preserve incoming params alongside- // verifiedArgs — only the signed payload is authorized. A merge- // would let the model slip an unsigned base-schema field (e.g. an- // extra 'name') into the downstream API body without it ever being- // shown to the user at prepare time.+ it('uses only verifiedArgs as the downstream action params', () => {const result = generateToolCode('organization-enforce-2fa-update',makeConfirmedConfig(),@@ -1879,8 +1887,8 @@ describe('generateToolCode with confirmed_action', () => {new Set<string>(),stubGetQuerySchema)- expect(result.code).toContain('params = { ...__guard.verifiedArgs }')- expect(result.code).not.toMatch(/params\s*=\s*\{\s*\.\.\.params\s*,\s*\.\.\.__guard\.verifiedArgs/)+ expect(result.code).toContain('const params = __guard.verifiedArgs')+ expect(result.code).toContain('incomingArgs: confirmationParams')})it('uses the tool title as the fallback action_label when none is set', () => {@@ -1900,6 +1908,65 @@ describe('generateToolCode with confirmed_action', () => {)expect(result.code).toContain('actionLabel: "Enforce 2FA"')})++ it('binds the active project scope into prepare and re-checks it in execute (cross-project replay guard)', () => {+ // A project-scoped confirmed action must sign the active project at+ // prepare time (boundScope) and re-verify it at execute time+ // (expectedScope). Without this, a confirmation prepared while one+ // project was active could be replayed against another after+ // switch-project.+ const result = generateToolCode(+ 'metric-approve',+ makeConfirmedConfig(),+ makeResolved({+ method: 'POST',+ path: '/api/projects/{project_id}/metrics/{name}/approve/',+ operation: {+ operationId: 'organizations_partial_update',+ parameters: [+ { in: 'path', name: 'project_id', required: true, schema: { type: 'string' } },+ { in: 'path', name: 'name', required: true, schema: { type: 'string' } },+ ],+ },+ }),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('boundScope: { projectId: String(__scopeProjectId) }')+ expect(result.code).toContain('expectedScope: { projectId: String(__scopeProjectId) }')+ })++ it('reuses the scope-checked project id to build the execute path (no post-guard re-read)', () => {+ // The path must be built from the same project id that was verified+ // against expectedScope. Re-reading state after the guard would let a+ // concurrent switch-project retarget the request at a different+ // project than the confirmation was bound to.+ const result = generateToolCode(+ 'metric-approve',+ makeConfirmedConfig(),+ makeResolved({+ method: 'POST',+ path: '/api/projects/{project_id}/metrics/{name}/approve/',+ operation: {+ operationId: 'organizations_partial_update',+ parameters: [+ { in: 'path', name: 'project_id', required: true, schema: { type: 'string' } },+ { in: 'path', name: 'name', required: true, schema: { type: 'string' } },+ ],+ },+ }),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('const projectId = __scopeProjectId')+ expect(result.code).not.toContain(+ 'const params = __guard.verifiedArgs\n const projectId = await context.stateManager.getProjectId()'+ )+ })})describe('optional param with state fallback', () => {diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 5e1d972bb23f..105843cc9545 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -817,9 +817,10 @@ describe('Tool Filtering - Feature Flags', () => {'endpoints-ai-materialization-fix','engineering-analytics','stamphog',+ 'product-data-catalog',]))- expect(flags).toHaveLength(21)+ expect(flags).toHaveLength(22)})// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries