Skip to content

Automate browser based workflows with AI

feat(tagging): Phase 1 schema + types (SKY-10100) (#6135)

Trevor Cheungfee3a1435abd
diff --git a/alembic/versions/2026_05_23_1202-729b4078a2e9_add_workflow_tag_tables.py b/alembic/versions/2026_05_23_1202-729b4078a2e9_add_workflow_tag_tables.py
new file mode 100644
index 000000000..488aba8cb
--- /dev/null
+++ b/alembic/versions/2026_05_23_1202-729b4078a2e9_add_workflow_tag_tables.py
@@ -0,0 +1,121 @@
+"""add workflow tag tables
+
+Revision ID: 729b4078a2e9
+Revises: d7e8f9a0b1c2
+Create Date: 2026-05-23T12:02:15.280583+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "729b4078a2e9"
+down_revision: Union[str, None] = "d7e8f9a0b1c2"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "tag_keys",
+ sa.Column("tag_key_id", sa.String(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("key", sa.String(), nullable=False),
+ sa.Column("description", sa.String(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("modified_at", sa.DateTime(), nullable=False),
+ sa.Column("deleted_at", sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(
+ ["organization_id"],
+ ["organizations.organization_id"],
+ ),
+ sa.PrimaryKeyConstraint("tag_key_id"),
+ )
+ op.create_index(
+ "ix_tag_keys_org_key_active",
+ "tag_keys",
+ ["organization_id", "key"],
+ unique=True,
+ postgresql_where=sa.text("deleted_at IS NULL"),
+ )
+ op.create_table(
+ "workflow_tag_events",
+ sa.Column("tag_event_id", sa.String(), nullable=False),
+ sa.Column("workflow_permanent_id", sa.String(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("key", sa.String(), nullable=False),
+ sa.Column("value", sa.String(), nullable=True),
+ sa.Column("event_type", sa.String(), nullable=False),
+ sa.Column("set_at", sa.DateTime(), nullable=False),
+ sa.Column("set_by", sa.String(), nullable=False),
+ sa.Column("source", sa.String(), nullable=False),
+ sa.Column("superseded_at", sa.DateTime(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("modified_at", sa.DateTime(), nullable=False),
+ sa.Column("deleted_at", sa.DateTime(), nullable=True),
+ sa.CheckConstraint("event_type != 'delete' OR value IS NULL", name="ck_workflow_tag_events_delete_null_value"),
+ sa.CheckConstraint("event_type IN ('set', 'delete')", name="ck_workflow_tag_events_event_type"),
+ sa.CheckConstraint(
+ "source IN ('manual', 'bulk_apply', 'backfill', 'inherited', 'import')",
+ name="ck_workflow_tag_events_source",
+ ),
+ sa.ForeignKeyConstraint(
+ ["organization_id"],
+ ["organizations.organization_id"],
+ ),
+ sa.PrimaryKeyConstraint("tag_event_id"),
+ )
+ op.create_index(
+ "workflow_tag_events_active_set_unique",
+ "workflow_tag_events",
+ ["organization_id", "workflow_permanent_id", "key"],
+ unique=True,
+ postgresql_where=sa.text("superseded_at IS NULL AND event_type = 'set'"),
+ )
+ op.create_index(
+ "workflow_tag_events_org_key_value_active_idx",
+ "workflow_tag_events",
+ ["organization_id", "key", "value"],
+ unique=False,
+ postgresql_include=["workflow_permanent_id"],
+ postgresql_where=sa.text("superseded_at IS NULL AND event_type = 'set'"),
+ )
+ op.create_index(
+ "workflow_tag_events_org_set_at_idx", "workflow_tag_events", ["organization_id", "set_at"], unique=False
+ )
+ op.create_index(
+ "workflow_tag_events_org_wpid_key_set_at_idx",
+ "workflow_tag_events",
+ ["organization_id", "workflow_permanent_id", "key", "set_at"],
+ unique=False,
+ )
+ op.create_index(
+ "workflow_tag_events_org_wpid_set_at_idx",
+ "workflow_tag_events",
+ ["organization_id", "workflow_permanent_id", "set_at"],
+ unique=False,
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("workflow_tag_events_org_wpid_set_at_idx", table_name="workflow_tag_events")
+ op.drop_index("workflow_tag_events_org_wpid_key_set_at_idx", table_name="workflow_tag_events")
+ op.drop_index("workflow_tag_events_org_set_at_idx", table_name="workflow_tag_events")
+ op.drop_index(
+ "workflow_tag_events_org_key_value_active_idx",
+ table_name="workflow_tag_events",
+ postgresql_include=["workflow_permanent_id"],
+ postgresql_where=sa.text("superseded_at IS NULL AND event_type = 'set'"),
+ )
+ op.drop_index(
+ "workflow_tag_events_active_set_unique",
+ table_name="workflow_tag_events",
+ postgresql_where=sa.text("superseded_at IS NULL AND event_type = 'set'"),
+ )
+ op.drop_table("workflow_tag_events")
+ op.drop_index("ix_tag_keys_org_key_active", table_name="tag_keys", postgresql_where=sa.text("deleted_at IS NULL"))
+ op.drop_table("tag_keys")
diff --git a/docs/snippets/mcp-content.mdx b/docs/snippets/mcp-content.mdx
index 3df3883a3..e05cedf72 100644
--- a/docs/snippets/mcp-content.mdx
+++ b/docs/snippets/mcp-content.mdx
@@ -23,7 +23,7 @@ You have three ways to connect a client to Skyvern:
| | OAuth (sign in with browser) | API key | Local mode |
|---|---|---|---|
-| **Best for** | Claude Code, Codex CLI, Cursor, and other clients that support MCP OAuth | Claude Desktop, Windsurf, Hermes, OpenClaw, headless/CI flows, or any client where you prefer a static key | Self-hosting Skyvern |
+| **Best for** | Claude Code, Codex CLI, Cursor, ChatGPT, and other clients that support MCP OAuth | Claude Desktop, Windsurf, Hermes, OpenClaw, headless/CI flows, or any client where you prefer a static key | Self-hosting Skyvern |
| **Install required** | None | None | Python 3.11+ and `pip install "skyvern[server]"` |
| **Credential** | Browser sign-in with your Skyvern account | API key from [app.skyvern.com](https://app.skyvern.com) | API key from your self-hosted instance |
| **Where it runs** | Directly against Skyvern Cloud over HTTPS | Directly against Skyvern Cloud over HTTPS | Local Python process talking to your Skyvern server |
@@ -32,7 +32,7 @@ If your client appears in the OAuth section below, start there. Otherwise use th
## Option A: Sign in with browser (OAuth)
-Supported clients today: **Claude Code**, **Codex CLI**, **Cursor**, and other MCP clients that support remote HTTP servers with OAuth. Skyvern Cloud publishes standard MCP OAuth discovery metadata, so supported clients can start browser sign-in without a static `CLIENT_ID` or `CLIENT_SECRET` in your config.
+Supported clients today: **Claude Code**, **Codex CLI**, **Cursor**, **ChatGPT** (custom connector), and other MCP clients that support remote HTTP servers with OAuth. Skyvern Cloud publishes standard MCP OAuth discovery metadata, so supported clients can start browser sign-in without a static `CLIENT_ID` or `CLIENT_SECRET` in your config.
There is **no install step**. You do not need `pip install skyvern`, Node.js, or an API key.
@@ -67,6 +67,14 @@ If you previously configured Skyvern with an `x-api-key` header, run `codex mcp
</Tab>
<Tab title="Cursor">
+**One-click install** (Cursor 0.43+):
+
+[Install Skyvern in Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=Skyvern&config=eyJ0eXBlIjoic3RyZWFtYWJsZS1odHRwIiwidXJsIjoiaHR0cHM6Ly9hcGkuc2t5dmVybi5jb20vbWNwLyJ9)
+
+Click the link above (or copy-paste it into your browser's address bar). Cursor opens and prompts you to authenticate via browser sign-in. No manual JSON editing needed.
+
+**Manual fallback** (any Cursor release):
+
Add to `~/.cursor/mcp.json`:
```json
@@ -82,6 +90,21 @@ Add to `~/.cursor/mcp.json`:
Use a current Cursor release. Restart Cursor, open MCP settings, and authenticate the Skyvern server when prompted. If the prompt does not appear, update Cursor and reopen MCP settings. Cursor opens your browser for Skyvern sign-in and stores the token for future sessions.
+</Tab>
+<Tab title="ChatGPT">
+
+**ChatGPT custom connector (Developer Mode)**
+
+This is not the ChatGPT App Directory. You can add Skyvern as a custom MCP connector immediately without marketplace approval, provided your ChatGPT plan has the custom connector feature available (Plus, Team, and Enterprise plans).
+
+1. In ChatGPT, open **Settings → Connectors** (the path may vary by plan; look under **Integrations** or **Beta features** if Connectors is not visible).
+2. Click **Add connector** and choose the **MCP** type.
+3. Enter the Skyvern MCP URL: `https://api.skyvern.com/mcp/`
+4. ChatGPT detects OAuth support automatically. Follow the browser sign-in prompt to authenticate with your Skyvern account.
+5. Once connected, Skyvern tools appear in the tool panel. You can ask ChatGPT to navigate pages, fill forms, extract data, or run multi-step workflows.
+
+No API key is required — OAuth handles authentication. If your account does not yet show the Connectors option, check **Settings → Beta features** to enable it.
+
</Tab>
</Tabs>
diff --git a/fern/integrations/mcp.mdx b/fern/integrations/mcp.mdx
index 927bda3b9..bed257c05 100644
--- a/fern/integrations/mcp.mdx
+++ b/fern/integrations/mcp.mdx
@@ -86,6 +86,14 @@ This fallback uses [mcp-remote](https://www.npmjs.com/package/mcp-remote) to bri
</Tab>
<Tab title="Cursor">
+**One-click install** (Cursor 0.43+, OAuth — no API key required):
+
+[Install Skyvern in Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=Skyvern&config=eyJ0eXBlIjoic3RyZWFtYWJsZS1odHRwIiwidXJsIjoiaHR0cHM6Ly9hcGkuc2t5dmVybi5jb20vbWNwLyJ9)
+
+Click the link above (or copy-paste it into your browser's address bar). Cursor opens and prompts you to authenticate via browser sign-in.
+
+**Manual setup with API key:**
+
Add to `~/.cursor/mcp.json`:
```json
@@ -124,6 +132,16 @@ Add to `~/.codeium/windsurf/mcp_config.json`:
</Tab>
<Tab title="Codex">
+**OAuth (recommended, no API key required):**
+
+```bash
+codex mcp add skyvern --url https://api.skyvern.com/mcp/
+```
+
+Codex opens your browser for Skyvern sign-in and stores the token automatically. Requires `codex --version` ≥ 0.125.0.
+
+**Manual setup with API key** (headless or CI environments):
+
Add to `~/.codex/config.toml`:
```toml
@@ -141,6 +159,21 @@ To load the API key from an environment variable instead, use `env_http_headers`
x-api-key = "SKYVERN_API_KEY"
```
+</Tab>
+<Tab title="ChatGPT">
+
+**ChatGPT custom connector (Developer Mode)**
+
+This is not the ChatGPT App Directory. You can add Skyvern as a custom MCP connector immediately without marketplace approval, provided your ChatGPT plan has the custom connector feature available (Plus, Team, and Enterprise plans).
+
+1. In ChatGPT, open **Settings → Connectors** (look under **Integrations** or **Beta features** if Connectors is not visible).
+2. Click **Add connector** and choose the **MCP** type.
+3. Enter the Skyvern MCP URL: `https://api.skyvern.com/mcp/`
+4. ChatGPT detects OAuth support automatically. Follow the browser sign-in prompt to authenticate with your Skyvern account.
+5. Once connected, Skyvern tools appear in the tool panel for navigating pages, filling forms, extracting data, and running workflows.
+
+No API key is required — OAuth handles authentication.
+
</Tab>
</Tabs>
diff --git a/skyvern/forge/sdk/db/id.py b/skyvern/forge/sdk/db/id.py
index cf4ad8be7..4b2af1fb4 100644
--- a/skyvern/forge/sdk/db/id.py
+++ b/skyvern/forge/sdk/db/id.py
@@ -75,6 +75,8 @@ WORKFLOW_COPILOT_CHAT_PREFIX = "wcc"
WORKFLOW_COPILOT_CHAT_MESSAGE_PREFIX = "wccm"
SCRIPT_FALLBACK_EPISODE_PREFIX = "sfe"
WORKFLOW_SCHEDULE_PREFIX = "wfs"
+TAG_EVENT_PREFIX = "tge"
+TAG_KEY_PREFIX = "tkey"
def generate_workflow_id() -> str:
@@ -247,6 +249,16 @@ def generate_folder_id() -> str:
return f"{FOLDER_PREFIX}_{int_id}"
+def generate_tag_event_id() -> str:
+ int_id = generate_id()
+ return f"{TAG_EVENT_PREFIX}_{int_id}"
+
+
+def generate_tag_key_id() -> str:
+ int_id = generate_id()
+ return f"{TAG_KEY_PREFIX}_{int_id}"
+
+
def generate_google_oauth_credential_id() -> str:
int_id = generate_id()
return f"{GOOGLE_OAUTH_CREDENTIAL_PREFIX}_{int_id}"
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 51a8858ee..16e0c353e 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -5,6 +5,7 @@ from sqlalchemy import (
JSON,
BigInteger,
Boolean,
+ CheckConstraint,
Column,
DateTime,
ForeignKey,
@@ -50,6 +51,8 @@ from skyvern.forge.sdk.db.id import (
generate_script_id,
generate_script_revision_id,
generate_step_id,
+ generate_tag_event_id,
+ generate_tag_key_id,
generate_task_generation_id,
generate_task_id,
generate_task_run_id,
@@ -301,6 +304,115 @@ class FolderModel(Base):
deleted_at = Column(DateTime, nullable=True)
+class WorkflowTagEventModel(Base):
+ """Append-only event log for workflow tags.
+
+ Every state change writes a new row. SET events carry value; DELETE
+ events have value=NULL and carry their own attribution. Supersession
+ sets superseded_at on the previously-current row so the partial unique
+ index keeps exactly one active SET per (org, wpid, key). superseded_at
+ means "no longer current but still historical fact"; deleted_at follows
+ the same soft-delete convention as SoftDeleteMixin (via a manual column)
+ and is separate.
+
+ workflow_permanent_id is intentionally NOT a foreign key: WorkflowModel
+ only has a unique constraint on (organization_id, workflow_permanent_id,
+ version), so the column itself isn't a valid FK target. Mirrors
+ WorkflowScheduleModel; integrity enforced at app level.
+ """
+
+ __tablename__ = "workflow_tag_events"
+ # workflow_permanent_id has no single-column index: it's only ever queried alongside
+ # organization_id, so the (organization_id, workflow_permanent_id, ...) composites below
+ # cover it. Skipping the redundant index saves write throughput on this append-only table.
+ __table_args__ = (
+ Index("workflow_tag_events_org_wpid_set_at_idx", "organization_id", "workflow_permanent_id", "set_at"),
+ Index(
+ "workflow_tag_events_org_wpid_key_set_at_idx",
+ "organization_id",
+ "workflow_permanent_id",
+ "key",
+ "set_at",
+ ),
+ Index(
+ "workflow_tag_events_org_key_value_active_idx",
+ "organization_id",
+ "key",
+ "value",
+ postgresql_include=["workflow_permanent_id"],
+ postgresql_where=text("superseded_at IS NULL AND event_type = 'set'"),
+ ),
+ Index("workflow_tag_events_org_set_at_idx", "organization_id", "set_at"),
+ Index(
+ "workflow_tag_events_active_set_unique",
+ "organization_id",
+ "workflow_permanent_id",
+ "key",
+ unique=True,
+ postgresql_where=text("superseded_at IS NULL AND event_type = 'set'"),
+ ),
+ CheckConstraint("event_type IN ('set', 'delete')", name="ck_workflow_tag_events_event_type"),
+ CheckConstraint(
+ "source IN ('manual', 'bulk_apply', 'backfill', 'inherited', 'import')",
+ name="ck_workflow_tag_events_source",
+ ),
+ CheckConstraint("event_type != 'delete' OR value IS NULL", name="ck_workflow_tag_events_delete_null_value"),
+ )
+
+ tag_event_id = Column(String, primary_key=True, default=generate_tag_event_id)
+ workflow_permanent_id = Column(String, nullable=False)
+ organization_id = Column(String, ForeignKey("organizations.organization_id"), nullable=False)
+ key = Column(String, nullable=False)
+ value = Column(String, nullable=True)
+ event_type = Column(String, nullable=False)
+ set_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ set_by = Column(String, nullable=False)
+ source = Column(String, nullable=False)
+ superseded_at = Column(DateTime, nullable=True)
+
+ created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ modified_at = Column(
+ DateTime,
+ default=datetime.datetime.utcnow,
+ onupdate=datetime.datetime.utcnow,
+ nullable=False,
+ )
+ deleted_at = Column(DateTime, nullable=True)
+
+
+class TagKeyModel(Base):
+ """Org-scoped registry of tag keys and their descriptions.
+
+ Auto-upserted on first use of a new key via INSERT ... ON CONFLICT
+ (organization_id, key) WHERE deleted_at IS NULL DO UPDATE.
+ """
+
+ __tablename__ = "tag_keys"
+ __table_args__ = (
+ Index(
+ "ix_tag_keys_org_key_active",
+ "organization_id",
+ "key",
+ unique=True,
+ postgresql_where=text("deleted_at IS NULL"),
+ ),
+ )
+
+ tag_key_id = Column(String, primary_key=True, default=generate_tag_key_id)
+ organization_id = Column(String, ForeignKey("organizations.organization_id"), nullable=False)
+ key = Column(String, nullable=False)
+ description = Column(String, nullable=True)
+
+ created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ modified_at = Column(
+ DateTime,
+ default=datetime.datetime.utcnow,
+ onupdate=datetime.datetime.utcnow,
+ nullable=False,
+ )
+ deleted_at = Column(DateTime, nullable=True)
+
+
# TODO: ~22 other models with manual deleted_at columns could inherit SoftDeleteMixin.
# WorkflowModel is the proof of concept; remaining models will be migrated in a follow-up PR.
class WorkflowModel(SoftDeleteMixin, Base):
diff --git a/skyvern/forge/sdk/workflow/models/tags.py b/skyvern/forge/sdk/workflow/models/tags.py
new file mode 100644
index 000000000..8b4bcb462
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/models/tags.py
@@ -0,0 +1,38 @@
+from dataclasses import dataclass
+from enum import StrEnum
+
+
+class TagSource(StrEnum):
+ """Provenance source for a tag-event row."""
+
+ MANUAL = "manual" # set by a person through the UI or API
+ BULK_APPLY = "bulk_apply" # set as part of a multi-workflow bulk operation
+ BACKFILL = "backfill" # written by a one-off migration/script over existing rows
+ INHERITED = "inherited" # copied from a parent (e.g. folder) rather than set directly
+ IMPORT = "import" # ingested from an external system
+
+
+class TagEventType(StrEnum):
+ """Kind of state change recorded in the event log.
+
+ DELETE events have value=NULL and carry their own attribution
+ (set_by / set_at / source).
+ """
+
+ SET = "set"
+ DELETE = "delete"
+
+
+class CallerType(StrEnum):
+ USER = "user"
+ API_KEY = "api_key"
+ SYSTEM = "system"
+
+
+@dataclass(frozen=True)
+class TagWriteContext:
+ """Attribution carried from a write call into the repository layer."""
+
+ caller_id: str
+ caller_type: CallerType
+ source: TagSource
diff --git a/skyvern/forge/sdk/workflow/models/validators.py b/skyvern/forge/sdk/workflow/models/validators.py
index 4a8d2b126..f9c66e0bf 100644
--- a/skyvern/forge/sdk/workflow/models/validators.py
+++ b/skyvern/forge/sdk/workflow/models/validators.py
@@ -1,3 +1,5 @@
+import re
+
import structlog
LOG = structlog.get_logger()
@@ -10,6 +12,17 @@ RUN_METADATA_MAX_KEYS = 20
RUN_METADATA_MAX_KEY_LENGTH = 64
RUN_METADATA_MAX_VALUE_LENGTH = 256
+TAG_DESCRIPTION_MAX_LENGTH = 500
+# Reserved for system-written tags. Uses a regex-valid separator so the
+# reservation actually excludes keys a user could otherwise create.
+SKYVERN_TAG_NAMESPACE = "skyvern."
+# Anchored regex: keys must be URL-safe so they round-trip through path
+# (`DELETE .../tags/{key}`) and query (`?tags=k:v`) without escaping.
+_TAG_KEY_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
+# `,` separates pairs in the `?tags=k:v,k2:v2` filter encoding, so it may not
+# appear inside a value. `:` is allowed: the parser splits on the first `:` only.
+_TAG_VALUE_FORBIDDEN_CHARS = (",",)
+
def normalize_run_with(v: str | None) -> str:
"""Normalize null and legacy values to valid run_with values.
@@ -27,13 +40,25 @@ def normalize_run_with(v: str | None) -> str:
return v
-def normalize_run_metadata(v: dict[str, str] | None) -> dict[str, str] | None:
- """Normalize and bound user-supplied workflow run metadata tags."""
+def _normalize_kv_dict(
+ v: dict[str, str] | None,
+ *,
+ max_keys: int,
+ max_key_length: int,
+ max_value_length: int,
+ field_name: str,
+) -> dict[str, str] | None:
+ """Shared cap + trim + skip-empty pass over a str→str dict.
+
+ Caller layers extra rules (regex, namespace, value-char restrictions)
+ on top of the returned dict. Returns None when the input is None or
+ every entry was skipped as empty.
+ """
if v is None:
return None
- if len(v) > RUN_METADATA_MAX_KEYS:
- raise ValueError(f"run_metadata can include at most {RUN_METADATA_MAX_KEYS} entries")
+ if len(v) > max_keys:
+ raise ValueError(f"{field_name} can include at most {max_keys} entries")
normalized: dict[str, str] = {}
for key, value in v.items():
@@ -41,10 +66,65 @@ def normalize_run_metadata(v: dict[str, str] | None) -> dict[str, str] | None:
trimmed_value = value.strip()
if not trimmed_key or not trimmed_value:
continue
- if len(trimmed_key) > RUN_METADATA_MAX_KEY_LENGTH:
- raise ValueError(f"run_metadata keys must be at most {RUN_METADATA_MAX_KEY_LENGTH} characters")
- if len(trimmed_value) > RUN_METADATA_MAX_VALUE_LENGTH:
- raise ValueError(f"run_metadata values must be at most {RUN_METADATA_MAX_VALUE_LENGTH} characters")
+ if len(trimmed_key) > max_key_length:
+ raise ValueError(f"{field_name} keys must be at most {max_key_length} characters")
+ if len(trimmed_value) > max_value_length:
+ raise ValueError(f"{field_name} values must be at most {max_value_length} characters")
normalized[trimmed_key] = trimmed_value
return normalized or None
+
+
+def normalize_run_metadata(v: dict[str, str] | None) -> dict[str, str] | None:
+ """Normalize and bound user-supplied workflow run metadata tags."""
+ return _normalize_kv_dict(
+ v,
+ max_keys=RUN_METADATA_MAX_KEYS,
+ max_key_length=RUN_METADATA_MAX_KEY_LENGTH,
+ max_value_length=RUN_METADATA_MAX_VALUE_LENGTH,
+ field_name="run_metadata",
+ )
+
+
+def normalize_tags(v: dict[str, str] | None) -> dict[str, str] | None:
+ """Normalize and bound user-supplied workflow tags.
+
+ Stricter than normalize_run_metadata: keys must match a URL-safe regex
+ and may not start with the reserved ``skyvern.`` prefix, and values may
+ not contain ``,`` (which would break ``?tags=`` pair parsing).
+ """
+ normalized = _normalize_kv_dict(
+ v,
+ max_keys=RUN_METADATA_MAX_KEYS,
+ max_key_length=RUN_METADATA_MAX_KEY_LENGTH,
+ max_value_length=RUN_METADATA_MAX_VALUE_LENGTH,
+ field_name="tags",
+ )
+ if normalized is None:
+ return None
+
+ for key, value in normalized.items():
+ if key.startswith(SKYVERN_TAG_NAMESPACE):
+ raise ValueError(f"tags keys must not start with the reserved '{SKYVERN_TAG_NAMESPACE}' prefix")
+ if not _TAG_KEY_REGEX.match(key):
+ raise ValueError(
+ "tags keys must match '^[A-Za-z0-9][A-Za-z0-9_.-]*$' "
+ "(alphanumeric, underscore, dot, hyphen; must start with alphanumeric)"
+ )
+ for forbidden in _TAG_VALUE_FORBIDDEN_CHARS:
+ if forbidden in value:
+ raise ValueError(f"tags values must not contain '{forbidden}'")
+
+ return normalized
+
+
+def normalize_tag_description(v: str | None) -> str | None:
+ """Trim and length-bound a tag-key description; return None when empty."""
+ if v is None:
+ return None
+ trimmed = v.strip()
+ if not trimmed:
+ return None
+ if len(trimmed) > TAG_DESCRIPTION_MAX_LENGTH:
+ raise ValueError(f"tag description must be at most {TAG_DESCRIPTION_MAX_LENGTH} characters")
+ return trimmed
diff --git a/tests/unit/test_tag_validators.py b/tests/unit/test_tag_validators.py
new file mode 100644
index 000000000..d7e030323
--- /dev/null
+++ b/tests/unit/test_tag_validators.py
@@ -0,0 +1,156 @@
+import pytest
+
+from skyvern.forge.sdk.workflow.models.validators import (
+ RUN_METADATA_MAX_KEY_LENGTH,
+ RUN_METADATA_MAX_KEYS,
+ RUN_METADATA_MAX_VALUE_LENGTH,
+ TAG_DESCRIPTION_MAX_LENGTH,
+ normalize_run_metadata,
+ normalize_tag_description,
+ normalize_tags,
+)
+
+
+class TestNormalizeRunMetadataUnchanged:
+ """Lock the existing normalize_run_metadata contract through the shared-core refactor."""
+
+ def test_none_passes_through(self) -> None:
+ assert normalize_run_metadata(None) is None
+
+ def test_strips_whitespace(self) -> None:
+ assert normalize_run_metadata({" customer ": " acme "}) == {"customer": "acme"}
+
+ def test_skips_empty_values(self) -> None:
+ assert normalize_run_metadata({"a": "v", "b": "", "c": " "}) == {"a": "v"}
+
+ def test_all_empty_returns_none(self) -> None:
+ assert normalize_run_metadata({"": "", " ": " "}) is None
+
+ def test_over_max_keys_raises(self) -> None:
+ too_many = {f"k{i}": "v" for i in range(RUN_METADATA_MAX_KEYS + 1)}
+ with pytest.raises(ValueError, match="at most"):
+ normalize_run_metadata(too_many)
+
+ def test_key_too_long_raises(self) -> None:
+ with pytest.raises(ValueError, match="keys must be at most"):
+ normalize_run_metadata({"k" * (RUN_METADATA_MAX_KEY_LENGTH + 1): "v"})
+
+ def test_value_too_long_raises(self) -> None:
+ with pytest.raises(ValueError, match="values must be at most"):
+ normalize_run_metadata({"k": "v" * (RUN_METADATA_MAX_VALUE_LENGTH + 1)})
+
+ def test_run_metadata_permits_punctuation_in_keys(self) -> None:
+ # Existing shipped behavior: run_metadata does NOT restrict key characters.
+ # Only normalize_tags applies the stricter regex.
+ assert normalize_run_metadata({"weird:key": "v"}) == {"weird:key": "v"}
+ assert normalize_run_metadata({"k": "value,with,commas"}) == {"k": "value,with,commas"}
+
+
+class TestNormalizeTagsCaps:
+ def test_none_passes_through(self) -> None:
+ assert normalize_tags(None) is None
+
+ def test_strips_whitespace(self) -> None:
+ assert normalize_tags({" env ": " prod "}) == {"env": "prod"}
+
+ def test_skips_empty_pairs(self) -> None:
+ assert normalize_tags({"a": "v", "b": "", "c": " "}) == {"a": "v"}
+
+ def test_over_max_keys_raises(self) -> None:
+ too_many = {f"k{i}": "v" for i in range(RUN_METADATA_MAX_KEYS + 1)}
+ with pytest.raises(ValueError, match="at most"):
+ normalize_tags(too_many)
+
+ def test_key_too_long_raises(self) -> None:
+ with pytest.raises(ValueError, match="keys must be at most"):
+ normalize_tags({"k" * (RUN_METADATA_MAX_KEY_LENGTH + 1): "v"})
+
+ def test_value_too_long_raises(self) -> None:
+ with pytest.raises(ValueError, match="values must be at most"):
+ normalize_tags({"k": "v" * (RUN_METADATA_MAX_VALUE_LENGTH + 1)})
+
+
+class TestNormalizeTagsKeyRegex:
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "env",
+ "customer.id",
+ "team_name",
+ "use-case",
+ "Env",
+ "k1",
+ "a",
+ "A1.b-c_d",
+ ],
+ )
+ def test_valid_keys_accepted(self, key: str) -> None:
+ assert normalize_tags({key: "v"}) == {key: "v"}
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "key:with:colons",
+ "key,with,commas",
+ "key/with/slashes",
+ "key?with?question",
+ "key#hash",
+ "key=equals",
+ "key&amp",
+ "key with space",
+ "_leading_underscore",
+ ".leading.dot",
+ "-leading-dash",
+ ],
+ )
+ def test_invalid_keys_rejected(self, key: str) -> None:
+ with pytest.raises(ValueError, match="must match"):
+ normalize_tags({key: "v"})
+
+
+class TestNormalizeTagsValueRestrictions:
+ def test_comma_in_value_rejected(self) -> None:
+ with pytest.raises(ValueError, match="must not contain ','"):
+ normalize_tags({"k": "value,with,comma"})
+
+ def test_colon_in_value_allowed(self) -> None:
+ # `:` is fine in values: the ?tags= parser splits on the first ':' only.
+ assert normalize_tags({"env": "staging:us-east-1"}) == {"env": "staging:us-east-1"}
+
+ def test_value_allows_other_punctuation(self) -> None:
+ assert normalize_tags({"k": "value with spaces.and-dashes_and!special"}) == {
+ "k": "value with spaces.and-dashes_and!special"
+ }
+
+
+class TestNormalizeTagsReservedNamespace:
+ @pytest.mark.parametrize(
+ "key",
+ ["skyvern.trigger_type", "skyvern.managed", "skyvern.foo"],
+ )
+ def test_skyvern_prefix_rejected(self, key: str) -> None:
+ with pytest.raises(ValueError, match="reserved"):
+ normalize_tags({key: "v"})
+
+ def test_skyvern_inside_key_allowed(self) -> None:
+ # Only the `skyvern.` prefix is reserved; substring is fine.
+ assert normalize_tags({"my-skyvern": "v"}) == {"my-skyvern": "v"}
+
+ def test_bare_skyvern_key_allowed(self) -> None:
+ # 'skyvern' without the dot separator is not the reserved prefix.
+ assert normalize_tags({"skyvern": "v"}) == {"skyvern": "v"}
+
+
+class TestNormalizeTagDescription:
+ def test_none_passes_through(self) -> None:
+ assert normalize_tag_description(None) is None
+
+ def test_strips_whitespace(self) -> None:
+ assert normalize_tag_description(" hello ") == "hello"
+
+ def test_empty_after_strip_returns_none(self) -> None:
+ assert normalize_tag_description(" ") is None
+
+ def test_over_max_length_raises(self) -> None:
+ with pytest.raises(ValueError, match="at most"):
+ normalize_tag_description("x" * (TAG_DESCRIPTION_MAX_LENGTH + 1))