Skip to content

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

feat(streamlit-apps): MCP tools + single-file source endpoint (#63012)

Jovan Sakovicdf5d2cd6d2f6
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.ts
index 4124bbd17ebc..ce98ae8e1fd7 100644
--- a/frontend/src/lib/agentScopes.generated.ts
+++ b/frontend/src/lib/agentScopes.generated.ts
@@ -108,6 +108,8 @@ export const AGENT_USE_CASE_SCOPES = [
'signal_scout:write',
'stamphog:read',
'stamphog:write',
+ 'streamlit_app:read',
+ 'streamlit_app:write',
'subscription:read',
'subscription:write',
'survey:read',
diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.py
index c1e3f596fda8..23ffe42ebfbf 100644
--- a/products/streamlit_apps/backend/facade/api.py
+++ b/products/streamlit_apps/backend/facade/api.py
@@ -23,7 +23,7 @@ from products.streamlit_apps.backend.logic.oauth import (
find_reusable_streamlit_access_token,
get_streamlit_oauth_app,
)
-from products.streamlit_apps.backend.logic.zip_validator import MAX_ZIP_SIZE, validate_zip
+from products.streamlit_apps.backend.logic.zip_validator import MAX_ZIP_SIZE, build_single_file_zip, validate_zip
from products.streamlit_apps.backend.models import (
MAX_CPU_CORES,
MAX_MEMORY_GB,
@@ -70,6 +70,7 @@ __all__ = [
"delete_app",
"list_versions",
"upload_version",
+ "create_version_from_source",
"activate_version",
"get_status",
"start_app",
@@ -432,6 +433,30 @@ def upload_version(
return _version_to_contract(version)
+def create_version_from_source(
+ team_id: int,
+ short_id: str,
+ user: User,
+ data: contracts.CreateVersionFromSourceInput,
+ was_impersonated: bool,
+) -> contracts.AppVersionContract:
+ """Create and activate a version from a single free-text app.py source string.
+
+ Packs the source into the same zip shape as an upload, so validation,
+ storage, versioning, and sandbox-stop semantics are identical to
+ ``upload_version``.
+ """
+ file_content = build_single_file_zip(data.source)
+ return upload_version(
+ team_id=team_id,
+ short_id=short_id,
+ user=user,
+ file_content=file_content,
+ declared_size=len(file_content),
+ was_impersonated=was_impersonated,
+ )
+
+
def activate_version(
team_id: int, short_id: str, user: User, version_number: int, was_impersonated: bool
) -> contracts.AppVersionContract:
diff --git a/products/streamlit_apps/backend/facade/contracts.py b/products/streamlit_apps/backend/facade/contracts.py
index 08d3d90920bd..6fdfafb1aafb 100644
--- a/products/streamlit_apps/backend/facade/contracts.py
+++ b/products/streamlit_apps/backend/facade/contracts.py
@@ -102,6 +102,11 @@ class CreateAppInput:
memory_gb: float = 1
+@dataclass(frozen=True)
+class CreateVersionFromSourceInput:
+ source: str
+
+
@dataclass(frozen=True)
class UpdateAppInput:
name: str | None = None
diff --git a/products/streamlit_apps/backend/logic/app_runtime.py b/products/streamlit_apps/backend/logic/app_runtime.py
index f4729ea6fa90..8b0a23540abd 100644
--- a/products/streamlit_apps/backend/logic/app_runtime.py
+++ b/products/streamlit_apps/backend/logic/app_runtime.py
@@ -341,6 +341,14 @@ class AppRuntimeService:
version = app.active_version
if version is None:
raise AppRuntimeError("App has no active version")
+ # The bridge runs the app's HogQL as the author of the code that is about to
+ # execute — not the app's creator, or a member who can only edit apps would
+ # inherit the creator's warehouse access. Checked before any sandbox is built:
+ # a deleted author is a deterministic no-start, not a provision-then-fail.
+ if version.created_by is None:
+ raise AppRuntimeError(
+ "The author of this app's active version no longer exists. Upload a new version to run it."
+ )
with transaction.atomic():
existing = StreamlitAppSandbox.objects.select_for_update().filter(app=app).first()
@@ -390,7 +398,7 @@ class AppRuntimeService:
version.save(update_fields=["snapshot_id", "snapshot_created_at"])
# Write before the proxy boots so it can read+unlink the file.
- bridge_token = create_sandbox_bridge_token(user=app.created_by, team_id=app.team_id)
+ bridge_token = create_sandbox_bridge_token(user=version.created_by, team_id=app.team_id)
_write_bridge_token(sandbox, bridge_token)
_start_auth_proxy(sandbox)
@@ -471,7 +479,10 @@ class AppRuntimeService:
if destroy_error is None:
sandbox_record.status = StreamlitAppSandbox.Status.STOPPED
- sandbox_record.save(update_fields=["status"])
+ # Clear the TTL marker too: auto_restart_crashed_streamlit_sandboxes matches
+ # on it, so a deliberate stop of a TTL-expired sandbox would be undone.
+ sandbox_record.last_error = ""
+ sandbox_record.save(update_fields=["status", "last_error"])
else:
# Modal may still be running; TTL or cleanup will reclaim it.
sandbox_record.status = StreamlitAppSandbox.Status.ERROR
diff --git a/products/streamlit_apps/backend/logic/bridge.py b/products/streamlit_apps/backend/logic/bridge.py
index 7f249cc9ee35..92e32f31a73a 100644
--- a/products/streamlit_apps/backend/logic/bridge.py
+++ b/products/streamlit_apps/backend/logic/bridge.py
@@ -1,12 +1,16 @@
from __future__ import annotations
import logging
+from typing import TYPE_CHECKING
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.query import execute_hogql_query
from posthog.models import Team
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
logger = logging.getLogger(__name__)
# Tighter than HogQL defaults so a misbehaving sandbox can't exhaust a query node.
@@ -15,7 +19,7 @@ BRIDGE_MAX_MEMORY_USAGE_BYTES = 256 * 1024 * 1024 # 256 MB
BRIDGE_MAX_BYTES_TO_READ = 5 * 1024 * 1024 * 1024 # 5 GB
-def execute_bridge_query(query: str, team_id: int, client_query_id: str | None = None) -> dict:
+def execute_bridge_query(query: str, team_id: int, user: User | None, client_query_id: str | None = None) -> dict:
from posthog.clickhouse.query_tagging import tag_queries
team = Team.objects.get(id=team_id)
@@ -24,9 +28,13 @@ def execute_bridge_query(query: str, team_id: int, client_query_id: str | None =
team_id=team_id,
client_query_id=client_query_id or "",
)
+ # The bridge token's minting user carries the access-control context: warehouse
+ # table/view ACLs fail closed without a user, so a userless run would deny every
+ # warehouse table — and running as anyone broader would bypass table-level RBAC.
response = execute_hogql_query(
query=query,
team=team,
+ user=user,
limit_context=LimitContext.POSTHOG_AI,
settings=HogQLGlobalSettings(
max_execution_time=BRIDGE_MAX_EXECUTION_TIME_SECONDS,
diff --git a/products/streamlit_apps/backend/logic/zip_validator.py b/products/streamlit_apps/backend/logic/zip_validator.py
index eb2e60cdecae..3a281e9f0d6d 100644
--- a/products/streamlit_apps/backend/logic/zip_validator.py
+++ b/products/streamlit_apps/backend/logic/zip_validator.py
@@ -14,6 +14,19 @@ def _format_mb(size_bytes: int) -> str:
return f"{size_bytes / (1024 * 1024):.1f} MB"
+def build_single_file_zip(source: str) -> bytes:
+ """Pack a single-file Streamlit app (free-text ``app.py``) into a zip.
+
+ Lets agents create an app from one block of source instead of uploading a
+ zip. The result still flows through ``validate_zip`` and the same storage
+ path, so size/structure guarantees are identical to an uploaded zip.
+ """
+ buf = BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr("app.py", source)
+ return buf.getvalue()
+
+
def is_safe_zip_path(filename: str) -> bool:
"""Check if a zip entry filename is safe (no path traversal)."""
normalized = os.path.normpath(filename)
diff --git a/products/streamlit_apps/backend/presentation/bridge_views.py b/products/streamlit_apps/backend/presentation/bridge_views.py
index 2c3f7db53509..b90ce42a751a 100644
--- a/products/streamlit_apps/backend/presentation/bridge_views.py
+++ b/products/streamlit_apps/backend/presentation/bridge_views.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import hashlib
import logging
+from typing import TYPE_CHECKING
from django.utils import timezone
@@ -18,6 +19,9 @@ from posthog.rate_limit import PersonalApiKeyRateThrottle
from products.streamlit_apps.backend.facade.api import execute_bridge_query, get_streamlit_oauth_app
from products.streamlit_apps.backend.presentation.serializers import streamlit_apps_flag_enabled
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
logger = logging.getLogger(__name__)
BRIDGE_REQUEST_MAX_BYTES = 16 * 1024
@@ -60,8 +64,8 @@ class StreamlitBridgeIPThrottle(PersonalApiKeyRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": self.get_ident(request)}
-def _authenticate_bearer(auth_header: str) -> tuple[int | None, str | None, str | None]:
- """Validate a bridge bearer token; returns (team_id, user_distinct_id, error).
+def _authenticate_bearer(auth_header: str) -> tuple[int | None, User | None, str | None]:
+ """Validate a bridge bearer token; returns (team_id, minting_user, error).
Kept as an in-view helper rather than a DRF BaseAuthentication class on purpose:
this is a single first-party endpoint with bespoke checks (single-team scope,
@@ -105,7 +109,7 @@ def _authenticate_bearer(auth_header: str) -> tuple[int | None, str | None, str
if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
return None, None, "Token user is not a member of the team's organization."
- return team_id, user.distinct_id, None
+ return team_id, user, None
def _streamlit_apps_enabled_for_team(team_id: int, user_distinct_id: str | None) -> bool:
@@ -127,13 +131,13 @@ class StreamlitBridgeView(APIView):
if not auth_header.startswith("Bearer "):
return Response({"error": "Missing or invalid Authorization header."}, status=401)
- team_id, user_distinct_id, error = _authenticate_bearer(auth_header)
+ team_id, token_user, error = _authenticate_bearer(auth_header)
if team_id is None:
return Response({"error": error}, status=401)
# Same gate as the viewset: a bridge token outlives a flag rollback,
# so the flag must be re-checked here, not just at token mint time.
- if not _streamlit_apps_enabled_for_team(team_id, user_distinct_id):
+ if not _streamlit_apps_enabled_for_team(team_id, token_user.distinct_id if token_user else None):
return Response({"error": "Streamlit apps is not available."}, status=403)
if len(request.body) > BRIDGE_REQUEST_MAX_BYTES:
@@ -149,7 +153,7 @@ class StreamlitBridgeView(APIView):
return Response({"error": "Missing or empty 'query' field."}, status=400)
try:
- result = execute_bridge_query(query=query, team_id=team_id)
+ result = execute_bridge_query(query=query, team_id=team_id, user=token_user)
return Response(result)
except Exception:
logger.exception(
diff --git a/products/streamlit_apps/backend/presentation/serializers.py b/products/streamlit_apps/backend/presentation/serializers.py
index 7f7325f9868e..250e21285771 100644
--- a/products/streamlit_apps/backend/presentation/serializers.py
+++ b/products/streamlit_apps/backend/presentation/serializers.py
@@ -13,6 +13,7 @@ from products.streamlit_apps.backend.facade.contracts import (
AppSandboxContract,
AppVersionContract,
CreateAppInput,
+ CreateVersionFromSourceInput,
StreamlitAppUserInfo,
UpdateAppInput,
)
@@ -90,6 +91,32 @@ class UpdateAppInputSerializer(DataclassSerializer):
dataclass = UpdateAppInput
+class CreateVersionFromSourceInputSerializer(DataclassSerializer):
+ # "source" is the natural API field name; it shadows DRF's Field.source attribute
+ # only in the eyes of mypy — DRF handles same-named declared fields fine.
+ source = serializers.CharField( # type: ignore[assignment]
+ trim_whitespace=False,
+ # Bounds the JSON body before any zip is built; the multipart path gets the
+ # same protection from the declared-size check against MAX_ZIP_SIZE.
+ max_length=1024 * 1024,
+ help_text=(
+ "Full Python source for the Streamlit app's root app.py file, as free text (max 1 MB). "
+ "Becomes a new version and is set as the active version."
+ ),
+ )
+
+ def validate_source(self, value: str) -> str:
+ # allow_blank already rejects "", but trim_whitespace=False (needed to preserve
+ # indentation) would otherwise let whitespace-only source through and serve a
+ # blank app with no error anywhere.
+ if not value.strip():
+ raise serializers.ValidationError("Source cannot be empty.")
+ return value
+
+ class Meta:
+ dataclass = CreateVersionFromSourceInput
+
+
class StreamlitAppStatusSerializer(serializers.Serializer):
status = serializers.CharField(help_text="Sandbox lifecycle status, or 'stopped' when no sandbox exists.")
restart_count = serializers.IntegerField(help_text="Number of times the app's sandbox has been restarted.")
diff --git a/products/streamlit_apps/backend/presentation/views.py b/products/streamlit_apps/backend/presentation/views.py
index 3851ffdad1e8..1537897f29b9 100644
--- a/products/streamlit_apps/backend/presentation/views.py
+++ b/products/streamlit_apps/backend/presentation/views.py
@@ -16,11 +16,16 @@ from posthog.models.user import User
from posthog.rate_limit import ClickHouseBurstRateThrottle
from products.streamlit_apps.backend.facade import api
-from products.streamlit_apps.backend.facade.contracts import CreateAppInput, UpdateAppInput
+from products.streamlit_apps.backend.facade.contracts import (
+ CreateAppInput,
+ CreateVersionFromSourceInput,
+ UpdateAppInput,
+)
from products.streamlit_apps.backend.presentation.serializers import (
ActivateVersionRequestSerializer,
ActivateVersionResponseSerializer,
CreateAppInputSerializer,
+ CreateVersionFromSourceInputSerializer,
StreamlitAppMinimalSerializer,
StreamlitAppsAccessPermission,
StreamlitAppSandboxSerializer,
@@ -37,12 +42,47 @@ logger = structlog.get_logger(__name__)
_STATUS_CACHE_TTL_SECONDS = 2
+# Actions that let a token ship app code, choose which code runs, or make it run.
+# The sandbox bridge executes the active version's HogQL as that version's author,
+# so tokens driving these paths must themselves hold query:read — otherwise a
+# streamlit_app-only key escalates to HogQL reads through code it uploads, or by
+# activating a version authored by someone with broader access. activate_version
+# counts without an explicit start of its own: the next start by anyone, or a live
+# sandbox its best-effort stop failed to reclaim, runs the newly activated code.
+_QUERY_CAPABLE_WRITE_ACTIONS = frozenset(
+ {"upload_version", "create_version_from_source", "activate_version", "start", "restart"}
+)
+
class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "streamlit_app"
+ # Custom actions are invisible to the default CRUD scope derivation, so
+ # without these lists personal-API-key (and MCP) calls to them are refused.
+ scope_object_read_actions = ["list", "retrieve", "versions", "get_status", "connect_info"]
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "destroy",
+ "upload_version",
+ "create_version_from_source",
+ "activate_version",
+ "start",
+ "stop",
+ "restart",
+ ]
permission_classes = [StreamlitAppsAccessPermission]
lookup_field = "short_id"
+ def dangerously_get_required_scopes(self, request: Request, view: "StreamlitAppViewSet") -> list[str] | None:
+ action = getattr(view, "action", None)
+ if action in _QUERY_CAPABLE_WRITE_ACTIONS:
+ return ["streamlit_app:write", "query:read"]
+ if action == "connect_info":
+ # The iframe renders whatever the app queried — reading it is reading query results.
+ return ["streamlit_app:read", "query:read"]
+ return None
+
@extend_schema(summary="List streamlit apps", responses={200: StreamlitAppMinimalSerializer(many=True)})
def list(self, request: Request, **kwargs: Any) -> Response:
apps = api.list_apps(self.team_id)
@@ -137,7 +177,7 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
request=UploadVersionRequestSerializer,
responses={201: StreamlitAppVersionSerializer},
)
- @action(methods=["POST"], detail=True, url_path="upload_version")
+ @action(methods=["POST"], detail=True, url_path="upload_version", throttle_classes=[ClickHouseBurstRateThrottle])
def upload_version(self, request: Request, short_id: str, **kwargs: Any) -> Response:
zip_file = request.FILES.get("file")
if not zip_file:
@@ -172,6 +212,37 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(StreamlitAppVersionSerializer(version).data, status=status.HTTP_201_CREATED)
+ @validated_request(
+ request_serializer=CreateVersionFromSourceInputSerializer,
+ summary="Create an app version from source code",
+ responses={201: OpenApiResponse(response=StreamlitAppVersionSerializer)},
+ )
+ @action(
+ methods=["POST"],
+ detail=True,
+ url_path="create_version_from_source",
+ throttle_classes=[ClickHouseBurstRateThrottle],
+ )
+ def create_version_from_source(
+ self, request: TypedRequest[CreateVersionFromSourceInput], short_id: str, **kwargs: Any
+ ) -> Response:
+ try:
+ version = api.create_version_from_source(
+ team_id=self.team_id,
+ short_id=short_id,
+ user=cast(User, request.user),
+ data=request.validated_data,
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.InvalidZipError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ except api.ConcurrentUploadError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_409_CONFLICT)
+
+ return Response(StreamlitAppVersionSerializer(version).data, status=status.HTTP_201_CREATED)
+
@extend_schema(
summary="Activate an existing app version",
request=ActivateVersionRequestSerializer,
diff --git a/products/streamlit_apps/backend/tests/test_app_runtime.py b/products/streamlit_apps/backend/tests/test_app_runtime.py
index e34a990f9d5e..7899dc7a1559 100644
--- a/products/streamlit_apps/backend/tests/test_app_runtime.py
+++ b/products/streamlit_apps/backend/tests/test_app_runtime.py
@@ -10,6 +10,8 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.models.user import User
+
from products.streamlit_apps.backend.logic.app_runtime import (
MAX_RESTART_COUNT,
RESTART_COUNT_STABILITY_SECONDS,
@@ -38,6 +40,9 @@ def _make_mock_sandbox():
return sandbox
+_UNSET = object()
+
+
def _make_mock_sandbox_class(sandbox=None):
if sandbox is None:
sandbox = _make_mock_sandbox()
@@ -50,7 +55,7 @@ def _make_mock_sandbox_class(sandbox=None):
@patch("products.streamlit_apps.backend.logic.app_runtime._wait_for_health", return_value=True)
@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
class TestAppRuntimeStartApp(BaseTest):
- def _create_app_with_version(self, snapshot_id=None):
+ def _create_app_with_version(self, snapshot_id=None, version_author=_UNSET):
app = StreamlitApp.objects.create(team=self.team, name="Test App", created_by=self.user)
version = StreamlitAppVersion.objects.create(
app=app,
@@ -58,6 +63,7 @@ class TestAppRuntimeStartApp(BaseTest):
zip_file="s3://bucket/app.zip",
zip_hash="abc123",
snapshot_id=snapshot_id,
+ created_by=version_author if version_author is not _UNSET else self.user,
)
app.active_version = version
app.save(update_fields=["active_version"])
@@ -89,6 +95,31 @@ class TestAppRuntimeStartApp(BaseTest):
assert snapshot.external_id == "snapshot-abc"
assert snapshot.status == tasks_facade.SandboxSnapshotStatus.COMPLETE
+ @patch("products.streamlit_apps.backend.logic.app_runtime.create_sandbox_bridge_token")
+ def test_bridge_token_is_minted_for_the_active_version_author(self, mock_mint, mock_get_sandbox_class, _mock_wait):
+ """The bridge runs the app's HogQL as this user, so it must be the author of
+ the running code — minting for the app creator would let anyone who can edit
+ an app inherit the creator's warehouse access."""
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class()
+ mock_mint.return_value = "tok"
+
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "pw")
+ app, _version = self._create_app_with_version(version_author=other_user)
+
+ AppRuntimeService().start_app(app, zip_content=_make_zip_bytes({"app.py": "pass"}))
+
+ assert mock_mint.call_args.kwargs["user"] == other_user
+
+ def test_start_refuses_when_active_version_author_is_gone(self, mock_get_sandbox_class, _mock_wait):
+ """created_by is SET_NULL, and a userless bridge token is rejected on every
+ query — so a null author must fail the start loudly instead of booting an app
+ whose queries all fail."""
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class()
+ app, _version = self._create_app_with_version(version_author=None)
+
+ with self.assertRaises(AppRuntimeError):
+ AppRuntimeService().start_app(app, zip_content=_make_zip_bytes({"app.py": "pass"}))
+
def test_cold_start_ignores_requirements_txt_in_zip(self, mock_get_sandbox_class, _mock_wait):
"""requirements.txt support was deleted: a zip with one is accepted but
we never run `pip install` and the file is dropped on the way to the
@@ -314,6 +345,7 @@ class TestAppRuntimeRestartApp(BaseTest):
zip_file="a.zip",
zip_hash="a",
snapshot_id="snap",
+ created_by=self.user,
)
app.active_version = version
app.save(update_fields=["active_version"])
diff --git a/products/streamlit_apps/backend/tests/test_bridge.py b/products/streamlit_apps/backend/tests/test_bridge.py
index e285b7594163..0ebd248093ca 100644
--- a/products/streamlit_apps/backend/tests/test_bridge.py
+++ b/products/streamlit_apps/backend/tests/test_bridge.py
@@ -27,7 +27,7 @@ class TestExecuteBridgeQuery(BaseTest):
clickhouse="SELECT ...",
)
- result = execute_bridge_query(query="SELECT 1", team_id=self.team.id)
+ result = execute_bridge_query(query="SELECT 1", team_id=self.team.id, user=self.user)
assert set(result.keys()) == {"columns", "results", "types"}
assert result["results"] == [[1, "hello"]]
@@ -38,16 +38,19 @@ class TestExecuteBridgeQuery(BaseTest):
def test_passes_query_and_team(self, mock_execute):
mock_execute.return_value = HogQLQueryResponse(results=[], columns=[])
- execute_bridge_query(query="SELECT event FROM events", team_id=self.team.id)
+ execute_bridge_query(query="SELECT event FROM events", team_id=self.team.id, user=self.user)
mock_execute.assert_called_once()
call_kwargs = mock_execute.call_args
assert call_kwargs.kwargs["query"] == "SELECT event FROM events"
assert call_kwargs.kwargs["team"].id == self.team.id
+ # Warehouse table/view ACLs fail closed without a user, so the minting
+ # user must reach HogQL execution for table-level RBAC to apply.
+ assert call_kwargs.kwargs["user"] == self.user
def test_invalid_team_raises(self):
with pytest.raises(Exception):
- execute_bridge_query(query="SELECT 1", team_id=999999)
+ execute_bridge_query(query="SELECT 1", team_id=999999, user=self.user)
class TestStreamlitBridgeView(_StreamlitAppsFlagMixin, APIBaseTest):
@@ -171,6 +174,9 @@ class TestStreamlitBridgeView(_StreamlitAppsFlagMixin, APIBaseTest):
assert data["results"] == [[1, "test"]]
assert data["columns"] == ["id", "name"]
assert "clickhouse" not in data
+ # End-to-end wiring guard: the token's minting user must reach HogQL
+ # execution, else warehouse ACLs fail closed and deny every warehouse table.
+ assert mock_execute.call_args.kwargs["user"] == self.user
@patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
def test_query_execution_error_returns_400(self, mock_execute):
diff --git a/products/streamlit_apps/backend/tests/test_presentation.py b/products/streamlit_apps/backend/tests/test_presentation.py
index 2586df5f0eb2..4e6e97dfba10 100644
--- a/products/streamlit_apps/backend/tests/test_presentation.py
+++ b/products/streamlit_apps/backend/tests/test_presentation.py
@@ -680,3 +680,122 @@ class TestStreamlitAppSandboxControlAPI(_StreamlitAppsFlagMixin, APIBaseTest):
second_count = OAuthAccessToken.objects.filter(user=self.user).count()
assert first_count == second_count, "expected token reuse, but a new token was minted"
+
+
+class TestCreateVersionFromSource(_StreamlitAppsFlagMixin, APIBaseTest):
+ def _url(self, short_id: str, suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/streamlit_apps/{short_id}"
+ return f"{base}/{suffix}" if suffix else f"{base}/"
+
+ def _create_app(self, **kwargs) -> StreamlitApp:
+ defaults = {"team": self.team, "name": "Source App", "created_by": self.user}
+ defaults.update(kwargs)
+ return StreamlitApp.objects.create(**defaults)
+
+ @patch("posthog.storage.object_storage.write")
+ def test_create_version_from_source(self, mock_storage_write):
+ app = self._create_app()
+ source = "import streamlit as st\nst.title('Hi')"
+ response = self.client.post(
+ self._url(app.short_id, "create_version_from_source/"),
+ data={"source": source},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["version_number"] == 1
+ mock_storage_write.assert_called_once()
+
+ # The stored object must be a valid zip with the source at app.py in the root.
+ stored_bytes = mock_storage_write.call_args[0][1]
+ with zipfile.ZipFile(io.BytesIO(stored_bytes)) as zf:
+ assert zf.read("app.py").decode() == source
+
+ app.refresh_from_db()
+ assert app.active_version_id == uuid.UUID(response.json()["id"])
+
+ @parameterized.expand([("missing", {}), ("blank", {"source": ""}), ("whitespace_only", {"source": " \n "})])
+ def test_create_version_from_source_rejects_empty_source(self, _name, payload):
+ app = self._create_app()
+ response = self.client.post(self._url(app.short_id, "create_version_from_source/"), data=payload, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestStreamlitAppPersonalAPIKeyAccess(_StreamlitAppsFlagMixin, APIBaseTest):
+ """Custom actions are invisible to the default CRUD scope derivation; these
+ guard the explicit scope_object_*_actions lists that make PAK/MCP calls work,
+ and the query:read requirement on code-shipping/executing actions (the sandbox
+ bridge runs HogQL, so a streamlit_app-only key must not reach it)."""
+
+ def _make_key(self, label: str, scopes: list[str]) -> str:
+ from posthog.models.personal_api_key import PersonalAPIKey
+ from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label=label, user=self.user, secure_value=hash_key_value(raw), scopes=scopes)
+ return raw
+
+ def setUp(self):
+ super().setUp()
+ self._write_query_key = self._make_key("streamlit-write-query", ["streamlit_app:write", "query:read"])
+ self._write_only_key = self._make_key("streamlit-write-only", ["streamlit_app:write"])
+ self._read_key = self._make_key("streamlit-read", ["streamlit_app:read"])
+ self.client.logout()
+
+ def _url(self, short_id: str = "", suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/streamlit_apps"
+ if short_id:
+ base = f"{base}/{short_id}"
+ return f"{base}/{suffix}" if suffix else f"{base}/"
+
+ def _auth(self, key: str) -> dict:
+ return {"HTTP_AUTHORIZATION": f"Bearer {key}"}
+
+ @patch("posthog.storage.object_storage.write")
+ def test_set_source_allowed_with_write_and_query_scopes(self, _mock_storage_write):
+ app = StreamlitApp.objects.create(team=self.team, name="PAK App", created_by=self.user)
+ response = self.client.post(
+ self._url(app.short_id, "create_version_from_source/"),
+ data={"source": "import streamlit as st"},
+ format="json",
+ **self._auth(self._write_query_key),
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+
+ @parameterized.expand(["create_version_from_source", "activate_version", "start", "restart"])
+ def test_code_executing_actions_refused_without_query_read(self, action: str):
+ app = StreamlitApp.objects.create(team=self.team, name="PAK App", created_by=self.user)
+ response = self.client.post(
+ self._url(app.short_id, f"{action}/"),
+ data={"source": "import streamlit as st"},
+ format="json",
+ **self._auth(self._write_only_key),
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert "query:read" in response.json()["detail"]
+
+ def test_set_source_refused_with_read_scope(self):
+ app = StreamlitApp.objects.create(team=self.team, name="PAK App", created_by=self.user)
+ response = self.client.post(
+ self._url(app.short_id, "create_version_from_source/"),
+ data={"source": "import streamlit as st"},
+ format="json",
+ **self._auth(self._read_key),
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_non_query_custom_action_allowed_with_write_only_scope(self):
+ """`stop` ships no code and runs none, so it stays streamlit-scoped only —
+ and unlike partial_update it is a custom action, so dropping it from
+ scope_object_write_actions would refuse every key with no other test noticing."""
+ app = StreamlitApp.objects.create(team=self.team, name="PAK App", created_by=self.user)
+ response = self.client.post(
+ self._url(app.short_id, "stop/"),
+ format="json",
+ **self._auth(self._write_only_key),
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ def test_custom_read_action_allowed_with_read_scope(self):
+ app = StreamlitApp.objects.create(team=self.team, name="PAK App", created_by=self.user)
+ response = self.client.get(self._url(app.short_id, "versions/"), **self._auth(self._read_key))
+ assert response.status_code == status.HTTP_200_OK
diff --git a/products/streamlit_apps/frontend/generated/api.schemas.ts b/products/streamlit_apps/frontend/generated/api.schemas.ts
index dda4b8a3c3e1..d4b2b93555c6 100644
--- a/products/streamlit_apps/frontend/generated/api.schemas.ts
+++ b/products/streamlit_apps/frontend/generated/api.schemas.ts
@@ -142,6 +142,14 @@ export interface StreamlitConnectInfoApi {
expires_in: number
}
+export interface CreateVersionFromSourceInputApi {
+ /**
+ * Full Python source for the Streamlit app's root app.py file, as free text (max 1 MB). Becomes a new version and is set as the active version.
+ * @maxLength 1048576
+ */
+ source: string
+}
+
export interface StreamlitAppStatusApi {
/** Sandbox lifecycle status, or 'stopped' when no sandbox exists. */
status: string
diff --git a/products/streamlit_apps/frontend/generated/api.ts b/products/streamlit_apps/frontend/generated/api.ts
index 4ac19bb2020f..475c88516075 100644
--- a/products/streamlit_apps/frontend/generated/api.ts
+++ b/products/streamlit_apps/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
AppContractApi,
AppVersionContractApi,
CreateAppInputApi,
+ CreateVersionFromSourceInputApi,
PaginatedAppSummaryContractListApi,
PatchedUpdateAppInputApi,
StreamlitAppStatusApi,
@@ -191,6 +192,27 @@ export const streamlitAppsConnectInfoRetrieve = async (
})
}
+export const getStreamlitAppsCreateVersionFromSourceCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/create_version_from_source/`
+}
+
+/**
+ * @summary Create an app version from source code
+ */
+export const streamlitAppsCreateVersionFromSourceCreate = async (
+ projectId: string,
+ shortId: string,
+ createVersionFromSourceInputApi: CreateVersionFromSourceInputApi,
+ options?: RequestInit
+): Promise<AppVersionContractApi> => {
+ return apiMutator<AppVersionContractApi>(getStreamlitAppsCreateVersionFromSourceCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createVersionFromSourceInputApi),
+ })
+}
+
export const getStreamlitAppsRestartCreateUrl = (projectId: string, shortId: string) => {
return `/api/projects/${projectId}/streamlit_apps/${shortId}/restart/`
}
diff --git a/products/streamlit_apps/frontend/generated/api.zod.ts b/products/streamlit_apps/frontend/generated/api.zod.ts
index 28726059face..2953432ff0a4 100644
--- a/products/streamlit_apps/frontend/generated/api.zod.ts
+++ b/products/streamlit_apps/frontend/generated/api.zod.ts
@@ -48,6 +48,20 @@ export const StreamlitAppsActivateVersionCreateBody = /* @__PURE__ */ zod.object
.describe('Version number to activate. Must reference an existing version of this app.'),
})
+/**
+ * @summary Create an app version from source code
+ */
+export const streamlitAppsCreateVersionFromSourceCreateBodySourceMax = 1048576
+
+export const StreamlitAppsCreateVersionFromSourceCreateBody = /* @__PURE__ */ zod.object({
+ source: zod
+ .string()
+ .max(streamlitAppsCreateVersionFromSourceCreateBodySourceMax)
+ .describe(
+ "Full Python source for the Streamlit app's root app.py file, as free text (max 1 MB). Becomes a new version and is set as the active version."
+ ),
+})
+
/**
* @summary Upload a new app version
*/
diff --git a/products/streamlit_apps/mcp/tools.yaml b/products/streamlit_apps/mcp/tools.yaml
new file mode 100644
index 000000000000..f9c70876c9b1
--- /dev/null
+++ b/products/streamlit_apps/mcp/tools.yaml
@@ -0,0 +1,185 @@
+# 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: Streamlit apps
+feature: streamlit_apps
+url_prefix: /streamlit-apps
+ui_apps: {}
+tools:
+ streamlit-apps-activate-version:
+ operation: streamlit_apps_activate_version_create
+ enabled: false
+ streamlit-apps-connect-info:
+ operation: streamlit_apps_connect_info_retrieve
+ enabled: false
+ streamlit-apps-create:
+ operation: streamlit_apps_create
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ enrich_url: '{short_id}'
+ title: Create Streamlit app
+ description: >
+ Create a new Streamlit app (metadata only — it has no code until you call streamlit-apps-set-source).
+ Typical flow: create the app, set its source, then start it. cpu_cores (0.25–8) and memory_gb (0.5–16)
+ control the sandbox size and default to 0.5 / 1.
+ feature_flag: streamlit-apps
+ streamlit-apps-delete:
+ operation: streamlit_apps_destroy
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete Streamlit app
+ description: |
+ Delete a Streamlit app by short_id. Stops any running sandbox and soft-deletes the app.
+ feature_flag: streamlit-apps
+ streamlit-apps-get:
+ operation: streamlit_apps_retrieve
+ enabled: true
+ scopes:
+ - streamlit_app:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{short_id}'
+ title: Get Streamlit app
+ description: |
+ Get a single Streamlit app by its short_id, including its active version and live sandbox status.
+ feature_flag: streamlit-apps
+ streamlit-apps-list:
+ operation: streamlit_apps_list
+ enabled: true
+ scopes:
+ - streamlit_app:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{short_id}'
+ list: true
+ title: List Streamlit apps
+ description: >
+ List all Streamlit apps in the current project. Each app is a Python data app that runs in an isolated
+ sandbox. Returns short_id, name, description, resource config, and current sandbox status.
+ feature_flag: streamlit-apps
+ streamlit-apps-put-update:
+ operation: streamlit_apps_update
+ enabled: false
+ streamlit-apps-restart:
+ operation: streamlit_apps_restart_create
+ enabled: false
+ streamlit-apps-set-source:
+ operation: streamlit_apps_create_version_from_source_create
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ - query:read
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Set Streamlit app source
+ description: >
+ Create a new version of a Streamlit app from a single free-text app.py source string, and set it as the
+ active version. This is the simplest way to ship code — no zip upload required. If the app is running, its
+ sandbox is stopped; call streamlit-apps-start afterwards to serve the new version. Use
+ posthog_apps.query("<HogQL>") inside the app to read PostHog data as a pandas DataFrame. There is no way to
+ add pip dependencies — only packages baked into the sandbox image are importable.
+ param_overrides:
+ source:
+ description: >
+ The complete Python source for the app's root app.py (a Streamlit script, e.g. starting with `import
+ streamlit as st`). Sent as plain text.
+ feature_flag: streamlit-apps
+ streamlit-apps-start:
+ operation: streamlit_apps_start_create
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ - query:read
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{short_id}'
+ title: Start Streamlit app
+ description: >
+ Start the app's sandbox (boots the active version). Returns immediately while the sandbox boots
+ asynchronously — poll streamlit-apps-status until it reports running. Requires an active version (set one
+ first with streamlit-apps-set-source). Idempotent: a no-op if already running or starting. The response's
+ _posthogUrl is the app's page in PostHog — share that link with humans.
+ feature_flag: streamlit-apps
+ streamlit-apps-status:
+ operation: streamlit_apps_status_retrieve
+ enabled: true
+ scopes:
+ - streamlit_app:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get Streamlit app status
+ description: >
+ Get the live sandbox status for a Streamlit app: one of starting, running, stopping, stopped, or error, plus
+ restart_count and last_error. Use this to poll after starting an app.
+ feature_flag: streamlit-apps
+ streamlit-apps-stop:
+ operation: streamlit_apps_stop_create
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{short_id}'
+ title: Stop Streamlit app
+ description: >
+ Stop the app's running sandbox. Idempotent: a no-op if the app is not running. The app's code and versions
+ are unaffected — it can be started again later.
+ feature_flag: streamlit-apps
+ streamlit-apps-update:
+ operation: streamlit_apps_partial_update
+ enabled: true
+ scopes:
+ - streamlit_app:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{short_id}'
+ title: Update Streamlit app
+ description: >
+ Update an app's metadata or sandbox sizing: name, description, cpu_cores (0.25–8), memory_gb (0.5–16). Only
+ the fields you provide change. Resizing applies the next time the sandbox starts. Code changes go through
+ streamlit-apps-set-source, not this tool.
+ feature_flag: streamlit-apps
+ streamlit-apps-upload-version:
+ operation: streamlit_apps_upload_version_create
+ enabled: false
+ streamlit-apps-versions:
+ operation: streamlit_apps_versions_retrieve
+ enabled: true
+ scopes:
+ - streamlit_app:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List Streamlit app versions
+ description: |
+ List a Streamlit app's versions (latest first). Each version is an immutable snapshot of the app's code.
+ feature_flag: streamlit-apps
diff --git a/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md b/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md
new file mode 100644
index 000000000000..a651e6b21621
--- /dev/null
+++ b/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md
@@ -0,0 +1,58 @@
+---
+name: managing-streamlit-apps
+description: Create, deploy, and operate Streamlit apps in PostHog via the streamlit-apps MCP tools — create an app, set its source, start and stop its sandbox, poll status, list versions, delete, and share the app with humans via its PostHog URL. Use when asked to "create a streamlit app", "deploy a data app", "ship a dashboard app", "restart/stop my app", "why is my app not running", or "give me a link to the app".
+---
+
+# Managing Streamlit apps
+
+A Streamlit app is a Python data app running in an isolated sandbox inside PostHog.
+Each app has immutable versions of its code; one version is active; a sandbox process serves the active version.
+The full lifecycle is driven with the `streamlit-apps-*` MCP tools.
+
+## The happy path: create → set source → start → share
+
+1. `streamlit-apps-create` with a `name` (optionally `description`, `cpu_cores` 0.25–8, `memory_gb` 0.5–16, defaults 0.5 / 1).
+ The app exists but has no code yet.
+2. `streamlit-apps-set-source` with the complete `app.py` source as one string.
+ This creates version 1 and activates it.
+ Write the source per the `writing-streamlit-apps` skill — in particular use `posthog_apps.query()` for PostHog data, never `import posthog`.
+3. `streamlit-apps-start`.
+ Returns immediately; the sandbox boots asynchronously.
+4. Poll `streamlit-apps-status` until `status` is `running` (typically well under a minute).
+ If it lands on `error`, read `last_error` — see Troubleshooting below.
+5. Share the app: the `_posthogUrl` returned by create/get/start (`/streamlit-apps/{short_id}`) is the app's page in PostHog.
+ That link is what you give humans.
+ Viewers need to be logged into PostHog with access to the project (the app renders in an authenticated iframe; there is no public URL).
+
+## Whose data the app reads
+
+The app's queries run with the data access of the person who authored the **active version** — set the source, and the app reads what you can read.
+Anyone who can view the app sees those results, so treat publishing an app as sharing that data with everyone on the project.
+An app whose version author has since been deleted can't start; upload a new version to fix it.
+
+## Updating code
+
+Call `streamlit-apps-set-source` again: it creates the next version and activates it.
+A running sandbox is stopped so it can't keep serving stale code — call `streamlit-apps-start` afterwards to serve the new version.
+Versions are immutable, but not permanent: `streamlit-apps-versions` lists the newest 50, and non-active versions older than 30 days are deleted along with their code.
+There is no rollback tool: to roll back, set the old source again (fetch it from your conversation or wherever it's kept — versions store the zip, not an inline source view).
+
+## Stopping, idling, and deleting
+
+- `streamlit-apps-stop` stops the sandbox; code and versions are untouched. Starting again later is cheap.
+- Idle sandboxes are stopped automatically after a period of no activity — a stopped app is normal, not an error. Start it again when needed.
+- `streamlit-apps-delete` stops any sandbox and soft-deletes the app. Confirm with the user before deleting anything you didn't create in this conversation.
+
+## Troubleshooting
+
+- **`status: error` with `last_error: "Start failed: ..."`** — the sandbox failed to provision or boot. Retry `streamlit-apps-start` once; if it persists, surface `last_error` to the user (provisioning failures are usually platform-side, not app-side).
+- **Tool calls return 403 "Streamlit apps is not available."** — the `streamlit-apps` feature flag is off for this organization. This is a rollout gate, not an error you can fix; tell the user.
+- **App runs but a query inside it fails** — that's an app-code concern; see `writing-streamlit-apps` (bridge limits: 30s execution, 256 MB memory per query).
+- **App shows old code after set-source** — you skipped step "start after set-source"; the sandbox was stopped and needs a start.
+
+## Renaming and resizing
+
+`streamlit-apps-update` changes an app's name, description, `cpu_cores` (0.25–8), or `memory_gb` (0.5–16); only the fields you pass change.
+New sizing applies the next time the sandbox starts, so stop + start after resizing a running app.
+Defaults (0.5 CPU / 1 GB) fit typical dashboard apps.
+Raise `memory_gb` only when the app itself holds large DataFrames in memory — the 256 MB HogQL bridge query cap is server-side and does NOT change with sandbox sizing, so bigger sandboxes don't fix failing queries.
diff --git a/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md b/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md
new file mode 100644
index 000000000000..fb0e2fd1f3de
--- /dev/null
+++ b/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: writing-streamlit-apps
+description: Write Streamlit app source code that runs well in a PostHog sandbox — the posthog_apps.query() bridge for reading PostHog data, the packages baked into the sandbox image, caching and session state across Streamlit reruns, layout and chart patterns, and single-file app.py structure. Use when authoring or debugging the Python source of a PostHog Streamlit app, when a query inside an app fails, or when asked to "write a streamlit app that shows PostHog data".
+---
+
+# Writing Streamlit apps for the PostHog sandbox
+
+The source you write becomes `app.py` at the root of a sandboxed Streamlit 1.31 runtime.
+Deployment mechanics (create/start/share) are the `managing-streamlit-apps` skill; this one is about the code.
+
+## Reading PostHog data: `posthog_apps.query()`
+
+The one and only data door is the in-sandbox bridge:
+
+```python
+import posthog_apps
+
+df = posthog_apps.query("SELECT event, count() FROM events GROUP BY event LIMIT 10")
+```
+
+- Takes a HogQL string, returns a **pandas DataFrame**.
+- Raises `RuntimeError` on failure. The message is deliberately generic ("Query execution failed") — the bridge does not return query internals to the sandbox, so you cannot diagnose a bad query from inside the app. Catch it and render with `st.error(str(e))` so viewers get a message instead of a stack trace, and test queries in the SQL editor where real errors are visible.
+- `import posthog` does NOT exist in the sandbox — the module is `posthog_apps`, deliberately distinct from the posthog-python SDK's name.
+- The bridge is pre-authenticated to the app's project; user code never sees a token, and there is nothing to configure.
+- Queries run with server-side caps (30 s execution, 256 MB memory) that don't scale with sandbox sizing — so bound time ranges, `LIMIT` results, and aggregate in HogQL rather than pulling raw events into pandas.
+
+## Design for Streamlit's rerun model
+
+Streamlit reruns the whole script top to bottom on every widget interaction.
+Two consequences:
+
+1. **Cache every bridge call** — uncached, one slider drag re-fires every query:
+
+ ```python
+ @st.cache_data(ttl=300, show_spinner="Running query...")
+ def run_query(hogql: str) -> pd.DataFrame:
+ return posthog_apps.query(hogql)
+ ```
+
+2. **Use `st.session_state` for anything that must survive reruns** — accumulated selections, pagination cursors, "last refreshed" stamps. Module-level variables reset on every interaction.
+
+Widgets drive parameters naturally, but **never interpolate a free-text widget value into HogQL**.
+The bridge runs your query with the version author's data access, and anyone who can view the app drives those widgets — a raw `st.text_input` spliced into a query hands viewers the author's access to write their own.
+Constrain the input instead: pick from a fixed list you control (`st.selectbox` over known values), or coerce to a type that can't carry SQL (`int(days)`, a `date` from `st.date_input`), and validate before it reaches the query.
+
+## Layout and charts
+
+- `st.set_page_config(page_title=..., layout="wide")` first — the default narrow layout wastes most of the screen for data apps.
+- Structure with `st.columns` for side-by-side metrics, `st.tabs` for alternate views, `st.expander` for detail sections; `st.metric` for headline numbers.
+- Charts: `st.plotly_chart(fig, use_container_width=True)` with plotly express is the reliable default; `st.dataframe(df, use_container_width=True)` for tables. matplotlib/seaborn also work via `st.pyplot`.
+
+## What's installed
+
+The image ships Python 3.11 with: `streamlit` 1.31, `pandas`, `numpy`, `polars`, `plotly`, `matplotlib`, `seaborn`, `scipy`, `scikit-learn`, `pyarrow`, `duckdb`, `requests`, `beautifulsoup4`, `lxml`, `sqlalchemy`, `aiohttp`.
+There is no way to add dependencies: the sandbox never runs pip (a deliberate security posture — no arbitrary package code at boot), and a `requirements.txt` in an uploaded zip is tolerated but dropped. Only import what's listed above.
+
+## Structure and runtime constraints
+
+- **One file.** Via the MCP set-source flow your source IS `app.py`; there are no other modules, so keep everything in it.
+- The sandbox is ephemeral: anything written to disk disappears on stop/restart. Don't build state on files; recompute from queries (with caching) or hold it in `st.session_state`.
+- Your code runs as an unprivileged user; there's no posthog SDK, no way to pass your own environment variables or secrets to the app, and no expectation of general network egress. Don't read from `os.environ` — anything there belongs to the sandbox runtime, not your app. Design around `posthog_apps.query()` as the data source.
+
+## A minimal well-shaped app
+
+```python
+import pandas as pd
+import plotly.express as px
+import posthog_apps
+import streamlit as st
+
+st.set_page_config(page_title="Events overview", layout="wide")
+st.title("Events overview")
+
+
[email protected]_data(ttl=300, show_spinner="Running query...")
+def run_query(hogql: str) -> pd.DataFrame:
+ return posthog_apps.query(hogql)
+
+
+# A slider is bounded and coerced to int, so it is safe to interpolate.
+days = int(st.slider("Days to show", 1, 30, 7))
+try:
+ daily = run_query(
+ f"""
+ SELECT toDate(timestamp) AS day, count() AS events
+ FROM events
+ WHERE timestamp >= now() - INTERVAL {days} DAY
+ GROUP BY day ORDER BY day
+ """
+ )
+ st.plotly_chart(px.bar(daily, x="day", y="events"), use_container_width=True)
+except RuntimeError as e:
+ st.error(str(e))
+```
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 90e750059c96..a227e2d0a172 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8526,6 +8526,156 @@
},
"feature_flag": "stamphog"
},
+ "streamlit-apps-create": {
+ "description": "Create a new Streamlit app (metadata only — it has no code until you call streamlit-apps-set-source). Typical flow: create the app, set its source, then start it. cpu_cores (0.25–8) and memory_gb (0.5–16) control the sandbox size and default to 0.5 / 1.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Create Streamlit app",
+ "title": "Create Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-delete": {
+ "description": "Delete a Streamlit app by short_id. Stops any running sandbox and soft-deletes the app.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Delete Streamlit app",
+ "title": "Delete Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-get": {
+ "description": "Get a single Streamlit app by its short_id, including its active version and live sandbox status.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Get Streamlit app",
+ "title": "Get Streamlit app",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-list": {
+ "description": "List all Streamlit apps in the current project. Each app is a Python data app that runs in an isolated sandbox. Returns short_id, name, description, resource config, and current sandbox status.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "List Streamlit apps",
+ "title": "List Streamlit apps",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-set-source": {
+ "description": "Create a new version of a Streamlit app from a single free-text app.py source string, and set it as the active version. This is the simplest way to ship code — no zip upload required. If the app is running, its sandbox is stopped; call streamlit-apps-start afterwards to serve the new version. Use posthog_apps.query(\"<HogQL>\") inside the app to read PostHog data as a pandas DataFrame. There is no way to add pip dependencies — only packages baked into the sandbox image are importable.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Set Streamlit app source",
+ "title": "Set Streamlit app source",
+ "required_scopes": ["streamlit_app:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-start": {
+ "description": "Start the app's sandbox (boots the active version). Returns immediately while the sandbox boots asynchronously — poll streamlit-apps-status until it reports running. Requires an active version (set one first with streamlit-apps-set-source). Idempotent: a no-op if already running or starting. The response's _posthogUrl is the app's page in PostHog — share that link with humans.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Start Streamlit app",
+ "title": "Start Streamlit app",
+ "required_scopes": ["streamlit_app:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-status": {
+ "description": "Get the live sandbox status for a Streamlit app: one of starting, running, stopping, stopped, or error, plus restart_count and last_error. Use this to poll after starting an app.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Get Streamlit app status",
+ "title": "Get Streamlit app status",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-stop": {
+ "description": "Stop the app's running sandbox. Idempotent: a no-op if the app is not running. The app's code and versions are unaffected — it can be started again later.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Stop Streamlit app",
+ "title": "Stop Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-update": {
+ "description": "Update an app's metadata or sandbox sizing: name, description, cpu_cores (0.25–8), memory_gb (0.5–16). Only the fields you provide change. Resizing applies the next time the sandbox starts. Code changes go through streamlit-apps-set-source, not this tool.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Update Streamlit app",
+ "title": "Update Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-versions": {
+ "description": "List a Streamlit app's versions (latest first). Each version is an immutable snapshot of the app's code.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "List Streamlit app versions",
+ "title": "List Streamlit app versions",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
"subscriptions-create": {
"description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 6) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email` or `slack`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)",
"category": "Subscriptions",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 961ebd5d720a..1354b7ee3e40 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9077,6 +9077,156 @@
},
"feature_flag": "stamphog"
},
+ "streamlit-apps-create": {
+ "description": "Create a new Streamlit app (metadata only — it has no code until you call streamlit-apps-set-source). Typical flow: create the app, set its source, then start it. cpu_cores (0.25–8) and memory_gb (0.5–16) control the sandbox size and default to 0.5 / 1.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Create Streamlit app",
+ "title": "Create Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-delete": {
+ "description": "Delete a Streamlit app by short_id. Stops any running sandbox and soft-deletes the app.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Delete Streamlit app",
+ "title": "Delete Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-get": {
+ "description": "Get a single Streamlit app by its short_id, including its active version and live sandbox status.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Get Streamlit app",
+ "title": "Get Streamlit app",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-list": {
+ "description": "List all Streamlit apps in the current project. Each app is a Python data app that runs in an isolated sandbox. Returns short_id, name, description, resource config, and current sandbox status.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "List Streamlit apps",
+ "title": "List Streamlit apps",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-set-source": {
+ "description": "Create a new version of a Streamlit app from a single free-text app.py source string, and set it as the active version. This is the simplest way to ship code — no zip upload required. If the app is running, its sandbox is stopped; call streamlit-apps-start afterwards to serve the new version. Use posthog_apps.query(\"<HogQL>\") inside the app to read PostHog data as a pandas DataFrame. There is no way to add pip dependencies — only packages baked into the sandbox image are importable.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Set Streamlit app source",
+ "title": "Set Streamlit app source",
+ "required_scopes": ["streamlit_app:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-start": {
+ "description": "Start the app's sandbox (boots the active version). Returns immediately while the sandbox boots asynchronously — poll streamlit-apps-status until it reports running. Requires an active version (set one first with streamlit-apps-set-source). Idempotent: a no-op if already running or starting. The response's _posthogUrl is the app's page in PostHog — share that link with humans.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Start Streamlit app",
+ "title": "Start Streamlit app",
+ "required_scopes": ["streamlit_app:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-status": {
+ "description": "Get the live sandbox status for a Streamlit app: one of starting, running, stopping, stopped, or error, plus restart_count and last_error. Use this to poll after starting an app.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Get Streamlit app status",
+ "title": "Get Streamlit app status",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-stop": {
+ "description": "Stop the app's running sandbox. Idempotent: a no-op if the app is not running. The app's code and versions are unaffected — it can be started again later.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Stop Streamlit app",
+ "title": "Stop Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-update": {
+ "description": "Update an app's metadata or sandbox sizing: name, description, cpu_cores (0.25–8), memory_gb (0.5–16). Only the fields you provide change. Resizing applies the next time the sandbox starts. Code changes go through streamlit-apps-set-source, not this tool.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "Update Streamlit app",
+ "title": "Update Streamlit app",
+ "required_scopes": ["streamlit_app:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "streamlit-apps"
+ },
+ "streamlit-apps-versions": {
+ "description": "List a Streamlit app's versions (latest first). Each version is an immutable snapshot of the app's code.",
+ "category": "Streamlit apps",
+ "feature": "streamlit_apps",
+ "summary": "List Streamlit app versions",
+ "title": "List Streamlit app versions",
+ "required_scopes": ["streamlit_app:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "streamlit-apps"
+ },
"subscriptions-create": {
"description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 6) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email` or `slack`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)",
"category": "Subscriptions",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f6b185dd013f..25982ccbdda9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15068,6 +15068,14 @@ export namespace Schemas {
color?: string | null;
}
+ export interface CreateVersionFromSourceInput {
+ /**
+ * Full Python source for the Streamlit app's root app.py file, as free text (max 1 MB). Becomes a new version and is set as the active version.
+ * @maxLength 1048576
+ */
+ source: string;
+ }
+
/**
* * `user` - user
* * `ai_generated` - ai_generated
diff --git a/services/mcp/src/generated/streamlit_apps/api.ts b/services/mcp/src/generated/streamlit_apps/api.ts
new file mode 100644
index 000000000000..10f1ce76d496
--- /dev/null
+++ b/services/mcp/src/generated/streamlit_apps/api.ts
@@ -0,0 +1,157 @@
+/**
+ * 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'
+
+/**
+ * @summary List streamlit apps
+ */
+export const StreamlitAppsListParams = /* @__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 StreamlitAppsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * @summary Create a streamlit app
+ */
+export const StreamlitAppsCreateParams = /* @__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 StreamlitAppsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().describe('Name of the app.'),
+ description: zod.string().optional().describe('Optional description of the app.'),
+ cpu_cores: zod.number().optional().describe('CPU cores allocated to the sandbox.'),
+ memory_gb: zod.number().optional().describe('Memory in GB allocated to the sandbox.'),
+})
+
+/**
+ * @summary Retrieve a streamlit app
+ */
+export const StreamlitAppsRetrieveParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+/**
+ * @summary Partially update a streamlit app
+ */
+export const StreamlitAppsPartialUpdateParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+export const StreamlitAppsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().optional().describe('New name for the app.'),
+ description: zod.string().optional().describe('New description for the app.'),
+ cpu_cores: zod.number().optional().describe('New CPU core allocation for the sandbox.'),
+ memory_gb: zod.number().optional().describe('New memory (GB) allocation for the sandbox.'),
+})
+
+/**
+ * @summary Delete a streamlit app
+ */
+export const StreamlitAppsDestroyParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+/**
+ * @summary Create an app version from source code
+ */
+export const StreamlitAppsCreateVersionFromSourceCreateParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+export const streamlitAppsCreateVersionFromSourceCreateBodySourceMax = 1048576
+
+export const StreamlitAppsCreateVersionFromSourceCreateBody = /* @__PURE__ */ zod.object({
+ source: zod
+ .string()
+ .max(streamlitAppsCreateVersionFromSourceCreateBodySourceMax)
+ .describe(
+ "Full Python source for the Streamlit app's root app.py file, as free text (max 1 MB). Becomes a new version and is set as the active version."
+ ),
+})
+
+/**
+ * @summary Start the app sandbox
+ */
+export const StreamlitAppsStartCreateParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+/**
+ * @summary Get app sandbox status
+ */
+export const StreamlitAppsStatusRetrieveParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+/**
+ * @summary Stop the app sandbox
+ */
+export const StreamlitAppsStopCreateParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
+
+/**
+ * @summary List app versions
+ */
+export const StreamlitAppsVersionsRetrieveParams = /* @__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\/."
+ ),
+ short_id: zod.string(),
+})
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index b24b50aed3e7..927ec88d9b65 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -48,6 +48,7 @@ import { GENERATED_TOOLS as review_hog } from './review_hog'
import { GENERATED_TOOLS as signals } from './signals'
import { GENERATED_TOOLS as skills } from './skills'
import { GENERATED_TOOLS as stamphog } from './stamphog'
+import { GENERATED_TOOLS as streamlit_apps } from './streamlit_apps'
import { GENERATED_TOOLS as subscriptions } from './subscriptions'
import { GENERATED_TOOLS as surveys } from './surveys'
import { GENERATED_TOOLS as tasks } from './tasks'
@@ -106,6 +107,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...signals,
...skills,
...stamphog,
+ ...streamlit_apps,
...subscriptions,
...surveys,
...tasks,
diff --git a/services/mcp/src/tools/generated/streamlit_apps.ts b/services/mcp/src/tools/generated/streamlit_apps.ts
new file mode 100644
index 000000000000..be835337c559
--- /dev/null
+++ b/services/mcp/src/tools/generated/streamlit_apps.ts
@@ -0,0 +1,245 @@
+// AUTO-GENERATED from products/streamlit_apps/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ StreamlitAppsCreateBody,
+ StreamlitAppsCreateVersionFromSourceCreateBody,
+ StreamlitAppsCreateVersionFromSourceCreateParams,
+ StreamlitAppsDestroyParams,
+ StreamlitAppsListQueryParams,
+ StreamlitAppsPartialUpdateBody,
+ StreamlitAppsPartialUpdateParams,
+ StreamlitAppsRetrieveParams,
+ StreamlitAppsStartCreateParams,
+ StreamlitAppsStatusRetrieveParams,
+ StreamlitAppsStopCreateParams,
+ StreamlitAppsVersionsRetrieveParams,
+} from '@/generated/streamlit_apps/api'
+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const StreamlitAppsCreateSchema = StreamlitAppsCreateBody
+
+const streamlitAppsCreate = (): ToolBase<typeof StreamlitAppsCreateSchema, WithPostHogUrl<Schemas.AppContract>> => ({
+ name: 'streamlit-apps-create',
+ schema: StreamlitAppsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.cpu_cores !== undefined) {
+ body['cpu_cores'] = params.cpu_cores
+ }
+ if (params.memory_gb !== undefined) {
+ body['memory_gb'] = params.memory_gb
+ }
+ const result = await context.api.request<Schemas.AppContract>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/streamlit-apps/${result.short_id}`)
+ },
+})
+
+const StreamlitAppsDeleteSchema = StreamlitAppsDestroyParams.omit({ project_id: true })
+
+const streamlitAppsDelete = (): ToolBase<typeof StreamlitAppsDeleteSchema, unknown> => ({
+ name: 'streamlit-apps-delete',
+ schema: StreamlitAppsDeleteSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsDeleteSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/`,
+ })
+ return result
+ },
+})
+
+const StreamlitAppsGetSchema = StreamlitAppsRetrieveParams.omit({ project_id: true })
+
+const streamlitAppsGet = (): ToolBase<typeof StreamlitAppsGetSchema, WithPostHogUrl<Schemas.AppContract>> => ({
+ name: 'streamlit-apps-get',
+ schema: StreamlitAppsGetSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsGetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AppContract>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/streamlit-apps/${result.short_id}`)
+ },
+})
+
+const StreamlitAppsListSchema = StreamlitAppsListQueryParams
+
+const streamlitAppsList = (): ToolBase<
+ typeof StreamlitAppsListSchema,
+ WithPostHogUrl<Schemas.PaginatedAppSummaryContractList>
+> => ({
+ name: 'streamlit-apps-list',
+ schema: StreamlitAppsListSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedAppSummaryContractList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(
+ context,
+ {
+ ...result,
+ results: await Promise.all(
+ (result.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/streamlit-apps/${item.short_id}`)
+ )
+ ),
+ },
+ '/streamlit-apps'
+ )
+ },
+})
+
+const StreamlitAppsSetSourceSchema = StreamlitAppsCreateVersionFromSourceCreateParams.omit({ project_id: true })
+ .extend(StreamlitAppsCreateVersionFromSourceCreateBody.shape)
+ .extend({
+ source: StreamlitAppsCreateVersionFromSourceCreateBody.shape['source'].describe(
+ "The complete Python source for the app's root app.py (a Streamlit script, e.g. starting with `import streamlit as st`). Sent as plain text."
+ ),
+ })
+
+const streamlitAppsSetSource = (): ToolBase<typeof StreamlitAppsSetSourceSchema, Schemas.AppVersionContract> => ({
+ name: 'streamlit-apps-set-source',
+ schema: StreamlitAppsSetSourceSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsSetSourceSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.source !== undefined) {
+ body['source'] = params.source
+ }
+ const result = await context.api.request<Schemas.AppVersionContract>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/create_version_from_source/`,
+ body,
+ })
+ return result
+ },
+})
+
+const StreamlitAppsStartSchema = StreamlitAppsStartCreateParams.omit({ project_id: true })
+
+const streamlitAppsStart = (): ToolBase<typeof StreamlitAppsStartSchema, WithPostHogUrl<Schemas.AppContract>> => ({
+ name: 'streamlit-apps-start',
+ schema: StreamlitAppsStartSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsStartSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AppContract>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/start/`,
+ })
+ return await withPostHogUrl(context, result, `/streamlit-apps/${result.short_id}`)
+ },
+})
+
+const StreamlitAppsStatusSchema = StreamlitAppsStatusRetrieveParams.omit({ project_id: true })
+
+const streamlitAppsStatus = (): ToolBase<typeof StreamlitAppsStatusSchema, Schemas.StreamlitAppStatus> => ({
+ name: 'streamlit-apps-status',
+ schema: StreamlitAppsStatusSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsStatusSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.StreamlitAppStatus>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/status/`,
+ })
+ return result
+ },
+})
+
+const StreamlitAppsStopSchema = StreamlitAppsStopCreateParams.omit({ project_id: true })
+
+const streamlitAppsStop = (): ToolBase<typeof StreamlitAppsStopSchema, WithPostHogUrl<Schemas.AppContract>> => ({
+ name: 'streamlit-apps-stop',
+ schema: StreamlitAppsStopSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsStopSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AppContract>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/stop/`,
+ })
+ return await withPostHogUrl(context, result, `/streamlit-apps/${result.short_id}`)
+ },
+})
+
+const StreamlitAppsUpdateSchema = StreamlitAppsPartialUpdateParams.omit({ project_id: true }).extend(
+ StreamlitAppsPartialUpdateBody.shape
+)
+
+const streamlitAppsUpdate = (): ToolBase<typeof StreamlitAppsUpdateSchema, WithPostHogUrl<Schemas.AppContract>> => ({
+ name: 'streamlit-apps-update',
+ schema: StreamlitAppsUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.cpu_cores !== undefined) {
+ body['cpu_cores'] = params.cpu_cores
+ }
+ if (params.memory_gb !== undefined) {
+ body['memory_gb'] = params.memory_gb
+ }
+ const result = await context.api.request<Schemas.AppContract>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/streamlit-apps/${result.short_id}`)
+ },
+})
+
+const StreamlitAppsVersionsSchema = StreamlitAppsVersionsRetrieveParams.omit({ project_id: true })
+
+const streamlitAppsVersions = (): ToolBase<
+ typeof StreamlitAppsVersionsSchema,
+ WithPostHogUrl<Schemas.StreamlitAppVersionList>
+> => ({
+ name: 'streamlit-apps-versions',
+ schema: StreamlitAppsVersionsSchema,
+ handler: async (context: Context, params: z.infer<typeof StreamlitAppsVersionsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.StreamlitAppVersionList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/streamlit_apps/${encodeURIComponent(String(params.short_id))}/versions/`,
+ })
+ return await withPostHogUrl(context, result, '/streamlit-apps')
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'streamlit-apps-create': streamlitAppsCreate,
+ 'streamlit-apps-delete': streamlitAppsDelete,
+ 'streamlit-apps-get': streamlitAppsGet,
+ 'streamlit-apps-list': streamlitAppsList,
+ 'streamlit-apps-set-source': streamlitAppsSetSource,
+ 'streamlit-apps-start': streamlitAppsStart,
+ 'streamlit-apps-status': streamlitAppsStatus,
+ 'streamlit-apps-stop': streamlitAppsStop,
+ 'streamlit-apps-update': streamlitAppsUpdate,
+ 'streamlit-apps-versions': streamlitAppsVersions,
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 96da3312012c..9ce604a346f5 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -820,9 +820,10 @@ describe('Tool Filtering - Feature Flags', () => {
'loops',
'review-hog',
'warehouse-person-properties',
+ 'streamlit-apps',
])
)
- expect(flags).toHaveLength(24)
+ expect(flags).toHaveLength(25)
})
it('every loops tool is gated on the loops flag', () => {