agent-browser をLLM(Gemini)で操作させる。Playwright MCPとのトークン比較まで検証
はじめに
個人的に、ブラウザをAgentが実行するということに興味はありつつも、browser-use時代からあまり追えていないので、最近公開された「agent-browser」を触ってみます。
主に記事の流れは下記です
- agent-browserとは?
- Playwright MCPよりもコンテキスト93%減は本当?
- agent-browserをLLMで動かしてみる
agent-browserとは?
agent-browserとは、Vercelが開発したAIエージェント向けのブラウザ操作CLIです。
「Rust製のCLIでコマンド処理が高速」「Playwright MCPと比べて約93%少ないコンテキスト量で動作する」などの強みを持つツールらしいです。
Playwright MCPよりもコンテキスト93%減は本当?
タスクによっては高速な実行も大切ですが、個人的にはコンテキストを93%少なくできるという点に凄みを感じます。
基本的に、ブラウザを操作するAIは「ページのHTML」や「DOMツリー」を利用することがありますがトークン数が膨大になることが多いです。(スクショ画像もありますが、そちらもtoken数大きめ)
数回の行動で終えられるタスクであれば問題ありませんが、試行錯誤が必要なタスクの場合、多量の過去のトークンを扱い続けることはコスト的にも性能面的にも不安があります。
agent-browserで情報を取得するsnapshotには、-i(ボタン/リンク/入力など操作に必要な要素だけ)や-c(空の構造要素を削る)といった情報を削減するオプションがあり、コレによりコンテキストを削減することが可能となります。
実際に動かしてみて比較する
「Playwright MCP」と「agent-browser」を両方動かして、ページを取得してみることで、実際にコンテキストの量が削減されていそうかを検証します。
自分が以前書いた「Geminiに財務の分析ができるのか?思考や分析の過程を覗いてみる」というnoteの記事に対して、情報取得を試みます。
Playwright MCPでnoteの情報を取得
import asyncio
import os
from dotenv import load_dotenv
from google import genai
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
load_dotenv()
# 使いたいモデル(必要なら環境変数で上書きできるように)
MODEL = os.getenv("GEMINI_MODEL", "gemini-3-flash-preview")
def count_tokens(client: genai.Client, text: str) -> int:
"""Geminiのトークナイザで text のトークン数を数える。"""
res = client.models.count_tokens(model=MODEL, contents=text)
# SDKの戻り値はオブジェクトで total_tokens 等を持つ
# 環境差に備えて両対応
if hasattr(res, "total_tokens"):
return int(res.total_tokens)
if isinstance(res, dict) and "total_tokens" in res:
return int(res["total_tokens"])
# 最後の保険(想定外)
return int(getattr(res, "token_count", 0))
async def main():
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
server_params = StdioServerParameters(
command="npx",
args=["-y", "@playwright/mcp@latest"], # Playwright MCP
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
await session.call_tool(
"browser_navigate",
{"url": "https://note.com/bekku_deepbank/n/n09e3e4c650b2"},
)
# アクセシビリティツリーのスナップショットを取得
result = await session.call_tool("browser_snapshot", {})
print(result.content)
print(len(result.content[0].text))
print(count_tokens(client, result.content[0].text))
if __name__ == "__main__":
asyncio.run(main())
agent-browserでnoteの情報を取得
import os
import subprocess
from dotenv import load_dotenv
from google import genai
load_dotenv()
# 使いたいモデル(必要なら環境変数で上書きできるように)
MODEL = os.getenv("GEMINI_MODEL", "gemini-3-flash-preview")
def count_tokens(client: genai.Client, text: str) -> int:
"""Geminiのトークナイザで text のトークン数を数える。"""
res = client.models.count_tokens(model=MODEL, contents=text)
# SDKの戻り値はオブジェクトで total_tokens 等を持つ
# 環境差に備えて両対応
if hasattr(res, "total_tokens"):
return int(res.total_tokens)
if isinstance(res, dict) and "total_tokens" in res:
return int(res["total_tokens"])
# 最後の保険(想定外)
return int(getattr(res, "token_count", 0))
def run_cmd(args: list[str], timeout_sec: int = 20) -> str:
p = subprocess.run(
args,
capture_output=True,
text=True,
timeout=timeout_sec,
check=True,
)
return p.stdout
def main() -> None:
url = "https://note.com/bekku_deepbank/n/n09e3e4c650b2"
headed = "--headed"
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
# browser_navigate 相当
open_out = run_cmd(["agent-browser", "open", url, headed], timeout_sec=25)
print(open_out)
# browser_snapshot 相当
snap_output = run_cmd(["agent-browser", "snapshot", headed], timeout_sec=25)
print(snap_output)
print(len(snap_output))
print(count_tokens(client, snap_output))
# browser_snapshot 相当を圧縮
snap_output = run_cmd(
["agent-browser", "snapshot", "-i", "-c", headed],
timeout_sec=25,
)
print(snap_output)
print(len(snap_output))
print(count_tokens(client, snap_output))
if __name__ == "__main__":
main()
結果
出力された文字数とトークン数を比較します。
(token数は Gemini の tokenizer 基準)
| ツール | 条件 | 文字数 | token数 |
|---|---|---|---|
| Playwright MCP | 標準 | 16,544 | 7846 |
| agent-browser | 標準 | 9,347 | 6117 |
| agent-browser | -i -c | 1,586 | 867 |
agent-browser(-i, -c)による取得された情報

Playwright MCPによる取得された情報

上記の結果をみると、確かに取得したページのコンテキストの量は削減されてそうです。
オプションをつけなかった場合でも文字数やトークン数は少なくなっており、オプションを追加すると更に削減されており、90%近くの削減に成功しています。
しかし、オプションを指定した場合、取得された実際の情報を画像で見てみると、noteの内容が取得されていないのがわかります。
考察
Agentが何かの目的のためにブラウザを動かす際、多くの場合は「ページ遷移」や「操作」を含みます。
操作を行うフェーズで情報を獲得する必要はないことを考えると、「agent-browserは、操作のタイミングではコンテキストを削減して、必要な時だけ削減を解除することで効率化しよう」というモチベーションなのかなと個人的に思いました。
逆を言えば、-iのようなオプションの理解を実行するLLM側が理解していないと、agent-browserをうまく使いこなせない可能性もあるのかなと考えます。
agent-browserをLLMで動かしてみる
実際にGemini-3-flash-previewにagent-browser を操作するエージェントを作ってみます。
メインタスク:「note.comへアクセスして、生成AI系でスキが10を超える記事を見つけて、作者がどんな記事書いてるかも教えて。」
実行するだけの簡易コード
Gemini APIと subprocess を簡易的なループで実行しており、とりあえず動かしてみるが目的なので、エラーの対処とかはしていません。
コード上で利用しているagent.mdは、github上に公開されているskill.mdを利用しました。
import json
import os
import shlex
import subprocess
from dotenv import load_dotenv
from google import genai
load_dotenv()
MODEL = "gemini-3-flash-preview"
def run_agent_browser(cmd: str, timeout_sec: int = 30) -> str:
"""agent-browser コマンドを1発実行して stdout を返す(最低限)"""
tokens = shlex.split(cmd)
# agent-browser 以外は実行禁止
if not tokens or tokens[0] != "agent-browser":
raise ValueError("Only agent-browser commands are allowed.")
# 学習用: 常に headed(不要なら削除OK)
tokens.append("--headed")
p = subprocess.run(tokens, capture_output=True, text=True, timeout=timeout_sec)
if p.returncode != 0:
return f"[exit={p.returncode}]\nSTDOUT:\n{p.stdout}\nSTDERR:\n{p.stderr}"
return p.stdout
def ask_gemini_next_cmd(
client: genai.Client,
main_task: str,
history: str,
) -> dict:
"""Geminiに次の1コマンドをJSONで返してもらう"""
# agent-browser のコマンド一覧
with open("agent.md", encoding="utf-8") as f:
agent_browser_md = f.read()
# システムプロンプトを設定
system = f"""
あなたは agent-browser CLI のコントローラーです。
目的: 各ターンで次のCLIコマンドを1つだけ発行して、ユーザーのタスクを完了してください。
ルール:
- 1ターンに1コマンドのみ(&& や ; などの連結は禁止)
- 出力は必ずJSONのみ:
- status_infoには、現在の状況と次の目的などを短く日本語で記載
- タスクが達成したら, "done"をTrueにする。
{{"cmd":"agent-browser ...","done":false,"status_info":""}}
agent-browser commands
----
{agent_browser_md}
""".strip()
prompt = f"""メインタスク: {main_task}
過去の実行ログ
{history}
次に実行する agent-browser コマンドを1つだけ、JSONで返してください。
"""
resp = client.models.generate_content(
model=MODEL,
contents=[system, prompt],
config={"response_mime_type": "application/json"},
)
return json.loads(resp.text)
def main() -> None:
# agent-browser のコマンド一覧
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
main_task = "note.comへアクセスして、スキが10を超える記事を見つけて、作者がどんな記事書いてるかも教えて。".strip()
history = []
# 最初にcloseしておく
run_agent_browser("agent-browser close", timeout_sec=10)
for step in range(20):
# geminiによって、次のコマンドと状況を推論
action = ask_gemini_next_cmd(
client,
main_task,
str(history),
)
cmd = action["cmd"]
# 終了しているか判定
done = bool(action.get("done", False))
# 各ステップをprint
step_report = f"\n[step {step}] {cmd}\n(info: {action.get('status_info', '')})"
print(step_report)
# agent_browserの実行結果を取得
last_output = run_agent_browser(cmd, timeout_sec=30)
# 過去の実行ログとして追加
history.append(f"{step_report}, result:{last_output}")
if done:
break
run_agent_browser("agent-browser close", timeout_sec=10)
if __name__ == "__main__":
main()
結果

上記の実行動画のように、ブラウザを起動して目的のタスクを解決しようと行動していることがわかります。下記のように、目的のスキが10以上の記事を見つけて、作者の情報も共有してもらえました。
note.comにて深津 貴之(fladdict)氏の「「そもそも生成AIでやるべきでない問い」に、
企業が挑んでしまう問題」(スキ数4,942)を見つけました。同氏はAIの活用術(プロンプト、
ビジネス活用、英語学習)のほか、経営戦略、デザイン、生活の最適化など、
テクノロジーとビジネスを軸にした幅広い記事を執筆しています。
実行結果の全ログ
[step 0] agent-browser open https://note.com
(info: note.comにアクセスを開始します。)
[step 1] agent-browser snapshot -i
(info: note.comのページ構造を確認し、検索バーを特定します。)
[step 2] agent-browser fill @e2 "生成AI"
(info: 検索バーに「生成AI」と入力して、関連する記事を検索します。)
[step 3] agent-browser click @e3
(info: 「生成AI」での検索を実行します。)
[step 4] agent-browser snapshot -i
(info: 検索結果からスキが10件以上の記事を探すため、ページ内容を確認します。)
[step 5] agent-browser click @e11
(info: 検索結果から「人気」タブを選択し、スキが多い記事を探します。)
[step 6] agent-browser snapshot -i
(info: 「人気」タブの検索結果を表示し、スキが10件以上の記事を特定します。)
[step 7] agent-browser click @e18
(info: 人気記事の作者である深津 貴之氏のプロフィールページに移動して、他の記事を確認します。)
[step 8] agent-browser snapshot -i
(info: 深津 貴之氏のプロフィールページを確認し、執筆記事の傾向や目的の記事のスキ数を確認します。)
[step 9] agent-browser close
(info: note.comにて深津 貴之(fladdict)氏の「「そもそも生成AIでやるべきでない問い」に、企業が挑んでしまう問題」(スキ数4,942)を見つけました。同氏はAIの活用術(プロンプト、ビジネス活用、英語学習)のほか、経営戦略、デザイン、生活の最適化など、テクノロジーとビジネスを軸にした幅広い記事を執筆しています。)
おわりに
agent-browserを触ってみて、「ブラウザを読むためのツール」というより、「ブラウザ操作を安く・速く実行する」ためのツールという印象を持ちました。
特に、-iや -c によってコンテキストを大幅に削減しながら操作できる点は、試行錯誤が多いエージェントタスクではかなり効いてきそうです。一方で、その代償として本文のような情報は簡単に落ちるため、「動く」と「読む」を同じ snapshot に期待しない設計が重要だと感じました。
Discussion