Once you wire up global MCP servers in agy, two practical headaches show up fast:

  1. Heavy background resources spin up on every session start: Point mcp_config.json directly at chrome-devtools-mcp or docker run ... mcp-atlassian, and every agy session pops open a debug Chrome instance or spins up a Docker container—even if you only opened the CLI to tweak two lines of a Go unit test and never touch a browser or Jira. Open four or five terminal splits in parallel, and RAM usage and your container list blow up immediately.
  2. A shared debug Chrome turns into tab soup: Even after consolidating Chrome into a single shared instance, three concurrent sessions calling new_page dump a dozen localhost, Swagger, and error tabs into the same window. You cannot tell which tab belongs to which session, and you hesitate to close any of them.

This post walks through the setup running on my machine: two zero-dependency Python stdio proxies that cut cold-start resource overhead to zero, paired with a 70-line RPC helper and a minimal Chrome MV3 extension that automatically files every tab opened by an AGY session into a tab group named after that session’s title.

Lazy MCP stdio proxies and Chrome session tab-group architecture


1. Two Lazy-Loading Strategies for Heavy MCP Servers

First, an important distinction: Antigravity’s built-in Lazy Loading covered in Part 8 of the Field Guide is schema lazy loading—it saves prompt tokens, but the MCP server process itself still starts with the session. The proxies here implement process- and container-level lazy loading, eliminating RAM overhead and cold starts for debug Chrome instances and Docker containers.

My global ~/.gemini/config/mcp_config.json configures four everyday servers. context7 and memory are lightweight local Node processes that can start eagerly; the real resource hogs are chrome-devtools and jira-internal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"mcpServers": {
"chrome-devtools": {
"command": "/home/user/.gemini/bin/chrome-devtools-mcp.sh"
},
"context7": {
"command": "/home/user/.gemini/mcp-servers/context7/node_modules/.bin/context7-mcp"
},
"jira-internal": {
"command": "/home/user/.gemini/bin/jira-mcp.sh"
},
"memory": {
"command": "/home/user/.gemini/mcp-servers/memory/node_modules/.bin/mcp-server-memory",
"env": {
"MEMORY_FILE_PATH": "/home/user/.gemini/memory/knowledge-graph.jsonl"
}
}
}
}

Both need lazy loading, but their bottlenecks differ, so each uses a different proxy pattern:

Server Actual Resource Bottleneck Proxy Strategy
chrome-devtools chrome-devtools-mcp itself is light; the Chrome instance it attaches to is heavy Transparent pass-through proxy: Starts chrome-devtools-mcp --browserUrl=... up front and passes handshakes and tools/list straight through; checks and launches the standalone debug Chrome on demand only when intercepting a tools/call
jira-internal The entire server runs inside a Docker container—even answering tools/list requires docker run Local-handshake proxy: Answers initialize, ping, tools/list, and notifications/* directly in Python; spawns the Docker container only on the first tools/call, transparently replaying the handshake

Request flow for both patterns side by side:


2. Chrome DevTools Lazy Proxy (chrome-devtools-mcp-lazy.py)

Start with a thin shell wrapper at ~/.gemini/bin/chrome-devtools-mcp.sh to keep the path stable and forward arguments cleanly:

1
2
3
#!/usr/bin/env bash
set -euo pipefail
exec python3 /home/user/.gemini/bin/chrome-devtools-mcp-lazy.py "$@"

The core logic lives in ~/.gemini/bin/chrome-devtools-mcp-lazy.py. Writing these 170 lines exposed four classic pitfalls, each guarded directly in code:

  1. Bypass proxy environment variables when probing localhost: Dev machines commonly export HTTP_PROXY or ALL_PROXY. Probing http://127.0.0.1:9223/json/version via urllib.request can route through the proxy and return 502, tricking the script into repeatedly spawning Chrome. Using low-level http.client.HTTPConnection("127.0.0.1", 9223) ignores proxy env vars completely.
  2. File lock to prevent concurrent duplicate launches: When two sessions trigger browser tools at the same instant, an unlocked launch races two Chrome instances onto the same --user-data-dir, crashing one of them. Locking <PROFILE_DIR>/.launch.lock via fcntl.flock (15-second timeout) and double-checking is_ready() after acquiring the lock prevents the race.
  3. Detach Chrome from the CLI lifecycle with systemd-run --user --collect: Spawning Chrome as a direct child of the proxy means closing one terminal window can send SIGHUP to the process group and tear down Chrome for every other active session. Delegating startup to user-level systemd via systemd-run --user --unit=agy-debug-chrome --collect isolates its lifecycle, falling back to start_new_session=True when systemd is unavailable.
  4. Always use a dedicated --user-data-dir: Never reuse your daily browser’s default profile, or Chrome will detect the running instance and silently ignore --remote-debugging-port.

Full implementation (with sanitized paths):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/env python3
"""Lazy-launch stdio proxy for chrome-devtools-mcp."""
import errno, fcntl, http.client, json, os, shutil, signal, subprocess, sys, time

HOST = "127.0.0.1"
PORT = int(os.environ.get("AGY_CHROME_DEBUG_PORT", "9223"))
URL = f"http://{HOST}:{PORT}"
PROFILE_DIR = os.environ.get(
"AGY_CHROME_PROFILE_DIR",
os.path.join(os.path.expanduser("~"), ".local", "share", "chrome-mcp-profile"),
)
LOCK_FILE = os.path.join(PROFILE_DIR, ".launch.lock")
CHROME_BIN = os.environ.get("AGY_CHROME_BIN", "/usr/bin/google-chrome")
MCP_BIN = os.environ.get(
"AGY_CHROME_MCP_BIN",
os.path.expanduser("~/.gemini/mcp-servers/chrome-devtools/node_modules/.bin/chrome-devtools-mcp"),
)


def is_ready() -> bool:
"""Directly probe local CDP endpoint, bypassing any proxy env vars."""
conn = None
try:
conn = http.client.HTTPConnection(HOST, PORT, timeout=1.0)
conn.request("GET", "/json/version")
resp = conn.getresponse()
resp.read()
return resp.status == 200
except OSError:
return False
finally:
if conn is not None:
conn.close()


def acquire_lock(fd: int, timeout_s: float = 15.0) -> bool:
deadline = time.monotonic() + timeout_s
while True:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EAGAIN) or time.monotonic() >= deadline:
return False
time.sleep(0.1)


def launch_chrome() -> None:
chrome_args = [
CHROME_BIN,
f"--remote-debugging-address={HOST}",
f"--remote-debugging-port={PORT}",
f"--user-data-dir={PROFILE_DIR}",
"--no-first-run",
"--no-default-browser-check",
]
launched = False
if shutil.which("systemd-run") and (
os.environ.get("DBUS_SESSION_BUS_ADDRESS") or os.environ.get("XDG_RUNTIME_DIR")
):
res = subprocess.run(
["systemd-run", "--user", "--unit=agy-debug-chrome", "--collect", *chrome_args],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
close_fds=True, check=False,
)
launched = res.returncode == 0
if not launched:
subprocess.Popen(
chrome_args,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True,
)


def ensure_chrome() -> None:
if os.environ.get("AGY_NO_AUTO_CHROME", "0") == "1" or is_ready():
return
os.makedirs(PROFILE_DIR, exist_ok=True)
lock_fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR, 0o600)
try:
if not acquire_lock(lock_fd, timeout_s=15.0):
return
if not is_ready():
launch_chrome()
for _ in range(40):
if is_ready():
break
time.sleep(0.25)
finally:
try:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
except OSError:
pass
os.close(lock_fd)


def needs_browser(raw_line: bytes) -> bool:
if b"tools/call" not in raw_line:
return False
try:
msg = json.loads(raw_line)
except (ValueError, UnicodeDecodeError):
return False
if isinstance(msg, dict):
return msg.get("method") == "tools/call"
if isinstance(msg, list):
return any(isinstance(item, dict) and item.get("method") == "tools/call" for item in msg)
return False


def main() -> int:
cmd = [
MCP_BIN,
f"--browserUrl={URL}",
"--categoryExtensions",
"--backgroundNewPages",
"--no-usage-statistics",
"--no-performance-crux",
*sys.argv[1:],
]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)

def forward_signal(signum: int, _frame: object) -> None:
if proc.poll() is None:
try:
proc.send_signal(signum)
except ProcessLookupError:
pass
raise SystemExit(128 + signum)

for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(sig, forward_signal)

assert proc.stdin is not None
try:
while True:
line = sys.stdin.buffer.readline()
if not line:
break
if needs_browser(line):
ensure_chrome()
try:
proc.stdin.write(line)
proc.stdin.flush()
except BrokenPipeError:
break
finally:
try:
proc.stdin.close()
except OSError:
pass
return proc.wait()


if __name__ == "__main__":
raise SystemExit(main())

Evolution note: The signal handler above includes raise SystemExit(128 + signum) so the proxy does not hang on the blocking sys.stdin.buffer.readline() call after receiving SIGTERM. If you share one debug Chrome across parallel terminals, continue to #5 Multi-Session Chrome Guardrails and the 6th Orange Status Color to see how this proxy evolves into a bidirectional cross-session guardrail backed by CDP targetId ownership.

Two extra CLI flags worth keeping enabled:

  • --backgroundNewPages: Prevents background tabs opened by the agent from stealing your desktop focus.
  • --categoryExtensions: Enables extension-management tools so you can reload local unpacked extensions directly inside the debug Chrome.

3. Jira Docker MCP Local-Handshake Proxy (jira-mcp-lazy.py)

For Jira MCP, I run the ghcr.io/sooperset/mcp-atlassian image—pinned to an @sha256 digest and locked down with READ_ONLY_MODE=true and ENABLED_TOOLS=jira_get_issue,jira_search so the agent can never mutate live tickets.

The problem is that listing it in mcp_config.json makes agy run MCP discovery (initialize → notifications/initialized → tools/list) the moment a session starts, spinning up the container and keeping it alive until exit.

The fix is to handle the entire discovery phase locally inside the Python proxy:

  • Cache the client’s initialize.params (including protocolVersion and capabilities) and immediately return a locally constructed initialize response.
  • Serve pre-recorded JSON Schemas for jira_get_issue and jira_search on tools/list, and empty arrays on resources/list and prompts/list.
  • Only when a non-discovery request (such as tools/call) arrives does ensure_backend() start the Docker container, replay the saved initialize request under an internal ID (__agy_jira_lazy_init__), consume the backend’s response, and send notifications/initialized.
  • Once the handshake completes, a daemon thread (_pump_stdout) continuously forwards container stdout back to agy, and the main loop switches to raw byte-level pass-through without reparsing JSON.
  • On exit, the proxy closes container stdin and runs wait(5) → terminate() → kill(); paired with docker run --rm, no orphaned containers remain.

Core excerpt below (the full ~100-line static TOOLS schema is abbreviated—just run tools/list against the container once and paste the output):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""Lazy-launch stdio MCP proxy for jira-internal (mcp-atlassian Docker container)."""
import json, os, shlex, signal, subprocess, sys, threading

JIRA_ENV_PATH = os.environ.get(
"AGY_JIRA_ENV_FILE",
os.path.join(os.path.expanduser("~"), ".gemini", "secrets", "jira.env"),
)
JIRA_IMAGE = os.environ.get(
"AGY_JIRA_IMAGE",
"ghcr.io/sooperset/mcp-atlassian@sha256:5b7c9b64d4eb3210cab74be8bf3e6aeea9ed14f3042dc59ba5c5287bd4dbe466",
)
DOCKER_BIN = os.environ.get("AGY_DOCKER_BIN", "/usr/bin/docker")
INIT_INTERNAL_ID = "__agy_jira_lazy_init__"

# Pre-recorded read-only tool schemas (jira_get_issue / jira_search) to avoid cold-starting the container
TOOLS = [
{"name": "jira_get_issue", "description": "Get details of a specific Jira issue.", "inputSchema": {"type": "object", "required": ["issue_key"], "properties": {"issue_key": {"type": "string"}}}},
{"name": "jira_search", "description": "Search Jira issues using JQL.", "inputSchema": {"type": "object", "required": ["jql"], "properties": {"jql": {"type": "string"}}}},
]

WRITE_LOCK = threading.Lock()


def write_client(raw_line: bytes) -> None:
with WRITE_LOCK:
sys.stdout.buffer.write(raw_line)
sys.stdout.buffer.flush()


def send_json(obj: dict) -> None:
write_client((json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8"))


def backend_command() -> list[str]:
if not os.access(JIRA_ENV_PATH, os.R_OK):
raise RuntimeError(f"Jira credentials file is missing or unreadable: {JIRA_ENV_PATH}")
return [
DOCKER_BIN, "run", "--rm", "-i",
"--env-file", JIRA_ENV_PATH,
"-e", "READ_ONLY_MODE=true",
"-e", "ENABLED_TOOLS=jira_get_issue,jira_search",
JIRA_IMAGE,
]


class LazyJiraProxy:
def __init__(self) -> None:
self.proc: subprocess.Popen[bytes] | None = None
self.reader_thread: threading.Thread | None = None
self.init_params: dict = {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "antigravity-lazy-proxy", "version": "1.0.0"},
}

def handle_local(self, msg: dict) -> bool:
method, req_id = msg.get("method"), msg.get("id")
if method == "initialize":
if isinstance(msg.get("params"), dict):
self.init_params = msg["params"]
proto = self.init_params.get("protocolVersion") or "2024-11-05"
if req_id is not None:
send_json({
"jsonrpc": "2.0", "id": req_id,
"result": {
"protocolVersion": proto,
"capabilities": {"tools": {}},
"serverInfo": {"name": "jira-internal-lazy", "version": "1.0.0"},
},
})
return True
if method == "ping":
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {}})
return True
if method == "tools/list":
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}})
return True
if method in ("resources/list", "resources/templates/list", "prompts/list"):
key = {"resources/list": "resources", "resources/templates/list": "resourceTemplates", "prompts/list": "prompts"}[method]
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {key: []}})
return True
return isinstance(method, str) and method.startswith("notifications/") and req_id is None

def ensure_backend(self) -> None:
if self.proc is not None and self.proc.poll() is None:
return
proc = subprocess.Popen(backend_command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
assert proc.stdin is not None and proc.stdout is not None

# Replay initialize with an internal ID, consume the response, then send notifications/initialized
init_req = {"jsonrpc": "2.0", "id": INIT_INTERNAL_ID, "method": "initialize", "params": self.init_params}
proc.stdin.write((json.dumps(init_req, separators=(",", ":")) + "\n").encode("utf-8"))
proc.stdin.flush()

while True:
line = proc.stdout.readline()
if not line:
raise RuntimeError(f"jira-internal backend exited during initialize (rc={proc.wait()})")
try:
resp = json.loads(line)
except (ValueError, UnicodeDecodeError):
continue
if isinstance(resp, dict) and resp.get("id") == INIT_INTERNAL_ID:
if "error" in resp:
raise RuntimeError(f"jira-internal initialize failed: {resp['error']}")
break

inited = {"jsonrpc": "2.0", "method": "notifications/initialized"}
proc.stdin.write((json.dumps(inited, separators=(",", ":")) + "\n").encode("utf-8"))
proc.stdin.flush()

self.proc = proc
self.reader_thread = threading.Thread(target=self._pump_stdout, args=(proc,), daemon=True)
self.reader_thread.start()

@staticmethod
def _pump_stdout(proc: subprocess.Popen[bytes]) -> None:
assert proc.stdout is not None
try:
for line in iter(proc.stdout.readline, b""):
write_client(line)
except OSError:
pass

With this proxy in place, opening 10 code-only agy sessions leaves zero Jira containers in docker ps. When you actually look up a ticket, the first jira_get_issue takes about 1.5 seconds to spin up the container; every subsequent query in that session runs instantaneously over the live stdio pipe.

If you upgrade the MCP image and tool parameters change, update the TOOLS list in the proxy script to match. For a Jira integration exposing just two read-only query tools, the schema rarely changes, so maintenance cost is effectively zero.


4. Shared Chrome Across Sessions: Auto-Grouping Tabs by AGY Session Title

Once Chrome is consolidated onto a single instance on port 9223, the next problem is tab collisions across concurrent sessions.

Chrome’s chrome.tabGroups API is only exposed to extensions—CDP itself cannot create or assign tab groups. Breaking the workflow into three small pieces produces a surprisingly clean solution:

  1. Fetch the current AGY session title (session-tab-url.py)
  2. Install a 50-line JS MV3 extension in the debug Chrome (~/.gemini/chrome-tab-group-ext/)
  3. Add a global Skill requiring the agent to wrap URLs before opening tabs (~/.gemini/config/skills/browser-tab-group/SKILL.md)

End-to-end interaction sequence:

1. Reading the Session Title and Building the Redirect URL (session-tab-url.py)

When agy runs a command, it injects ANTIGRAVITY_LS_ADDRESS, ANTIGRAVITY_CSRF_TOKEN, and ANTIGRAVITY_CONVERSATION_ID. Call the local Connect-RPC endpoint ConversationService/GetConversation, preferring annotations.title and falling back to state.summary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
"""Print the current Antigravity conversation title (or a tab-grouper redirect URL)."""
import json, os, sys, urllib.parse, urllib.request


def get_session_title():
addr = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip()
csrf = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip()
conv_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip()
if not (addr and csrf and conv_id):
raise RuntimeError(
"Missing Antigravity conversation env vars "
"(ANTIGRAVITY_LS_ADDRESS / ANTIGRAVITY_CSRF_TOKEN / ANTIGRAVITY_CONVERSATION_ID)."
)
req = urllib.request.Request(
f"http://{addr}/product.v1.ConversationService/GetConversation",
data=json.dumps({"conversationId": conv_id}).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Connect-Protocol-Version": "1",
"x-antigravity-csrf-token": csrf,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=3) as resp:
data = json.loads(resp.read().decode("utf-8"))
except Exception as exc:
raise RuntimeError(
f"Failed to resolve conversation title via GetConversation ({exc}). "
"If blocked by sandbox (e.g., HTTP 403 / connection refused), "
"rerun this command outside the sandbox."
) from exc
title = (data.get("annotations") or {}).get("title") or ""
summary = (data.get("state") or {}).get("summary") or ""
picked = title.strip() or summary.strip()
if not picked:
raise RuntimeError(f"Conversation {conv_id} has neither annotations.title nor state.summary.")
return picked


def main():
try:
title = get_session_title()
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
if len(sys.argv) >= 3 and sys.argv[1] == "--url":
ext_id = os.environ.get("AGY_TAB_GROUP_EXT_ID", "").strip()
if not ext_id:
cfg = os.path.expanduser("~/.gemini/chrome-tab-group-ext/extension_id")
if os.path.isfile(cfg):
with open(cfg, encoding="utf-8") as f:
ext_id = f.read().strip()
if not ext_id:
print("Missing extension_id", file=sys.stderr)
return 1
query = urllib.parse.urlencode({"group": title, "url": sys.argv[2]})
print(f"chrome-extension://{ext_id}/group.html?{query}")
return 0
print(title)
return 0


if __name__ == "__main__":
raise SystemExit(main())

2. Minimal MV3 Extension (manifest.json + group.html + group.js)

Place the extension in ~/.gemini/chrome-tab-group-ext/, enable Developer Mode in the debug Chrome’s chrome://extensions, load it unpacked once, and save the generated extension ID into extension_id in the same directory.

If you want the same unpacked extension to keep an identical extension ID across multiple machines (so you do not have to copy extension_id on every host), pin the "key" field in manifest.json. See #4 Cross-Platform Backup and One-Click Bootstrap for how to generate it.

manifest.json requests only two minimal permissions:

1
2
3
4
5
6
7
{
"manifest_version": 3,
"name": "Antigravity Session Tab Grouper",
"version": "1.0.0",
"description": "Group tabs opened by Antigravity CLI sessions using the current conversation title.",
"permissions": ["tabs", "tabGroups"]
}

group.html serves as the redirect landing page with a single status element and an external script tag (MV3 disallows inline scripts):

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Grouping Tab...</title>
</head>
<body>
<p id="status">Grouping tab...</p>
<script src="group.js"></script>
</body>
</html>

group.js does four things: picks a deterministic color by hashing the group title, checks the current window for an existing group with that name, joins it or creates a new one, and redirects only to ^https?:// URLs (blocking crafted javascript: or file:// redirects):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const COLORS = ["blue", "cyan", "green", "yellow", "orange", "pink", "purple", "red", "grey"];

function pickColor(name, explicit) {
if (explicit && COLORS.includes(explicit)) return explicit;
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
}
return COLORS[hash % COLORS.length];
}

async function run() {
const statusEl = document.getElementById("status");
const params = new URLSearchParams(window.location.search);
const groupName = (params.get("group") || "Antigravity").trim().slice(0, 80);
const targetUrl = (params.get("url") || "").trim();
const color = pickColor(groupName, (params.get("color") || "").trim());

const tab = await chrome.tabs.getCurrent();
if (!tab || typeof tab.id !== "number") throw new Error("Cannot resolve current tab.");

const existing = await chrome.tabGroups.query({ windowId: tab.windowId, title: groupName });
if (existing.length > 0) {
await chrome.tabs.group({ groupId: existing[0].id, tabIds: [tab.id] });
} else {
const groupId = await chrome.tabs.group({ tabIds: [tab.id] });
await chrome.tabGroups.update(groupId, { title: groupName, color });
}

if (/^https?:\/\//i.test(targetUrl)) {
statusEl.textContent = `Grouped into "${groupName}", redirecting...`;
await chrome.tabs.update(tab.id, { url: targetUrl });
} else {
statusEl.textContent = `Grouped into "${groupName}".`;
}
}

run().catch((err) => {
const statusEl = document.getElementById("status");
if (statusEl) statusEl.textContent = `Tab group error: ${err?.message || err}`;
});

3. Enforcing Behavior and Edge Cases with a Global Skill (SKILL.md)

Having the script and extension on disk is not enough—the agent will not remember to invoke them on its own. Install a global Skill at ~/.gemini/config/skills/browser-tab-group/SKILL.md and encode the real-world edge cases directly in the rules:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
---
name: browser-tab-group
description: >-
Use this skill whenever opening a new browser tab with the chrome-devtools
MCP (new_page) or starting browser automation/debugging in Chrome. Ensures
every tab opened by this Antigravity session is placed into a single Chrome
tab group named after the current Antigravity conversation title.
---

# Browser Session Tab Grouping

1. **Always wrap `new_page` URLs through the local tab-grouper helper**:
python3 ~/.gemini/config/skills/browser-tab-group/scripts/session-tab-url.py --url "<target-url>"
- If the terminal sandbox blocks `GetConversation`, rerun **only** that helper command outside the sandbox.
- Never fall back to the workspace directory name or pass `<target-url>` directly to `new_page`.

2. **One tab group per conversation**:
- First tab creates and names the group; subsequent tabs join the same group automatically.
- Reuse an existing tab in this session's group via `navigate_page` when a new tab is unnecessary.

3. **Wait for redirect before interacting**:
- Verify via `list_pages` or `take_snapshot` that the tab has left `group.html` before clicking or filling.

4. **Edge cases**:
- Do not combine `chrome-extension://` URLs with `isolatedContext`; isolated browser contexts cannot run the local extension.

Three pitfalls from real usage deserve calling out explicitly:

  • Sandbox blocking localhost loopback: With the terminal sandbox enabled, local port connections are blocked by default, so session-tab-url.py fails to reach GetConversation. Make sure the error hint instructs the agent to rerun only that helper outside the sandbox—and never let the agent fall back to the workspace directory name, or three sessions in the same repository will pile back into one tab group.
  • Redirect race condition: When new_page returns, the tab may still be on group.html mid-chrome.tabs.update. Calling click or take_snapshot immediately hits the redirect stub instead of the target page, which is why Rule 3 requires verifying the URL has moved past group.html first.
  • isolatedContext incompatibility: Incognito/isolated browser contexts cannot load chrome-extension:// pages. When you explicitly need an unauthenticated verification session, pass the target URL directly.

Series Navigation