Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10201: Treat MCP calls like frontend calls (#6138)
Cindy Li2803b6dfaec5
diff --git a/skyvern/cli/core/client.py b/skyvern/cli/core/client.pyindex af68a0563..59d986637 100644--- a/skyvern/cli/core/client.py+++ b/skyvern/cli/core/client.py@@ -10,6 +10,7 @@ import structlogfrom skyvern.client import SkyvernEnvironmentfrom skyvern.config import settings+from skyvern.constants import SKYVERN_MCP_USER_AGENTfrom skyvern.library.skyvern import Skyvernfrom .api_key_hash import hash_api_key_for_cache@@ -67,6 +68,7 @@ def _build_cloud_client(api_key: str) -> Skyvern:api_key=api_key,environment=SkyvernEnvironment.CLOUD,base_url=base_url,+ headers={"x-user-agent": SKYVERN_MCP_USER_AGENT},)diff --git a/skyvern/constants.py b/skyvern/constants.pyindex 581afb082..104d91e70 100644--- a/skyvern/constants.py+++ b/skyvern/constants.py@@ -4,9 +4,10 @@ from pathlib import Path# This is the attribute name used to tag interactable elementsSKYVERN_ID_ATTR: str = "unique_id"-# Value sent in the x-user-agent header by the Skyvern UI. Used to distinguish UI-triggered-# runs from API/SDK callers (e.g. for trigger_type classification and routing strategy).+# Values sent in the x-user-agent header by first-party Skyvern clients. Used to distinguish+# UI- and MCP-triggered runs from API/SDK callers (e.g. for trigger_type classification and routing strategy).SKYVERN_UI_USER_AGENT: str = "skyvern-ui"+SKYVERN_MCP_USER_AGENT: str = "skyvern-mcp"SKYVERN_DIR = Path(__file__).parentREPO_ROOT_DIR = SKYVERN_DIR.parentdiff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 7912ecec6..684c4bb24 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -29,7 +29,6 @@ from skyvern import analyticsfrom skyvern._version import __version__from skyvern.analytics import get_oss_versionfrom skyvern.config import settings-from skyvern.constants import SKYVERN_UI_USER_AGENTfrom skyvern.exceptions import (MissingBrowserAddressError,SkyvernHTTPException,@@ -49,7 +48,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.curl_converter import curl_to_http_request_block_paramsfrom skyvern.forge.sdk.core.permissions.permission_checker_factory import PermissionCheckerFactoryfrom skyvern.forge.sdk.core.security import generate_skyvern_signature-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, WorkflowRunTriggerType+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenTypefrom skyvern.forge.sdk.executor.factory import AsyncExecutorFactoryfrom skyvern.forge.sdk.models import Stepfrom skyvern.forge.sdk.routes.code_samples import (@@ -77,6 +76,7 @@ from skyvern.forge.sdk.routes.code_samples import (UPDATE_WORKFLOW_CODE_SAMPLE_TS,)from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router, legacy_v2_router+from skyvern.forge.sdk.routes.trigger_type import workflow_run_trigger_type_from_user_agentfrom skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionBase, AISuggestionRequestfrom skyvern.forge.sdk.schemas.organizations import (GetOrganizationAPIKeysResponse,@@ -311,9 +311,7 @@ async def run_task()if run_request.engine == RunEngine.skyvern_v2:# create task v2- v2_trigger_type = (- WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api- )+ v2_trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)try:task_v2 = await task_v2_service.initialize_task_v2(organization=current_org,@@ -448,7 +446,7 @@ async def run_workflow(run_metadata=workflow_run_request.run_metadata,)- trigger_type = WorkflowRunTriggerType.manual if x_user_agent == "skyvern-ui" else WorkflowRunTriggerType.api+ trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)try:workflow_run = await workflow_service.run_workflow(workflow_id=workflow_id,@@ -1956,9 +1954,7 @@ async def run_block(block_labels=block_run_request.block_labels,)- block_trigger_type = (- WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api- )+ block_trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)workflow_run = await block_service.ensure_workflow_run(organization=organization,template=template,@@ -2633,7 +2629,7 @@ async def run_workflow_legacy()await app.RATE_LIMITER.rate_limit_submit_run(current_org.organization_id)- legacy_trigger_type = WorkflowRunTriggerType.manual if x_user_agent == "skyvern-ui" else WorkflowRunTriggerType.api+ legacy_trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)try:workflow_run = await workflow_service.run_workflow(workflow_id=workflow_id,@@ -3538,9 +3534,7 @@ async def run_task_v2(await PermissionCheckerFactory.get_instance().check(organization, browser_session_id=data.browser_session_id)await app.RATE_LIMITER.rate_limit_submit_run(organization.organization_id)- legacy_v2_trigger_type = (- WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api- )+ legacy_v2_trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)try:task_v2 = await task_v2_service.initialize_task_v2(organization=organization,diff --git a/skyvern/forge/sdk/routes/run_blocks.py b/skyvern/forge/sdk/routes/run_blocks.pyindex 22b8714cf..f5d5ff4cd 100644--- a/skyvern/forge/sdk/routes/run_blocks.py+++ b/skyvern/forge/sdk/routes/run_blocks.py@@ -4,11 +4,10 @@ import structlogfrom fastapi import BackgroundTasks, Depends, Header, HTTPException, Requestfrom skyvern.config import settings-from skyvern.constants import DEFAULT_LOGIN_PROMPT, SKYVERN_UI_USER_AGENT+from skyvern.constants import DEFAULT_LOGIN_PROMPTfrom skyvern.exceptions import MissingBrowserAddressErrorfrom skyvern.forge import appfrom skyvern.forge.sdk.core import skyvern_context-from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.routes.code_samples import (DOWNLOAD_FILES_CODE_SAMPLE_PYTHON,DOWNLOAD_FILES_CODE_SAMPLE_TS,@@ -20,6 +19,7 @@ from skyvern.forge.sdk.routes.code_samples import (LOGIN_CODE_SAMPLE_SKYVERN_TS,)from skyvern.forge.sdk.routes.routers import base_router+from skyvern.forge.sdk.routes.trigger_type import workflow_run_trigger_type_from_user_agentfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.services import org_auth_servicefrom skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterType@@ -79,9 +79,7 @@ async def _run_workflow_and_build_response(extra_http_headers=run_block_request.extra_http_headers,)- trigger_type = (- WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api- )+ trigger_type = workflow_run_trigger_type_from_user_agent(x_user_agent)try:workflow_run = await workflow_service.run_workflow(workflow_id=workflow_id,diff --git a/skyvern/forge/sdk/routes/trigger_type.py b/skyvern/forge/sdk/routes/trigger_type.pynew file mode 100644index 000000000..e8373a89d--- /dev/null+++ b/skyvern/forge/sdk/routes/trigger_type.py@@ -0,0 +1,10 @@+from skyvern.constants import SKYVERN_MCP_USER_AGENT, SKYVERN_UI_USER_AGENT+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType++_MANUAL_USER_AGENTS = frozenset({SKYVERN_UI_USER_AGENT, SKYVERN_MCP_USER_AGENT})+++def workflow_run_trigger_type_from_user_agent(x_user_agent: str | None) -> WorkflowRunTriggerType:+ if x_user_agent in _MANUAL_USER_AGENTS:+ return WorkflowRunTriggerType.manual+ return WorkflowRunTriggerType.apidiff --git a/skyvern/library/skyvern.py b/skyvern/library/skyvern.pyindex 3b308e7e0..521670623 100644--- a/skyvern/library/skyvern.py+++ b/skyvern/library/skyvern.py@@ -97,6 +97,7 @@ class Skyvern(AsyncSkyvern):api_key: str,environment: SkyvernEnvironment = SkyvernEnvironment.CLOUD,base_url: str | None = None,+ headers: dict[str, str] | None = None,timeout: float | None = None,follow_redirects: bool | None = True,httpx_client: httpx.AsyncClient | None = None,@@ -111,6 +112,7 @@ class Skyvern(AsyncSkyvern):instances. Defaults to SkyvernEnvironment.CLOUD.base_url: Override the base URL for the Skyvern API. If not provided, uses the default URL forthe specified environment.+ headers: Additional headers to send with every API request.timeout: Timeout in seconds for API requests. If not provided, uses the default timeout.follow_redirects: Whether to automatically follow HTTP redirects. Defaults to True.httpx_client: Custom httpx AsyncClient for making API requests.@@ -120,6 +122,7 @@ class Skyvern(AsyncSkyvern):base_url=base_url,environment=environment,api_key=api_key,+ headers=headers,timeout=timeout,follow_redirects=follow_redirects,httpx_client=httpx_client,diff --git a/tests/unit/forge/sdk/test_trigger_type.py b/tests/unit/forge/sdk/test_trigger_type.pynew file mode 100644index 000000000..82ae26835--- /dev/null+++ b/tests/unit/forge/sdk/test_trigger_type.py@@ -0,0 +1,19 @@+from skyvern.constants import SKYVERN_MCP_USER_AGENT, SKYVERN_UI_USER_AGENT+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+from skyvern.forge.sdk.routes.trigger_type import workflow_run_trigger_type_from_user_agent+++def test_workflow_run_trigger_type_from_user_agent_ui_returns_manual() -> None:+ assert workflow_run_trigger_type_from_user_agent(SKYVERN_UI_USER_AGENT) == WorkflowRunTriggerType.manual+++def test_workflow_run_trigger_type_from_user_agent_mcp_returns_manual() -> None:+ assert workflow_run_trigger_type_from_user_agent(SKYVERN_MCP_USER_AGENT) == WorkflowRunTriggerType.manual+++def test_workflow_run_trigger_type_from_user_agent_none_returns_api() -> None:+ assert workflow_run_trigger_type_from_user_agent(None) == WorkflowRunTriggerType.api+++def test_workflow_run_trigger_type_from_user_agent_unknown_returns_api() -> None:+ assert workflow_run_trigger_type_from_user_agent("some-other-client") == WorkflowRunTriggerType.apidiff --git a/tests/unit/test_mcp_session_lifecycle.py b/tests/unit/test_mcp_session_lifecycle.pyindex 40e9190bc..a48fb08c2 100644--- a/tests/unit/test_mcp_session_lifecycle.py+++ b/tests/unit/test_mcp_session_lifecycle.py@@ -12,6 +12,7 @@ from skyvern.cli.core.result import BrowserContextfrom skyvern.cli.core.session_ops import SessionCloseResult, coerce_proxy_locationfrom skyvern.cli.mcp_tools import session as mcp_sessionfrom skyvern.client.types.extensions import Extensions+from skyvern.constants import SKYVERN_MCP_USER_AGENTfrom skyvern.schemas.runs import GeoTarget, ProxyLocationCAPTCHA_SOLVER_EXTENSION: Extensions = "captcha-solver"@@ -186,6 +187,23 @@ def test_build_cloud_client_uses_self_url_in_stateless_mode(monkeypatch: pytest.base_url = captured_kwargs[0]["base_url"]assert isinstance(base_url, str)assert "127.0.0.1" in base_url+ assert captured_kwargs[0]["headers"] == {"x-user-agent": SKYVERN_MCP_USER_AGENT}+++def test_build_cloud_client_passes_mcp_user_agent_header(monkeypatch: pytest.MonkeyPatch) -> None:+ captured_kwargs: list[dict[str, object]] = []++ class FakeSkyvern:+ def __init__(self, *args: object, **kwargs: object) -> None:+ captured_kwargs.append(dict(kwargs))++ monkeypatch.setattr(client_mod, "Skyvern", FakeSkyvern)+ session_manager.set_stateless_http_mode(False)++ client_mod._build_cloud_client("sk_test")++ assert len(captured_kwargs) == 1+ assert captured_kwargs[0]["headers"] == {"x-user-agent": SKYVERN_MCP_USER_AGENT}def test_build_cloud_client_uses_settings_url_in_normal_mode(monkeypatch: pytest.MonkeyPatch) -> None:@@ -204,6 +222,7 @@ def test_build_cloud_client_uses_settings_url_in_normal_mode(monkeypatch: pytestassert len(captured_kwargs) == 1assert captured_kwargs[0]["base_url"] == "https://api-staging.skyvern.com"+ assert captured_kwargs[0]["headers"] == {"x-user-agent": SKYVERN_MCP_USER_AGENT}@pytest.mark.asyncio