Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/docs/tests/sdk-reference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ describe("SDK reference surface", () => {
`${language} method headings must match the public SDK surface`,
).toStrictEqual(expected);
}
});
}, 30_000);

it("has exactly one reference page for every documented SDK object", async () => {
const pageSlugs = (await readReferencePages()).map(({ classSlug }) => classSlug).sort();
Expand Down
3 changes: 3 additions & 0 deletions packages/integrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@
Private workspace package for Stagehand integration adapters.

The code-mode stdio entrypoint currently provides the MCP host and process lifecycle used by later code-mode capabilities. It intentionally advertises no tools yet.

The `deepagents/` Python project provides local and managed LangChain Deep Agents integrations. Both
expose stateful `run`, `snapshot`, and `screenshot` browser tools using the Stagehand Python SDK.
5 changes: 5 additions & 0 deletions packages/integrations/deepagents/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.venv/
__pycache__/
.pytest_cache/
.ruff_cache/
*.py[cod]
1 change: 1 addition & 0 deletions packages/integrations/deepagents/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
109 changes: 109 additions & 0 deletions packages/integrations/deepagents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Stagehand Deep Agents integration

This local integration exposes one stateful Stagehand browser to LangChain Deep Agents through a
stdio MCP server. Its complete tool surface is `run`, `snapshot`, and `screenshot`.

## Run locally

Set a model-provider key and select the Deep Agents model:

```bash
export OPENAI_API_KEY=...
export DEEPAGENTS_MODEL=openai:gpt-5.6-luna
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
```

The MCP server launches a visible local Chrome browser by default. Then run:

```bash
cd packages/integrations/deepagents
uv run --project examples/local python examples/local/agent.py
```

The model, instruction, and Pydantic response classes are declared directly in `agent.py` so the
example can be edited and rerun without passing command-line arguments. Set `response_format` to a
Pydantic model class for structured output, or `None` for the normal text response.

`agents2.py` is a form-filling example inspired by Stagehand's sensible form-filling example. The
Deep Agent navigates to the form, snapshots it, fills the requested fields with mock data, and
returns a typed Pydantic summary without submitting the form:

```bash
uv run --project examples/local python examples/local/agents2.py
```

To use Browserbase instead:

```bash
export STAGEHAND_BROWSER=browserbase
export BROWSERBASE_API_KEY=...
uv run --project examples/local python examples/local/agent.py
```

Browserbase sessions use a 1280 × 720 viewport by default.

The server and client intentionally use separate Python environments. Stagehand currently requires
`websockets>=16.1.1`, while the current LangGraph SDK used by Deep Agents requires `websockets<16`.
The stdio transport isolates those dependency sets.

The example deliberately creates a persistent MCP `ClientSession`. Do not replace it with
`MultiServerMCPClient.get_tools()`: the default stateless tools create a new stdio process for each
call and therefore lose the browser and snapshot IDs.

## Server configuration

| Variable | Default | Meaning |
| -------------------------- | ------- | -------------------------------------------------------- |
| `STAGEHAND_BROWSER` | `local` | `local` or `browserbase` |
| `STAGEHAND_HEADLESS` | `false` | Headless local Chrome |
| `STAGEHAND_START_URL` | unset | Optional URL opened when the server starts |
| `STAGEHAND_MODEL` | unset | Optional model used by Stagehand AI methods inside `run` |
| `STAGEHAND_RUN_TIMEOUT_MS` | `60000` | Callback-batch timeout |
| `BROWSERBASE_API_KEY` | unset | Required for Browserbase |

`run` accepts exactly one of JavaScript `code` or snapshot `actions`. JavaScript executes against
the Playwright-shaped `page`, `context`, and `browser` facade. Snapshot actions use bracketed IDs
from the most recent `snapshot` call.

## Managed Deep Agents

The managed example lives in `examples/managed`. Its authored LangChain tools run the Python
Stagehand SDK directly and expose the same `run`, `snapshot`, and `screenshot` contract. The managed
thread ID is injected by `ToolRuntime` and scopes an in-process Browserbase runtime; it is not
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
exposed to the model.

The current LangGraph SDK requires `websockets<16`, while Stagehand declares `websockets>=16.1.1`.
For this spike, the managed project overrides the shared dependency to `websockets==15.0.1`. Remove
the override once the SDK ranges converge. Browser continuity is guaranteed while the managed
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
worker remains warm; durable reconnection after worker replacement is future work.

### Develop and deploy the managed agent

From `examples/managed`, copy `.env.example` to `.env` and configure:

- `DEEPAGENTS_MODEL` and the matching provider key, such as `OPENAI_API_KEY`.
- `BROWSERBASE_API_KEY` for the hosted browser.
- Either `STAGEHAND_API_URL` for Browserbase Model Gateway, or `STAGEHAND_MODEL` plus
`STAGEHAND_MODEL_API_KEY` for direct-provider BYOK.

Then run:

```bash
uv sync
uv run mda dev .
uv run mda deploy .
```

Managed Deep Agents forwards non-reserved `.env` entries as deployment secrets. The agent model key
and the optional Stagehand model key are independent: users can bring their own key for either,
while Browserbase Model Gateway remains the zero-additional-key Stagehand path.

The published `stagehand` wheel bundles the browser extension and `browserbase.launch` provisions
it automatically. Set `STAGEHAND_EXTENSION_ID` to reuse a pre-uploaded extension instead.

## Security model

The `run` tool executes model-authored JavaScript inside the Stagehand browser extension's service
worker — browser-side, never in the host process. Browserbase is the recommended isolation
boundary: the privileged execution environment is a disposable cloud browser with no access to the
host machine. Only `STAGEHAND_*` and `BROWSERBASE_*` environment variables are forwarded to the
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
browser session; host secrets such as the deep-agent model key never reach it.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
47 changes: 47 additions & 0 deletions packages/integrations/deepagents/examples/local/_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Shared MCP client config for the local Deep Agents examples.

The MCP stdio client strips the parent environment down to a safe default
set (HOME, PATH, SHELL, TERM, USER), so the server would never see
STAGEHAND_* / BROWSERBASE_* configuration without an explicit env block.
Every script in this example builds its client here so the allowlist can't
regress in one copy.
"""

from __future__ import annotations

import os
from pathlib import Path

from langchain_mcp_adapters.client import MultiServerMCPClient

SERVER_NAME = "stagehand_browser"

_SERVER_PROJECT = Path(__file__).resolve().parents[2]


def _allowlisted_env() -> dict[str, str]:
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
"""Forward only STAGEHAND_* and BROWSERBASE_* variables to the server."""
return {
name: value
for name, value in os.environ.items()
if (name.startswith("STAGEHAND_") or name.startswith("BROWSERBASE_")) and value
}


def create_stagehand_client() -> MultiServerMCPClient:
return MultiServerMCPClient(
{
SERVER_NAME: {
"transport": "stdio",
"command": "uv",
"args": [
"run",
"--project",
str(_SERVER_PROJECT),
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
"--locked",
"stagehand-deepagents-mcp",
],
"env": _allowlisted_env(),
}
}
)
64 changes: 64 additions & 0 deletions packages/integrations/deepagents/examples/local/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from __future__ import annotations

import asyncio

import dotenv
from _client import SERVER_NAME, create_stagehand_client
from deepagents import create_deep_agent
from langchain_mcp_adapters.tools import load_mcp_tools
from pydantic import BaseModel, ConfigDict, Field

dotenv.load_dotenv()

BROWSER_INSTRUCTIONS = """You control one persistent browser through exactly three tools:
- snapshot: inspect the active page and hydrate bracketed element IDs.
- run: provide either snapshot actions or JavaScript using the Playwright-shaped page API.
- screenshot: inspect the rendered page visually.

Use snapshot actions for simple interactions and run code for multi-step workflows. Snapshot IDs are
valid only for the latest snapshot of the active page. Snapshot again after navigation or stale IDs.
Do not launch another browser.
"""


class SportsEvent(BaseModel):
model_config = ConfigDict(extra="forbid")

name: str = Field(description="The name of the event")
sport: str = Field(description="The sport being played")
summary: str = Field(description="A concise summary of the event")
source_url: str = Field(description="The source URL for the event information")


class SportsSummary(BaseModel):
model_config = ConfigDict(extra="forbid")

events: list[SportsEvent] = Field(description="The day's main sporting events")


async def main() -> None:
model = "openai:gpt-5.6-luna"
instruction = "Go find me a summary of all main sports events today"
response_format = SportsSummary

client = create_stagehand_client()

async with client.session(SERVER_NAME) as session:
tools = await load_mcp_tools(session)
agent = create_deep_agent(
model=model,
tools=tools,
system_prompt=BROWSER_INSTRUCTIONS,
response_format=response_format,
)
result = await agent.ainvoke({"messages": [{"role": "user", "content": instruction}]})

if response_format is not None:
response = result["structured_response"]
print(response.model_dump_json(indent=2))
return
print(result["messages"][-1].content)


if __name__ == "__main__":
asyncio.run(main())
71 changes: 71 additions & 0 deletions packages/integrations/deepagents/examples/local/agents2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from __future__ import annotations

import asyncio

import dotenv
from _client import SERVER_NAME, create_stagehand_client
from deepagents import create_deep_agent
from langchain_mcp_adapters.tools import load_mcp_tools
from pydantic import BaseModel, ConfigDict, Field

dotenv.load_dotenv()

BROWSER_INSTRUCTIONS = """You control one persistent browser through exactly three tools:
- snapshot: inspect the active page and hydrate bracketed element IDs.
- run: provide either snapshot actions or JavaScript using the Playwright-shaped page API.
- screenshot: inspect the rendered page visually.

Navigate to the requested form, take a snapshot, identify the requested fields, and fill them with
the supplied mock data. Prefer one batched run actions call after taking the snapshot. Do not submit
the form unless explicitly asked.
"""


class FilledField(BaseModel):
model_config = ConfigDict(extra="forbid")

field: str = Field(description="The form field that was filled")
value: str = Field(description="The mock value entered into the field")


class FormFillResult(BaseModel):
model_config = ConfigDict(extra="forbid")

url: str = Field(description="The final page URL")
fields: list[FilledField] = Field(description="The fields successfully filled")
completed: bool = Field(description="Whether all requested fields were filled")


async def main() -> None:
model = "openai:gpt-5.6-luna"
instruction = """Navigate to https://file.1040.com/estimate/ and wait for it to load. Fill the
form with this mock data:
- age: 26
- dependents under age 17: 1
- wages / W-2 Box 1: 54321
- federal tax / Box 2: 8345
- state tax / Box 17: 2222

and then every other field with data of your choice.

Do not submit the form. Return a summary of the fields you successfully filled."""
response_format = FormFillResult

client = create_stagehand_client()

async with client.session(SERVER_NAME) as session:
tools = await load_mcp_tools(session)
agent = create_deep_agent(
model=model,
tools=tools,
system_prompt=BROWSER_INSTRUCTIONS,
response_format=response_format,
)
result = await agent.ainvoke({"messages": [{"role": "user", "content": instruction}]})
response: FormFillResult = result["structured_response"]

print(response.model_dump_json(indent=2))


if __name__ == "__main__":
asyncio.run(main())
14 changes: 14 additions & 0 deletions packages/integrations/deepagents/examples/local/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[project]
name = "stagehand-deepagents-local-example"
version = "0.1.0"
requires-python = ">=3.11,<3.14"
dependencies = [
"python-dotenv>=1.0",
"deepagents>=0.7,<1",
"langchain-mcp-adapters>=0.3,<1",
"langchain-openai>=1,<2",
"pydantic>=2,<3",
Comment thread
miguelg719 marked this conversation as resolved.
Resolved
]

[tool.uv]
package = false
Loading
Loading