Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Support GeoTarget proxies for MCP browser sessions (#5764)
Marc Kelechava12c33e91c940
diff --git a/docs/docs.json b/docs/docs.jsonindex 2ef40df55..b0be62ff6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -371,14 +371,13 @@"navbar": {"links": [{- "label": "Talk to us",- "href": "https://www.skyvern.com/contact"+ "label": "Try it now",+ "href": "https://app.skyvern.com/settings"}],"primary": {- "type": "button",- "label": "Get Started",- "href": "https://app.skyvern.com/"+ "type": "github",+ "href": "https://github.com/Skyvern-AI/skyvern"}},"footer": {diff --git a/skyvern/cli/core/session_ops.py b/skyvern/cli/core/session_ops.pyindex 4e3014eb2..73b779349 100644--- a/skyvern/cli/core/session_ops.py+++ b/skyvern/cli/core/session_ops.py@@ -2,10 +2,11 @@from __future__ import annotations+import jsonfrom dataclasses import dataclassfrom typing import Any-from skyvern.schemas.runs import ProxyLocation+from skyvern.schemas.runs import GeoTarget, ProxyLocation, ProxyLocationInput@dataclass@@ -32,10 +33,34 @@ class SessionInfo:available: bool = False+def coerce_proxy_location(proxy_location: ProxyLocationInput | str | None) -> ProxyLocationInput:+ if proxy_location is None or isinstance(proxy_location, (GeoTarget, ProxyLocation)):+ return proxy_location+ if isinstance(proxy_location, dict):+ return GeoTarget.model_validate(proxy_location)++ stripped = proxy_location.strip()+ try:+ parsed_proxy_location = json.loads(stripped)+ except json.JSONDecodeError:+ pass+ else:+ if isinstance(parsed_proxy_location, dict):+ return GeoTarget.model_validate(parsed_proxy_location)+ raise ValueError("Proxy location JSON must be a GeoTarget object.")++ try:+ return ProxyLocation(stripped)+ except ValueError as exc:+ raise ValueError(+ f"Unknown proxy location: {stripped!r}. Expected a valid enum value or a GeoTarget JSON object."+ ) from exc++async def do_session_create(skyvern: Any,timeout: int = 60,- proxy_location: str | None = None,+ proxy_location: ProxyLocationInput | str | None = None,local: bool = False,headless: bool = False,) -> tuple[Any, SessionCreateResult]:@@ -44,7 +69,7 @@ async def do_session_create(browser = await skyvern.launch_local_browser(headless=headless)return browser, SessionCreateResult(session_id=None, local=True, headless=headless)- proxy = ProxyLocation(proxy_location) if proxy_location else None+ proxy = coerce_proxy_location(proxy_location)browser = await skyvern.launch_cloud_browser(timeout=timeout, proxy_location=proxy)return browser, SessionCreateResult(session_id=browser.browser_session_id,diff --git a/skyvern/cli/mcp_tools/session.py b/skyvern/cli/mcp_tools/session.pyindex ea3e7e3b3..11aba55c0 100644--- a/skyvern/cli/mcp_tools/session.py+++ b/skyvern/cli/mcp_tools/session.py@@ -8,8 +8,8 @@ from pydantic import Fieldfrom skyvern.cli.core.api_key_hash import hash_api_key_for_cachefrom skyvern.cli.core.client import get_active_api_keyfrom skyvern.cli.core.session_manager import is_stateless_http_mode-from skyvern.cli.core.session_ops import do_session_close, do_session_create, do_session_list-from skyvern.schemas.runs import ProxyLocation+from skyvern.cli.core.session_ops import coerce_proxy_location, do_session_close, do_session_create, do_session_list+from skyvern.schemas.runs import proxy_location_to_requestfrom ._common import BrowserContext, ErrorCode, Timer, make_error, make_resultfrom ._session import (@@ -39,7 +39,15 @@ def _should_default_to_cdp() -> tuple[bool, str | None]:async def skyvern_browser_session_create(timeout: Annotated[int | None, Field(description="Session timeout in minutes (5-1440)")] = 60,- proxy_location: Annotated[str | None, Field(description="Proxy location: RESIDENTIAL, US, etc.")] = None,+ proxy_location: Annotated[+ str | dict[str, Any] | None,+ Field(+ description=(+ "Proxy location as a legacy enum string like RESIDENTIAL, or a GeoTarget object like "+ '{"country":"US","subdivision":"CA","city":"San Francisco"}.'+ )+ ),+ ] = None,local: Annotated[bool, Field(description="Launch local browser instead of cloud")] = False,headless: Annotated[bool, Field(description="Run local browser in headless mode")] = False,) -> dict[str, Any]:@@ -91,7 +99,7 @@ async def skyvern_browser_session_create(skyvern = get_skyvern()if is_stateless_http_mode():- proxy = ProxyLocation(proxy_location) if proxy_location else None+ proxy = proxy_location_to_request(coerce_proxy_location(proxy_location))session = await skyvern.create_browser_session(timeout=timeout or 60, proxy_location=proxy)timer.mark("sdk")ctx = BrowserContext(mode="cloud_session", session_id=session.browser_session_id)@@ -108,7 +116,7 @@ async def skyvern_browser_session_create(browser, result = await do_session_create(skyvern,timeout=timeout or 60,- proxy_location=proxy_location,+ proxy_location=coerce_proxy_location(proxy_location),local=local,headless=headless,)diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.pyindex 05f4a5b5c..40211615f 100644--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py@@ -410,6 +410,7 @@ class WorkflowRunsRepository(BaseRepository):.join(WorkflowModel, WorkflowModel.workflow_id == WorkflowRunModel.workflow_id).filter(WorkflowRunModel.organization_id == organization_id).filter(WorkflowRunModel.parent_workflow_run_id.is_(None))+ .filter(WorkflowRunModel.copilot_session_id.is_(None)))if not include_debugger_runs:@@ -519,6 +520,7 @@ class WorkflowRunsRepository(BaseRepository):.filter(TaskRunModel.status.isnot(None)).filter(TaskRunModel.parent_workflow_run_id.is_(None)).filter(TaskRunModel.debug_session_id.is_(None))+ .filter(WorkflowRunModel.copilot_session_id.is_(None)))if status:@@ -799,6 +801,7 @@ class WorkflowRunsRepository(BaseRepository):.join(WorkflowModel, WorkflowModel.workflow_id == WorkflowRunModel.workflow_id).filter(WorkflowRunModel.organization_id == organization_id).filter(WorkflowRunModel.parent_workflow_run_id.is_(None))+ .filter(WorkflowRunModel.copilot_session_id.is_(None)))query = self._apply_search_key_filter(query, search_key)@@ -916,6 +919,7 @@ class WorkflowRunsRepository(BaseRepository):.join(WorkflowModel, WorkflowModel.workflow_id == WorkflowRunModel.workflow_id).filter(WorkflowRunModel.workflow_permanent_id == workflow_permanent_id).filter(WorkflowRunModel.organization_id == organization_id)+ .filter(WorkflowRunModel.copilot_session_id.is_(None)))query = self._apply_search_key_filter(query, search_key)query = self._apply_error_code_filter(query, error_code)diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex fe8200458..7e259fbe5 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -106,7 +106,11 @@ def _safe_trigger_type(raw: str | None) -> WorkflowRunTriggerType | None:return None-def _deserialize_proxy_location(value: str | None) -> ProxyLocationInput:+def deserialize_proxy_location(+ value: str | None,+ *,+ raise_on_invalid_geo_target: bool = False,+) -> ProxyLocationInput:"""Deserialize proxy_location from database storage.@@ -118,12 +122,16 @@ def _deserialize_proxy_location(value: str | None) -> ProxyLocationInput:if value is None:return None+ value = value.strip()result: ProxyLocationInput = None# Try to parse as JSON first (for GeoTarget)if value.startswith("{"):try:data = json.loads(value)+ if not isinstance(data, dict):+ raise ValueError("GeoTarget proxy_location JSON must be an object")+# Handle malformed subdivision (e.g., boolean instead of string)subdivision = data.get("subdivision")if subdivision is not None and not isinstance(subdivision, str):@@ -137,6 +145,8 @@ def _deserialize_proxy_location(value: str | None) -> ProxyLocationInput:)return resultexcept (json.JSONDecodeError, ValueError) as e:+ if raise_on_invalid_geo_target:+ raiseLOG.warning("Failed to parse proxy_location as GeoTarget", db_value=value, error=str(e))# Try as ProxyLocation enum@@ -163,9 +173,10 @@ def serialize_proxy_location(proxy_location: ProxyLocationInput) -> str | None:result = json.dumps(proxy_location.model_dump())elif isinstance(proxy_location, dict):result = json.dumps(proxy_location)+ elif isinstance(proxy_location, ProxyLocation):+ result = proxy_location.valueelse:- # ProxyLocation enum - return the string value- result = str(proxy_location)+ raise TypeError(f"Unsupported proxy_location type: {type(proxy_location).__name__}")LOG.debug("Serializing proxy_location for DB",@@ -236,7 +247,7 @@ def convert_to_task(task_obj: TaskModel, debug_enabled: bool = False, workflow_pextracted_information=task_obj.extracted_information,failure_reason=task_obj.failure_reason,organization_id=task_obj.organization_id,- proxy_location=_deserialize_proxy_location(task_obj.proxy_location),+ proxy_location=deserialize_proxy_location(task_obj.proxy_location),extracted_information_schema=task_obj.extracted_information_schema,extra_http_headers=task_obj.extra_http_headers,workflow_run_id=task_obj.workflow_run_id,@@ -266,7 +277,7 @@ def convert_to_task_v2(task_v2_model: TaskV2Model, debug_enabled: bool = False)LOG.debug("Converting TaskV2Model to TaskV2", observer_cruise_id=task_v2_model.observer_cruise_id)task_v2_data = {column.name: getattr(task_v2_model, column.name) for column in TaskV2Model.__table__.columns}# Deserialize proxy_location FIRST (string → GeoTarget), otherwise model_validate will fail for city/state proxy selections- task_v2_data["proxy_location"] = _deserialize_proxy_location(task_v2_model.proxy_location)+ task_v2_data["proxy_location"] = deserialize_proxy_location(task_v2_model.proxy_location)return TaskV2.model_validate(task_v2_data)@@ -421,7 +432,7 @@ def convert_to_workflow(totp_identifier=workflow_model.totp_identifier,persist_browser_session=workflow_model.persist_browser_session,model=workflow_model.model,- proxy_location=_deserialize_proxy_location(workflow_model.proxy_location),+ proxy_location=deserialize_proxy_location(workflow_model.proxy_location),max_screenshot_scrolls=workflow_model.max_screenshot_scrolling_times,version=workflow_model.version,is_saved_task=workflow_model.is_saved_task,@@ -468,7 +479,7 @@ def convert_to_workflow_run(browser_profile_id=workflow_run_model.browser_profile_id,status=WorkflowRunStatus[workflow_run_model.status],failure_reason=workflow_run_model.failure_reason,- proxy_location=_deserialize_proxy_location(workflow_run_model.proxy_location),+ proxy_location=deserialize_proxy_location(workflow_run_model.proxy_location),webhook_callback_url=workflow_run_model.webhook_callback_url,webhook_failure_reason=workflow_run_model.webhook_failure_reason,totp_verification_url=workflow_run_model.totp_verification_url,diff --git a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py b/skyvern/forge/sdk/schemas/persistent_browser_sessions.pyindex 79e9d1b1a..4ae1c8cd3 100644--- a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py+++ b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py@@ -2,9 +2,10 @@ from datetime import datetimefrom decimal import Decimalfrom enum import StrEnum-from pydantic import BaseModel, ConfigDict+from pydantic import BaseModel, ConfigDict, field_validator-from skyvern.schemas.runs import ProxyLocation+from skyvern.forge.sdk.db.utils import deserialize_proxy_location+from skyvern.schemas.runs import ProxyLocationInputclass PersistentBrowserSessionStatus(StrEnum):@@ -56,7 +57,7 @@ class PersistentBrowserSession(BaseModel):ip_address: str | None = Nonestatus: str | None = Nonetimeout_minutes: int | None = None- proxy_location: ProxyLocation | None = None+ proxy_location: ProxyLocationInput = Noneinstance_type: str | None = Nonevcpu_millicores: int | None = Nonememory_mb: int | None = None@@ -71,6 +72,13 @@ class PersistentBrowserSession(BaseModel):browser_type: PersistentBrowserType | None = Nonebrowser_profile_id: str | None = None+ @field_validator("proxy_location", mode="before")+ @classmethod+ def deserialize_proxy_location_field(cls, value: object) -> object:+ if isinstance(value, str):+ return deserialize_proxy_location(value, raise_on_invalid_geo_target=True)+ return value+class AddressablePersistentBrowserSession(PersistentBrowserSession):browser_address: strdiff --git a/skyvern/library/skyvern.py b/skyvern/library/skyvern.pyindex 09909ab5e..8e2372d5f 100644--- a/skyvern/library/skyvern.py+++ b/skyvern/library/skyvern.py@@ -17,7 +17,7 @@ from skyvern.forge.sdk.api.llm.models import LLMConfig, LLMRouterConfigfrom skyvern.library.constants import DEFAULT_AGENT_HEARTBEAT_INTERVAL, DEFAULT_AGENT_TIMEOUT, DEFAULT_CDP_PORTfrom skyvern.library.skyvern_browser import SkyvernBrowserfrom skyvern.schemas.run_blocks import CredentialType-from skyvern.schemas.runs import ProxyLocation, RunEngine, RunStatus+from skyvern.schemas.runs import ProxyLocationInput, RunEngine, RunStatus, proxy_location_to_requestLOG = structlog.get_logger()@@ -284,7 +284,7 @@ class Skyvern(AsyncSkyvern):title: str | None = None,error_code_mapping: dict[str, str] | None = None,data_extraction_schema: dict[str, Any] | str | None = None,- proxy_location: ProxyLocation | None = None,+ proxy_location: ProxyLocationInput = None,max_steps: int | None = None,wait_for_completion: bool = False,timeout: float = DEFAULT_AGENT_TIMEOUT,@@ -308,7 +308,7 @@ class Skyvern(AsyncSkyvern):title=title,error_code_mapping=error_code_mapping,data_extraction_schema=data_extraction_schema,- proxy_location=proxy_location,+ proxy_location=proxy_location_to_request(proxy_location),max_steps=max_steps,browser_session_id=browser_session_id,user_agent=user_agent,@@ -335,7 +335,7 @@ class Skyvern(AsyncSkyvern):parameters: dict[str, Any] | None = None,template: bool | None = None,title: str | None = None,- proxy_location: ProxyLocation | None = None,+ proxy_location: ProxyLocationInput = None,webhook_url: str | None = None,totp_url: str | None = None,totp_identifier: str | None = None,@@ -357,7 +357,7 @@ class Skyvern(AsyncSkyvern):parameters=parameters,template=template,title=title,- proxy_location=proxy_location,+ proxy_location=proxy_location_to_request(proxy_location),webhook_url=webhook_url,totp_url=totp_url,totp_identifier=totp_identifier,@@ -393,7 +393,7 @@ class Skyvern(AsyncSkyvern):onepassword_item_id: str | None = None,prompt: str | None = None,webhook_url: str | None = None,- proxy_location: ProxyLocation | None = None,+ proxy_location: ProxyLocationInput = None,totp_identifier: str | None = None,totp_url: str | None = None,browser_session_id: str | None = None,@@ -418,7 +418,7 @@ class Skyvern(AsyncSkyvern):onepassword_item_id=onepassword_item_id,prompt=prompt,webhook_url=webhook_url,- proxy_location=proxy_location,+ proxy_location=proxy_location_to_request(proxy_location),totp_identifier=totp_identifier,totp_url=totp_url,browser_session_id=browser_session_id,@@ -527,7 +527,7 @@ class Skyvern(AsyncSkyvern):self,*,timeout: int | None = None,- proxy_location: ProxyLocation | None = None,+ proxy_location: ProxyLocationInput = None,) -> SkyvernBrowser:"""Launch a new cloud-hosted browser session.@@ -545,7 +545,7 @@ class Skyvern(AsyncSkyvern):self._ensure_cloud_environment()browser_session = await self.create_browser_session(timeout=timeout,- proxy_location=proxy_location,+ proxy_location=proxy_location_to_request(proxy_location),)if self._environment == SkyvernEnvironment.CLOUD:LOG.info(@@ -560,7 +560,7 @@ class Skyvern(AsyncSkyvern):self,*,timeout: int | None = None,- proxy_location: ProxyLocation | None = None,+ proxy_location: ProxyLocationInput = None,) -> SkyvernBrowser:"""Get or create a cloud browser session.@@ -589,7 +589,7 @@ class Skyvern(AsyncSkyvern):LOG.info("No existing cloud browser session found, launching a new session")browser_session = await self.create_browser_session(timeout=timeout,- proxy_location=proxy_location,+ proxy_location=proxy_location_to_request(proxy_location),)if self._environment == SkyvernEnvironment.CLOUD:LOG.info(diff --git a/skyvern/schemas/browser_sessions.py b/skyvern/schemas/browser_sessions.pyindex 3e9c2e04f..7d29dbada 100644--- a/skyvern/schemas/browser_sessions.py+++ b/skyvern/schemas/browser_sessions.py@@ -1,10 +1,10 @@-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validatorfrom skyvern.client.types.workflow_definition_yaml_blocks_item import WorkflowDefinitionYamlBlocksItemfrom skyvern.client.types.workflow_definition_yaml_parameters_item import WorkflowDefinitionYamlParametersItem_Workflowfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import Extensions, PersistentBrowserTypefrom skyvern.schemas.docs.doc_strings import PROXY_LOCATION_DOC_STRING-from skyvern.schemas.runs import ProxyLocation+from skyvern.schemas.runs import GeoTarget, ProxyLocationInputMIN_TIMEOUT = 5MAX_TIMEOUT = 60 * 24 # 24 hours@@ -18,11 +18,18 @@ class CreateBrowserSessionRequest(BaseModel):ge=MIN_TIMEOUT,le=MAX_TIMEOUT,)- proxy_location: ProxyLocation | None = Field(+ proxy_location: ProxyLocationInput = Field(default=None,description=PROXY_LOCATION_DOC_STRING,)+ @field_validator("proxy_location", mode="before")+ @classmethod+ def validate_proxy_location_dict(cls, proxy_location: object) -> object:+ if isinstance(proxy_location, dict):+ return GeoTarget.model_validate(proxy_location)+ return proxy_location+extensions: list[Extensions] | None = Field(default=None,description="A list of extensions to install in the browser session.",diff --git a/skyvern/schemas/runs.py b/skyvern/schemas/runs.pyindex b8d36dc31..b89f36724 100644--- a/skyvern/schemas/runs.py+++ b/skyvern/schemas/runs.py@@ -250,6 +250,12 @@ class GeoTarget(BaseModel):ProxyLocationInput = ProxyLocation | GeoTarget | dict | None+def proxy_location_to_request(proxy_location: ProxyLocationInput) -> ProxyLocation | dict | None:+ if isinstance(proxy_location, GeoTarget):+ return proxy_location.model_dump()+ return proxy_location++def get_tzinfo_from_proxy(proxy_location: ProxyLocation) -> ZoneInfo | None:if proxy_location == ProxyLocation.NONE:return Nonediff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.pyindex 35594298a..25a09ce0c 100644--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py@@ -42,6 +42,23 @@ class _SessionContext:return False+class _EmptyExecuteResult:+ def mappings(self) -> _EmptyExecuteResult:+ return self++ def all(self) -> list[Any]:+ return []+++def _where_clause_sql(query: Any) -> str:+ return str(query.whereclause.compile(compile_kwargs={"literal_binds": True}))+++def _assert_not_filtering_copilot_authored_workflows(where_clause: str) -> None:+ assert "workflows.created_by" not in where_clause+ assert "workflows.edited_by" not in where_clause++@pytest.mark.asyncioasync def test_batch_create_uses_add_all_flush_commit_not_refresh() -> None:"""Batch insert should use add_all + flush + commit and never call refresh."""@@ -164,17 +181,9 @@ async def test_get_all_runs_v2_search_key_matches_run_id_and_workflow_permanent_`searchable_text` (which contains only title + url)."""captured: dict[str, Any] = {}- class _Result:- def mappings(self):- class _M:- def all(self_inner):- return []-- return _M()-async def _execute(query):captured["query"] = query- return _Result()+ return _EmptyExecuteResult()session = MagicMock()session.execute = AsyncMock(side_effect=_execute)@@ -185,8 +194,75 @@ async def test_get_all_runs_v2_search_key_matches_run_id_and_workflow_permanent_# Inspect the WHERE clause specifically — both columns are also in the SELECT# list, so a substring check on the full SQL would be a false positive.- where_clause = str(captured["query"].whereclause.compile(compile_kwargs={"literal_binds": True}))+ where_clause = _where_clause_sql(captured["query"])assert "task_runs.run_id" in where_clauseassert "task_runs.workflow_permanent_id" in where_clause# autoescape rewrites '_' to e.g. '/_' so check the distinctive suffix.assert "abc123" in where_clause+++async def test_get_all_runs_v2_excludes_copilot_session_workflow_runs() -> None:+ captured: dict[str, Any] = {}++ async def _execute(query):+ captured["query"] = query+ return _EmptyExecuteResult()++ session = MagicMock()+ session.execute = AsyncMock(side_effect=_execute)++ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)++ await repo.get_all_runs_v2(organization_id="o_test")++ where_clause = _where_clause_sql(captured["query"])+ assert "workflow_runs.copilot_session_id IS NULL" in where_clause+ _assert_not_filtering_copilot_authored_workflows(where_clause)+++async def test_get_all_runs_excludes_copilot_session_workflow_runs() -> None:+ captured: dict[str, Any] = {}++ async def _execute(query):+ captured["query"] = query+ return _EmptyExecuteResult()++ session = MagicMock()+ session.execute = AsyncMock(side_effect=_execute)+ session.scalars = AsyncMock(return_value=_EmptyExecuteResult())++ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)++ await repo.get_all_runs(organization_id="o_test")++ where_clause = _where_clause_sql(captured["query"])+ assert "workflow_runs.copilot_session_id IS NULL" in where_clause+ _assert_not_filtering_copilot_authored_workflows(where_clause)+++async def test_workflow_run_history_queries_exclude_copilot_session_runs() -> None:+ captured_queries: list[Any] = []++ async def _execute(query):+ captured_queries.append(query)+ return _EmptyExecuteResult()++ session = MagicMock()+ session.execute = AsyncMock(side_effect=_execute)++ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)++ await repo.get_workflow_runs(organization_id="o_test")+ await repo.get_workflow_runs_for_workflow_permanent_id(+ workflow_permanent_id="wpid_test",+ organization_id="o_test",+ )++ assert len(captured_queries) == 2+ for query in captured_queries:+ where_clause = _where_clause_sql(query)+ assert "workflow_runs.copilot_session_id IS NULL" in where_clause+ _assert_not_filtering_copilot_authored_workflows(where_clause)diff --git a/tests/unit/test_mcp_session_lifecycle.py b/tests/unit/test_mcp_session_lifecycle.pyindex 735a8e043..5a10a0d0f 100644--- a/tests/unit/test_mcp_session_lifecycle.py+++ b/tests/unit/test_mcp_session_lifecycle.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom types import SimpleNamespace+from typing import castfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -8,8 +9,9 @@ import pytestfrom skyvern.cli.core import client as client_modfrom skyvern.cli.core import session_managerfrom skyvern.cli.core.result import BrowserContext-from skyvern.cli.core.session_ops import SessionCloseResult+from skyvern.cli.core.session_ops import SessionCloseResult, coerce_proxy_locationfrom skyvern.cli.mcp_tools import session as mcp_session+from skyvern.schemas.runs import GeoTarget, ProxyLocation@pytest.fixture(autouse=True)@@ -59,7 +61,7 @@ def test_get_skyvern_reuses_override_instance_per_api_key(monkeypatch: pytest.Moclass FakeSkyvern:def __init__(self, *args: object, **kwargs: object) -> None:- created_keys.append(kwargs["api_key"])+ created_keys.append(cast(str, kwargs["api_key"]))@classmethoddef local(cls) -> FakeSkyvern:@@ -89,7 +91,7 @@ def test_get_skyvern_override_client_cache_uses_lru_eviction(monkeypatch: pytestclass FakeSkyvern:def __init__(self, *args: object, **kwargs: object) -> None:- created_keys.append(kwargs["api_key"])+ created_keys.append(cast(str, kwargs["api_key"]))@classmethoddef local(cls) -> FakeSkyvern:@@ -138,7 +140,7 @@ def test_get_skyvern_override_cache_closes_evicted_client(monkeypatch: pytest.Moclass FakeSkyvern:def __init__(self, *args: object, **kwargs: object) -> None:- self.api_key = kwargs["api_key"]+ self.api_key = cast(str, kwargs["api_key"])@classmethoddef local(cls) -> FakeSkyvern:@@ -549,6 +551,25 @@ async def test_close_current_session_still_closes_browser_when_api_fails(monkeyp# ---------------------------------------------------------------------------+def test_coerce_proxy_location_rejects_unknown_string_with_context() -> None:+ with pytest.raises(ValueError, match="Unknown proxy location: 'INVALID'"):+ coerce_proxy_location("INVALID")+++def test_coerce_proxy_location_accepts_supported_input_shapes() -> None:+ geo_target = GeoTarget(country="US", subdivision="CA", city="San Francisco")++ assert coerce_proxy_location(None) is None+ assert coerce_proxy_location(geo_target) is geo_target+ assert coerce_proxy_location("RESIDENTIAL") == ProxyLocation.RESIDENTIAL+ assert coerce_proxy_location('{"country":"US"}') == GeoTarget(country="US")+++def test_coerce_proxy_location_rejects_non_object_json() -> None:+ with pytest.raises(ValueError, match="Proxy location JSON must be a GeoTarget object"):+ coerce_proxy_location('["RESIDENTIAL"]')++@pytest.mark.asyncioasync def test_session_create_stateless_mode_returns_session_without_persisting_browser(monkeypatch: pytest.MonkeyPatch,@@ -572,6 +593,31 @@ async def test_session_create_stateless_mode_returns_session_without_persisting_assert mcp_session.get_current_session().context is None+async def test_session_create_stateless_mode_accepts_geotarget_proxy_location(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_manager.set_stateless_http_mode(True)+ fake_skyvern = MagicMock()+ fake_skyvern.create_browser_session = AsyncMock(return_value=SimpleNamespace(browser_session_id="pbs_geo"))+ monkeypatch.setattr(mcp_session, "get_skyvern", lambda: fake_skyvern)++ try:+ result = await mcp_session.skyvern_browser_session_create(+ timeout=45,+ proxy_location={"country": "US", "subdivision": "CA", "city": "San Francisco"},+ )+ finally:+ session_manager.set_stateless_http_mode(False)++ assert result["ok"] is True+ # Stateless mode sends request payloads, so GeoTarget instances are serialized back to dicts.+ fake_skyvern.create_browser_session.assert_awaited_once_with(+ timeout=45,+ proxy_location={"country": "US", "subdivision": "CA", "city": "San Francisco"},+ )++@pytest.mark.asyncioasync def test_session_create_stateless_mode_rejects_local() -> None:session_manager.set_stateless_http_mode(True)