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): ship extra files and assets through set-source (#96688)

Jovan Sakovicafe0659b7e21
diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.py
index 23ffe42ebfbf..58c79ac8381b 100644
--- a/products/streamlit_apps/backend/facade/api.py
+++ b/products/streamlit_apps/backend/facade/api.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import uuid
+import base64
import hashlib
from django.db import IntegrityError, transaction
@@ -23,7 +24,13 @@ 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, build_single_file_zip, validate_zip
+from products.streamlit_apps.backend.logic.zip_validator import (
+ MAX_FILE_COUNT,
+ MAX_ZIP_SIZE,
+ attachment_path_error,
+ build_app_zip,
+ validate_zip,
+)
from products.streamlit_apps.backend.models import (
MAX_CPU_CORES,
MAX_MEMORY_GB,
@@ -47,6 +54,7 @@ logger = structlog.get_logger(__name__)
_LAST_ACTIVITY_DEBOUNCE_SECONDS = 30
__all__ = [
+ "attachment_path_error",
"AppRuntimeConcurrencyError",
"AppRuntimeError",
"AppNotFoundError",
@@ -57,6 +65,7 @@ __all__ = [
"NoActiveVersionError",
"AppNotRunningError",
"ConnectUnavailableError",
+ "MAX_FILE_COUNT",
"MAX_ZIP_SIZE",
"MIN_CPU_CORES",
"MAX_CPU_CORES",
@@ -440,13 +449,14 @@ def create_version_from_source(
data: contracts.CreateVersionFromSourceInput,
was_impersonated: bool,
) -> contracts.AppVersionContract:
- """Create and activate a version from a single free-text app.py source string.
+ """Create and activate a version from free-text source plus optional extra files.
- Packs the source into the same zip shape as an upload, so validation,
+ Packs everything 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)
+ assets = {path: base64.b64decode(content, validate=True) for path, content in data.assets.items()}
+ file_content = build_app_zip(data.source, files=data.files, assets=assets)
return upload_version(
team_id=team_id,
short_id=short_id,
diff --git a/products/streamlit_apps/backend/facade/contracts.py b/products/streamlit_apps/backend/facade/contracts.py
index 6fdfafb1aafb..aaf0706aee1d 100644
--- a/products/streamlit_apps/backend/facade/contracts.py
+++ b/products/streamlit_apps/backend/facade/contracts.py
@@ -12,6 +12,7 @@ working), but with runtime validation on construction. See
from __future__ import annotations
+from dataclasses import field
from datetime import datetime
from uuid import UUID
@@ -105,6 +106,8 @@ class CreateAppInput:
@dataclass(frozen=True)
class CreateVersionFromSourceInput:
source: str
+ files: dict[str, str] = field(default_factory=dict)
+ assets: dict[str, str] = field(default_factory=dict)
@dataclass(frozen=True)
diff --git a/products/streamlit_apps/backend/logic/zip_validator.py b/products/streamlit_apps/backend/logic/zip_validator.py
index 3a281e9f0d6d..27df3ec1e279 100644
--- a/products/streamlit_apps/backend/logic/zip_validator.py
+++ b/products/streamlit_apps/backend/logic/zip_validator.py
@@ -2,31 +2,61 @@ from __future__ import annotations
import os
import zipfile
+from collections.abc import Mapping
from dataclasses import dataclass, field
from io import BytesIO
MAX_ZIP_SIZE = 10 * 1024 * 1024 # 10 MB
MAX_UNCOMPRESSED_SIZE = 100 * 1024 * 1024 # 100 MB
MAX_FILE_COUNT = 500
+# The sandbox unpacks every entry onto a real filesystem, which allows 255 bytes per name.
+# The whole-path bound keeps an entry clear of PATH_MAX once the sandbox prefix is added, and
+# inside the two-byte name length a zip header can hold.
+MAX_PATH_SEGMENT_BYTES = 255
+MAX_PATH_BYTES = 1024
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.
+ROOT_APP_FILE = "app.py"
- 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.
+
+def build_app_zip(source: str, files: Mapping[str, str], assets: Mapping[str, bytes]) -> bytes:
+ """Pack a Streamlit app given as free text into a zip.
+
+ ``source`` becomes the root ``app.py``; ``files`` are extra text entries and
+ ``assets`` extra binary entries, both keyed by project-relative path. Lets
+ agents create an app from a tool call 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)
+ zf.writestr(ROOT_APP_FILE, source)
+ for path, text in files.items():
+ zf.writestr(path, text)
+ for path, content in assets.items():
+ zf.writestr(path, content)
return buf.getvalue()
+def attachment_path_error(path: str) -> str | None:
+ """Return why ``path`` cannot be an extra entry next to ``app.py``, or None if it can."""
+ if "\\" in path or any(segment in ("", ".", "..") for segment in path.split("/")):
+ return "Path must be a relative file path using '/' with no '.' or '..' segments."
+ if any(ord(char) < 32 for char in path):
+ return "Path cannot contain control characters."
+ if len(path.encode()) > MAX_PATH_BYTES:
+ return f"Path is too long (max {MAX_PATH_BYTES} bytes)."
+ if any(len(segment.encode()) > MAX_PATH_SEGMENT_BYTES for segment in path.split("/")):
+ return f"Each name in the path must be {MAX_PATH_SEGMENT_BYTES} bytes or fewer."
+ if path == ROOT_APP_FILE:
+ return f"{ROOT_APP_FILE} comes from the source field; pick another path."
+ return None
+
+
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/serializers.py b/products/streamlit_apps/backend/presentation/serializers.py
index 250e21285771..3388bfc9c30f 100644
--- a/products/streamlit_apps/backend/presentation/serializers.py
+++ b/products/streamlit_apps/backend/presentation/serializers.py
@@ -1,3 +1,5 @@
+import base64
+import binascii
from typing import TYPE_CHECKING, cast
import posthoganalytics
@@ -8,6 +10,7 @@ from rest_framework.request import Request
from rest_framework.views import APIView
from rest_framework_dataclasses.serializers import DataclassSerializer
+from products.streamlit_apps.backend.facade.api import MAX_FILE_COUNT, MAX_ZIP_SIZE, attachment_path_error
from products.streamlit_apps.backend.facade.contracts import (
AppContract,
AppSandboxContract,
@@ -91,6 +94,15 @@ class UpdateAppInputSerializer(DataclassSerializer):
dataclass = UpdateAppInput
+_MAX_TEXT_FILE_LENGTH = 1024 * 1024
+# Base64 length of MAX_ZIP_SIZE bytes: no single asset can be larger than the whole archive may be.
+_MAX_ASSET_BASE64_LENGTH = 4 * ((MAX_ZIP_SIZE + 2) // 3)
+
+
+def _decoded_base64_size(encoded: str) -> int:
+ return len(encoded) * 3 // 4 - (2 if encoded.endswith("==") else 1 if encoded.endswith("=") else 0)
+
+
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.
@@ -98,13 +110,30 @@ class CreateVersionFromSourceInputSerializer(DataclassSerializer):
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,
+ max_length=_MAX_TEXT_FILE_LENGTH,
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."
),
)
+ files = serializers.DictField(
+ child=serializers.CharField(trim_whitespace=False, allow_blank=True, max_length=_MAX_TEXT_FILE_LENGTH),
+ required=False,
+ help_text=(
+ "Extra text files to ship next to app.py, keyed by project-relative path "
+ "(for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB)."
+ ),
+ )
+ assets = serializers.DictField(
+ child=serializers.CharField(max_length=_MAX_ASSET_BASE64_LENGTH),
+ required=False,
+ help_text=(
+ "Extra binary files to ship next to app.py, keyed by project-relative path "
+ "(for example 'data/events.parquet'), each as standard base64 text."
+ ),
+ )
+
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
@@ -113,10 +142,57 @@ class CreateVersionFromSourceInputSerializer(DataclassSerializer):
raise serializers.ValidationError("Source cannot be empty.")
return value
+ def validate_files(self, value: dict[str, str]) -> dict[str, str]:
+ return _validate_attachment_paths(value)
+
+ def validate_assets(self, value: dict[str, str]) -> dict[str, str]:
+ _validate_attachment_paths(value)
+ for path, content in value.items():
+ try:
+ base64.b64decode(content, validate=True)
+ except (binascii.Error, ValueError):
+ raise serializers.ValidationError({path: "Content must be standard base64 text."}) from None
+ return value
+
+ def validate(self, attrs: CreateVersionFromSourceInput) -> CreateVersionFromSourceInput:
+ overlap = sorted(set(attrs.files) & set(attrs.assets))
+ if overlap:
+ raise serializers.ValidationError({"assets": f"Paths also present in files: {', '.join(overlap)}"})
+
+ entry_count = 1 + len(attrs.files) + len(attrs.assets)
+ if entry_count > MAX_FILE_COUNT:
+ raise serializers.ValidationError(f"Too many files ({entry_count}, max {MAX_FILE_COUNT}).")
+
+ # A path that is also a directory prefix of another cannot be unpacked on any filesystem.
+ paths = {"app.py", *attrs.files, *attrs.assets}
+ for path in sorted(paths):
+ if any(other.startswith(f"{path}/") for other in paths):
+ raise serializers.ValidationError(f"'{path}' is used as both a file and a directory.")
+
+ # Bound the work before any asset is decoded or the archive is built. The zip check
+ # after compression stays, this only refuses what could never fit.
+ raw_size = (
+ len(attrs.source.encode())
+ + sum(len(text.encode()) for text in attrs.files.values())
+ + sum(_decoded_base64_size(content) for content in attrs.assets.values())
+ )
+ if raw_size > MAX_ZIP_SIZE:
+ raise serializers.ValidationError(
+ f"App files total {raw_size / (1024 * 1024):.1f} MB, max {MAX_ZIP_SIZE / (1024 * 1024):.1f} MB."
+ )
+ return attrs
+
class Meta:
dataclass = CreateVersionFromSourceInput
+def _validate_attachment_paths(value: dict[str, str]) -> dict[str, str]:
+ errors = {path: error for path in value if (error := attachment_path_error(path))}
+ if errors:
+ raise serializers.ValidationError(errors)
+ return value
+
+
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 1537897f29b9..47f67910fb96 100644
--- a/products/streamlit_apps/backend/presentation/views.py
+++ b/products/streamlit_apps/backend/presentation/views.py
@@ -236,6 +236,10 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
except api.AppNotFoundError:
return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.ZipTooLargeError as e:
+ # The serializer bounds the raw bytes, but compression overhead and per-entry
+ # headers can still push the built archive past the zip limit.
+ return Response({"detail": str(e)}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
except api.InvalidZipError as e:
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
except api.ConcurrentUploadError as e:
diff --git a/products/streamlit_apps/backend/tests/test_presentation.py b/products/streamlit_apps/backend/tests/test_presentation.py
index 4e6e97dfba10..a08c4ff82889 100644
--- a/products/streamlit_apps/backend/tests/test_presentation.py
+++ b/products/streamlit_apps/backend/tests/test_presentation.py
@@ -1,17 +1,20 @@
import io
import uuid
+import base64
import zipfile
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
+from products.streamlit_apps.backend.presentation.serializers import CreateVersionFromSourceInputSerializer
def _make_zip(files: dict[str, str]) -> bytes:
@@ -719,6 +722,76 @@ class TestCreateVersionFromSource(_StreamlitAppsFlagMixin, APIBaseTest):
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
+ @patch("posthog.storage.object_storage.write")
+ def test_create_version_from_source_packs_files_and_assets(self, mock_storage_write):
+ app = self._create_app()
+ parquet_bytes = b"PAR1\x00\x01\x02\xff"
+ response = self.client.post(
+ self._url(app.short_id, "create_version_from_source/"),
+ data={
+ "source": "import streamlit as st",
+ "files": {"utils.py": "def helper():\n return 1\n", "data/empty.txt": ""},
+ "assets": {"data/events.parquet": base64.b64encode(parquet_bytes).decode()},
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ stored_bytes = mock_storage_write.call_args[0][1]
+ with zipfile.ZipFile(io.BytesIO(stored_bytes)) as zf:
+ assert sorted(zf.namelist()) == ["app.py", "data/empty.txt", "data/events.parquet", "utils.py"]
+ assert zf.read("utils.py").decode() == "def helper():\n return 1\n"
+ assert zf.read("data/events.parquet") == parquet_bytes
+
+ @patch("posthog.storage.object_storage.write")
+ @patch("products.streamlit_apps.backend.facade.api.MAX_ZIP_SIZE", 64)
+ def test_create_version_from_source_oversized_archive_413(self, mock_storage_write):
+ # The serializer's budget counts raw bytes, so an archive that only goes over once
+ # zip overhead is added reaches the facade and must not surface as a 500.
+ app = self._create_app()
+ response = self.client.post(
+ self._url(app.short_id, "create_version_from_source/"),
+ data={"source": "import streamlit as st\n" * 20},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
+ mock_storage_write.assert_not_called()
+
+
+class TestCreateVersionFromSourceInputSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("traversal", {"files": {"../x.py": ""}}, "files"),
+ ("absolute", {"files": {"/etc/x": ""}}, "files"),
+ ("dot_segment", {"files": {"./x.py": ""}}, "files"),
+ ("trailing_slash", {"files": {"data/": ""}}, "files"),
+ ("backslash", {"files": {"data\\x.csv": ""}}, "files"),
+ ("root_app_file", {"files": {"app.py": "print(1)"}}, "files"),
+ ("asset_traversal", {"assets": {"../x.bin": "AAAA"}}, "assets"),
+ ("asset_not_base64", {"assets": {"x.bin": "not base64!"}}, "assets"),
+ ("same_path_in_both", {"files": {"x.txt": "a"}, "assets": {"x.txt": "AAAA"}}, "assets"),
+ ("nul_in_path", {"files": {"bad\x00.txt": "a"}}, "files"),
+ ("file_and_directory", {"files": {"data": "a"}, "assets": {"data/events.csv": "AAAA"}}, "non_field_errors"),
+ ("under_app_py", {"files": {"app.py/helper.py": "a"}}, "non_field_errors"),
+ ("too_many_entries", {"files": {f"f{i}.txt": "a" for i in range(500)}}, "non_field_errors"),
+ ("overlong_segment", {"files": {"data/" + "a" * 256: "a"}}, "files"),
+ ("overlong_path", {"files": {"/".join(["d"] * 600) + "/x.txt": "a"}}, "files"),
+ ]
+ )
+ def test_rejects_bad_attachments(self, _name, extra, error_field):
+ serializer = CreateVersionFromSourceInputSerializer(data={"source": "import streamlit as st", **extra})
+ assert not serializer.is_valid()
+ assert error_field in serializer.errors
+
+ @parameterized.expand([("fits", 40, True), ("over_budget", 48, False)])
+ def test_raw_size_budget_counts_decoded_assets(self, _name, asset_bytes, expected_valid):
+ asset = base64.b64encode(b"x" * asset_bytes).decode()
+ with patch("products.streamlit_apps.backend.presentation.serializers.MAX_ZIP_SIZE", 64):
+ serializer = CreateVersionFromSourceInputSerializer(
+ data={"source": "import streamlit as st", "assets": {"d.bin": asset}}
+ )
+ assert serializer.is_valid() is expected_valid, serializer.errors
+
class TestStreamlitAppPersonalAPIKeyAccess(_StreamlitAppsFlagMixin, APIBaseTest):
"""Custom actions are invisible to the default CRUD scope derivation; these
diff --git a/products/streamlit_apps/frontend/generated/api.schemas.ts b/products/streamlit_apps/frontend/generated/api.schemas.ts
index d4b2b93555c6..3de309986914 100644
--- a/products/streamlit_apps/frontend/generated/api.schemas.ts
+++ b/products/streamlit_apps/frontend/generated/api.schemas.ts
@@ -142,12 +142,26 @@ export interface StreamlitConnectInfoApi {
expires_in: number
}
+/**
+ * Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB).
+ */
+export type CreateVersionFromSourceInputApiFiles = { [key: string]: string }
+
+/**
+ * Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data/events.parquet'), each as standard base64 text.
+ */
+export type CreateVersionFromSourceInputApiAssets = { [key: string]: string }
+
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
+ /** Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB). */
+ files?: CreateVersionFromSourceInputApiFiles
+ /** Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data/events.parquet'), each as standard base64 text. */
+ assets?: CreateVersionFromSourceInputApiAssets
}
export interface StreamlitAppStatusApi {
diff --git a/products/streamlit_apps/frontend/generated/api.zod.ts b/products/streamlit_apps/frontend/generated/api.zod.ts
index 2953432ff0a4..4bc01caa8dd8 100644
--- a/products/streamlit_apps/frontend/generated/api.zod.ts
+++ b/products/streamlit_apps/frontend/generated/api.zod.ts
@@ -53,6 +53,10 @@ export const StreamlitAppsActivateVersionCreateBody = /* @__PURE__ */ zod.object
*/
export const streamlitAppsCreateVersionFromSourceCreateBodySourceMax = 1048576
+export const streamlitAppsCreateVersionFromSourceCreateBodyFilesMaxOne = 1048576
+
+export const streamlitAppsCreateVersionFromSourceCreateBodyAssetsMaxOne = 13981016
+
export const StreamlitAppsCreateVersionFromSourceCreateBody = /* @__PURE__ */ zod.object({
source: zod
.string()
@@ -60,6 +64,18 @@ export const StreamlitAppsCreateVersionFromSourceCreateBody = /* @__PURE__ */ zo
.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."
),
+ files: zod
+ .record(zod.string(), zod.string().max(streamlitAppsCreateVersionFromSourceCreateBodyFilesMaxOne))
+ .optional()
+ .describe(
+ "Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data\/config.json'), each as plain text (max 1 MB)."
+ ),
+ assets: zod
+ .record(zod.string(), zod.string().max(streamlitAppsCreateVersionFromSourceCreateBodyAssetsMaxOne))
+ .optional()
+ .describe(
+ "Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data\/events.parquet'), each as standard base64 text."
+ ),
})
/**
diff --git a/products/streamlit_apps/mcp/tools.yaml b/products/streamlit_apps/mcp/tools.yaml
index f9c70876c9b1..be5826cc7087 100644
--- a/products/streamlit_apps/mcp/tools.yaml
+++ b/products/streamlit_apps/mcp/tools.yaml
@@ -92,9 +92,10 @@ tools:
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
+ Create a new version of a Streamlit app from free-text source, and set it as the active version. The source
+ becomes the root app.py; optional extra text files (helper modules, CSV, JSON) go in `files` and binary
+ files (Parquet, images) go base64-encoded in `assets`, so no zip upload is needed. 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:
@@ -102,6 +103,17 @@ tools:
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.
+ files:
+ description: >
+ Optional extra text files keyed by project-relative path (e.g. `utils.py`, `data/config.json`), each
+ value the file's full text. Paths must not be `app.py` and must not contain `..`. The app process
+ does not run inside its own directory, so open them via `Path(__file__).parent /
+ "data/config.json"`.
+ assets:
+ description: >
+ Optional extra binary files keyed by project-relative path (e.g. `data/events.parquet`), each value
+ the file's bytes as standard base64. Same path rules as `files`. Keep them small: the whole call is
+ sent as JSON, so a large file costs tokens on every set-source.
feature_flag: streamlit-apps
streamlit-apps-start:
operation: streamlit_apps_start_create
diff --git a/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md b/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md
index a651e6b21621..60dbc0b1a6a5 100644
--- a/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md
+++ b/products/streamlit_apps/skills/managing-streamlit-apps/SKILL.md
@@ -14,6 +14,7 @@ The full lifecycle is driven with the `streamlit-apps-*` MCP tools.
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.
+ Extra files ride along in the same call: `files` maps a project-relative path to text (helper modules, CSV, JSON), `assets` maps a path to base64 (Parquet, images).
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`.
@@ -33,9 +34,11 @@ An app whose version author has since been deleted can't start; upload a new ver
## Updating code
Call `streamlit-apps-set-source` again: it creates the next version and activates it.
+Every call ships the complete app, so pass `files` and `assets` again too; a version holds only what that call carried.
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).
+There is no rollback tool: to roll back, set the old `source`, `files`, and `assets` again, so a rollback needs a saved copy of the complete bundle.
+Fetch that copy from your conversation or wherever it's kept — versions store the zip, not an inline source view.
## Stopping, idling, and deleting
diff --git a/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md b/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md
index fb0e2fd1f3de..f0cd625a1d6d 100644
--- a/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md
+++ b/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md
@@ -1,6 +1,6 @@
---
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".
+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 the app.py entry point with any helper modules and data files bundled beside it. 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
@@ -56,7 +56,7 @@ There is no way to add dependencies: the sandbox never runs pip (a deliberate se
## 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.
+- **`app.py` is the entry point.** Via the MCP set-source flow your source IS `app.py`. Helper modules and data files can ship next to it through the `files` (text) and `assets` (base64) maps; `import utils` works because Streamlit puts the app directory on `sys.path`, but the process does not run inside that directory, so open data files via `Path(__file__).parent / "data/events.parquet"`, never a bare relative path. Keep bundled data small: it is sent inline as JSON on every set-source call.
- 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.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d7d864a1be86..231731910c40 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10577,7 +10577,7 @@
"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.",
+ "description": "Create a new version of a Streamlit app from free-text source, and set it as the active version. The source becomes the root app.py; optional extra text files (helper modules, CSV, JSON) go in `files` and binary files (Parquet, images) go base64-encoded in `assets`, so no zip upload is needed. 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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bf0ea90246e6..903bb5c9f272 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11149,7 +11149,7 @@
"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.",
+ "description": "Create a new version of a Streamlit app from free-text source, and set it as the active version. The source becomes the root app.py; optional extra text files (helper modules, CSV, JSON) go in `files` and binary files (Parquet, images) go base64-encoded in `assets`, so no zip upload is needed. 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",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 013e33503311..8cd0f630afbd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20234,12 +20234,26 @@ export namespace Schemas {
color?: string | null;
}
+ /**
+ * Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB).
+ */
+ export type CreateVersionFromSourceInputFiles = {[key: string]: string};
+
+ /**
+ * Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data/events.parquet'), each as standard base64 text.
+ */
+ export type CreateVersionFromSourceInputAssets = {[key: string]: string};
+
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;
+ /** Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB). */
+ files?: CreateVersionFromSourceInputFiles;
+ /** Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data/events.parquet'), each as standard base64 text. */
+ assets?: CreateVersionFromSourceInputAssets;
}
/**
diff --git a/services/mcp/src/generated/streamlit_apps/api.ts b/services/mcp/src/generated/streamlit_apps/api.ts
index a3fb5dbf376c..305e0e4f2e07 100644
--- a/services/mcp/src/generated/streamlit_apps/api.ts
+++ b/services/mcp/src/generated/streamlit_apps/api.ts
@@ -99,6 +99,10 @@ export const StreamlitAppsCreateVersionFromSourceCreateParams = () => zod.object
export const streamlitAppsCreateVersionFromSourceCreateBodySourceMax = 1048576
+export const streamlitAppsCreateVersionFromSourceCreateBodyFilesMaxOne = 1048576
+
+export const streamlitAppsCreateVersionFromSourceCreateBodyAssetsMaxOne = 13981016
+
export const StreamlitAppsCreateVersionFromSourceCreateBody = () => zod.object({
source: zod
.string()
@@ -106,6 +110,18 @@ export const StreamlitAppsCreateVersionFromSourceCreateBody = () => zod.object({
.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."
),
+ files: zod
+ .record(zod.string(), zod.string().max(streamlitAppsCreateVersionFromSourceCreateBodyFilesMaxOne))
+ .optional()
+ .describe(
+ "Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data\/config.json'), each as plain text (max 1 MB)."
+ ),
+ assets: zod
+ .record(zod.string(), zod.string().max(streamlitAppsCreateVersionFromSourceCreateBodyAssetsMaxOne))
+ .optional()
+ .describe(
+ "Extra binary files to ship next to app.py, keyed by project-relative path (for example 'data\/events.parquet'), each as standard base64 text."
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/streamlit_apps.ts b/services/mcp/src/tools/generated/streamlit_apps.ts
index 342a8205fc9c..fbd82804e497 100644
--- a/services/mcp/src/tools/generated/streamlit_apps.ts
+++ b/services/mcp/src/tools/generated/streamlit_apps.ts
@@ -126,6 +126,12 @@ const StreamlitAppsSetSourceSchema = () => {
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."
),
+ files: StreamlitAppsCreateVersionFromSourceCreateBody.shape['files'].describe(
+ 'Optional extra text files keyed by project-relative path (e.g. `utils.py`, `data/config.json`), each value the file\'s full text. Paths must not be `app.py` and must not contain `..`. The app process does not run inside its own directory, so open them via `Path(__file__).parent / "data/config.json"`.'
+ ),
+ assets: StreamlitAppsCreateVersionFromSourceCreateBody.shape['assets'].describe(
+ "Optional extra binary files keyed by project-relative path (e.g. `data/events.parquet`), each value the file's bytes as standard base64. Same path rules as `files`. Keep them small: the whole call is sent as JSON, so a large file costs tokens on every set-source."
+ ),
})
}
@@ -141,6 +147,12 @@ const streamlitAppsSetSource = (): ToolBase<
if (params.source !== undefined) {
body['source'] = params.source
}
+ if (params.files !== undefined) {
+ body['files'] = params.files
+ }
+ if (params.assets !== undefined) {
+ body['assets'] = params.assets
+ }
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/`,