Una vez que configuras tus servidores MCP globales en agy, no tardan en aparecer dos efectos secundarios muy tangibles:

  1. Los recursos en segundo plano se disparan al abrir cada sesión: si registras directamente chrome-devtools-mcp o docker run ... mcp-atlassian en mcp_config.json, aunque solo entres para editar dos líneas de pruebas unitarias en Go —sin tocar el navegador ni consultar Jira—, cada arranque de agy abrirá un Chrome de depuración o levantará un contenedor de Docker. Con cuatro o cinco paneles abiertos a la vez, la memoria RAM y la lista de contenedores crecen sin control.
  2. Al compartir un único Chrome de depuración entre varias sesiones, la barra de pestañas se vuelve un caos: cuando por fin consolidas Chrome en una sola instancia compartida, tres sesiones concurrentes empiezan a lanzar new_page sobre la misma ventana y mezclan una docena de pestañas de localhost, Swagger y pantallas de error. Es imposible saber qué pestaña pertenece a qué sesión y tampoco te atreves a cerrar ninguna.

Este artículo documenta la solución completa que tengo en producción en mi equipo: dos proxies stdio en Python sin dependencias de terceros para erradicar el coste de arranque en frío, junto con un script RPC de 70 líneas y una extensión minimalista de Chrome MV3 para que cada pestaña abierta por AGY entre automáticamente en un grupo bautizado con el título de su sesión.

Arquitectura de proxy MCP stdio de carga diferida integrada con grupos de pestañas por sesión en Chrome


1. Distinguir dos estrategias de carga diferida para MCP pesados

Conviene aclarar primero una confusión frecuente: el Lazy Loading integrado de Antigravity explicado en la entrega #8 de la serie base es carga diferida de esquemas (ahorra tokens de prompt, pero el proceso del servidor sigue arrancando con cada sesión); en cambio, los proxies de este artículo implementan carga diferida a nivel de proceso y contenedor (ahorran memoria RAM, instancias de Chrome de depuración y arranques en frío de contenedores Docker).

En mi ~/.gemini/config/mcp_config.json global tengo cuatro servicios habituales. context7 y memory son procesos locales de Node muy ligeros que pueden arrancar directamente; los verdaderos consumidores de recursos son chrome-devtools y 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"
}
}
}
}

Aunque ambos necesitan carga diferida (lazy-loading), sus cuellos de botella son distintos, por lo que apliqué dos patrones de proxy diferentes:

Servicio Elemento que realmente consume recursos Estrategia de proxy
chrome-devtools chrome-devtools-mcp en sí es muy ligero; lo pesado es la instancia de Chrome a la que se conecta Proxy transparente de paso: inicia chrome-devtools-mcp --browserUrl=... y deja pasar el handshake y tools/list sin modificar; solo al interceptar tools/call verifica y arranca bajo demanda una instancia aislada de Chrome de depuración
jira-internal Todo el servidor corre dentro de un contenedor Docker, así que incluso responder a tools/list exige un docker run Proxy de handshake local: el script responde localmente en Python puro a initialize, ping, tools/list y notifications/*; solo al recibir el primer tools/call levanta el contenedor y reproduce el handshake de forma transparente

Comparativa del recorrido de peticiones en ambos modos:


2. Proxy de carga diferida para Chrome DevTools (chrome-devtools-mcp-lazy.py)

Primero colocamos un envoltorio shell mínimo en ~/.gemini/bin/chrome-devtools-mcp.sh para fijar la ruta y reenviar argumentos:

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

La lógica principal vive en ~/.gemini/bin/chrome-devtools-mcp-lazy.py. Al escribir estas 170 líneas aparecieron cuatro problemas reales muy típicos, todos cubiertos defensivamente en el código:

  1. Sondear el puerto local ignorando variables de proxy: las máquinas de desarrollo suelen tener definidos HTTP_PROXY o ALL_PROXY. Si usas urllib.request para comprobar http://127.0.0.1:9223/json/version, la petición puede desviarse al proxy y devolver 502, haciendo creer al script que Chrome no está corriendo y disparando arranques repetidos. Usar directamente http.client.HTTPConnection("127.0.0.1", 9223) ignora por completo esas variables de entorno.
  2. Bloqueo por archivo contra doble arranque concurrente: si dos sesiones solicitan una acción de navegador a la vez sin sincronización, lanzarán dos procesos de Chrome peleando por el mismo --user-data-dir y uno de ellos se cerrará con error. Usar fcntl.flock sobre <PROFILE_DIR>/.launch.lock (con timeout de 15 s) y volver a comprobar is_ready() tras adquirir el bloqueo evita la condición de carrera.
  3. Desacoplar el ciclo de vida del CLI con systemd-run --user --collect: si Chrome arranca como subproceso directo del proxy, cerrar una ventana de terminal puede enviar SIGHUP a todo el grupo de procesos y cortar la conexión a otras sesiones que estaban depurando. Priorizar systemd-run --user --unit=agy-debug-chrome --collect deja el navegador bajo el gestor de usuario de systemd y solo recurre a start_new_session=True si no hay systemd disponible.
  4. Usar siempre un --user-data-dir dedicado: no reutilices el perfil habitual de tu navegador diario; si Chrome detecta una instancia ya abierta con ese perfil, ignorará silenciosamente --remote-debugging-port.

Implementación completa (con rutas saneadas):

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())

Nota de evolución: el manejador de señales anterior ya incluye raise SystemExit(128 + signum) para evitar que el proceso quede bloqueado en sys.stdin.buffer.readline() tras recibir SIGTERM. Si compartes un único Chrome de depuración entre múltiples terminales concurrentes, conviene continuar con #5 Control paralelo de Chrome y estado naranja de UI, donde este proxy evoluciona hacia un guardrail bidireccional basado en targetId de CDP.

Dos flags muy útiles en los argumentos de lanzamiento:

  • --backgroundNewPages: evita que el navegador te robe el foco del escritorio cada vez que el agente abre una nueva pestaña en segundo plano;
  • --categoryExtensions: habilita las herramientas de gestión de extensiones, muy práctico para recargar extensiones locales durante la depuración.

3. Proxy de handshake completamente local para Jira Docker MCP (jira-mcp-lazy.py)

Para Jira MCP utilizo la imagen ghcr.io/sooperset/mcp-atlassian (fijada por digest @sha256, con dos límites estrictos: READ_ONLY_MODE=true y ENABLED_TOOLS=jira_get_issue,jira_search, garantizando que el agente nunca pueda modificar incidencias en producción).

El inconveniente es que, en cuanto aparece en mcp_config.json, agy ejecuta el descubrimiento MCP al arrancar (initialize → notifications/initialized → tools/list), levantando el contenedor y manteniéndolo vivo durante toda la sesión.

La solución consiste en resolver toda la fase de descubrimiento localmente dentro del proxy en Python:

  • El proxy guarda initialize.params enviados por el cliente (incluidos protocolVersion y capabilities) y devuelve de inmediato una respuesta initialize generada localmente;
  • tools/list responde directamente con el JSON Schema pregrabado de jira_get_issue y jira_search, mientras que resources/list y prompts/list devuelven arreglos vacíos;
  • Solo cuando llega una llamada de negocio real (como tools/call) invoca ensure_backend() para arrancar el contenedor Docker, reproduce el initialize almacenado en nombre del cliente usando el ID interno __agy_jira_lazy_init__, espera la respuesta del contenedor y envía notifications/initialized;
  • Una vez completado el handshake, lanza un hilo daemon _pump_stdout que reenvía de forma continua la salida del contenedor hacia agy, y a partir de ese instante el bucle principal pasa a modo de reenvío directo a nivel de bytes sin volver a ejecutar json.loads;
  • Al salir cierra stdin del contenedor y aplica wait(5) → terminate() → kill(), lo que junto a docker run --rm limpia el contenedor sin dejar procesos zombis.

Extracto del código principal (se ha resumido la definición estática de TOOLS, que en el archivo real ocupa un centenar de líneas obtenidas ejecutando una sola vez tools/list contra el contenedor):

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__"

# Esquemas pregrabados de solo lectura (jira_get_issue / jira_search) para evitar arrancar el contenedor en frío
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

# Reproducir initialize con ID interno, consumir su respuesta y enviar 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

Con este proxy en marcha puedes abrir 10 sesiones de agy dedicadas únicamente a código sin que aparezca un solo contenedor de Jira en docker ps. Cuando necesitas consultar un ticket, la primera llamada a jira_get_issue tarda alrededor de 1.5 segundos en levantar el contenedor y todas las consultas posteriores dentro de esa sesión responden al instante sobre la conexión persistente.

Si alguna actualización de la imagen MCP cambia los parámetros de las herramientas, recuerda actualizar también la lista TOOLS del proxy; no obstante, para un servicio de Jira que solo expone dos consultas de solo lectura, el esquema apenas cambia durante meses y el mantenimiento es prácticamente nulo.


4. Chrome compartido entre varias sesiones: agrupación automática de pestañas por título de sesión AGY

Una vez consolidado Chrome en una sola instancia escuchando en el puerto 9223, el siguiente problema que hay que atajar es la colisión de pestañas entre sesiones.

La API nativa chrome.tabGroups solo puede invocarse desde una extensión del navegador; el protocolo CDP por sí mismo no permite crear grupos de pestañas directamente. Siguiendo esa restricción, la arquitectura se divide en tres piezas muy limpias:

  1. Obtener el título de la sesión actual de AGY (session-tab-url.py)
  2. Instalar una extensión MV3 de 50 líneas de JS en el Chrome de depuración (~/.gemini/chrome-tab-group-ext/)
  3. Definir una Skill global que obligue al agente a pasar siempre por el script auxiliar antes de abrir una pestaña (~/.gemini/config/skills/browser-tab-group/SKILL.md)

Secuencia completa de interacción:

1. Consultar el título de la sesión actual y construir la URL puente (session-tab-url.py)

Al ejecutar comandos, agy inyecta las variables de entorno ANTIGRAVITY_LS_ADDRESS, ANTIGRAVITY_CSRF_TOKEN y ANTIGRAVITY_CONVERSATION_ID. Con ellas basta invocar el endpoint Connect-RPC local ConversationService/GetConversation, tomando annotations.title como primera opción y state.summary como respaldo:

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. Extensión MV3 minimalista (manifest.json + group.html + group.js)

La extensión se guarda en ~/.gemini/chrome-tab-group-ext/. Basta habilitar el modo desarrollador en chrome://extensions dentro del Chrome de depuración, cargarla una vez sin empaquetar y copiar el ID generado en el archivo extension_id del mismo directorio.

Si deseas que esta misma extensión sin empaquetar conserve exactamente el mismo ID en varias máquinas (evitando copiar extension_id en cada equipo), puedes fijar el campo "key" dentro de manifest.json. El procedimiento para generarlo está detallado en #4 Respaldo local, adaptación multiplataforma e inicialización.

manifest.json solo requiere dos permisos mínimos:

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 actúa como página puente: muestra únicamente un nodo de estado y carga group.js (MV3 prohíbe los scripts en línea):

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 realiza cuatro tareas: selecciona un color determinista aplicando un hash al título → busca si ya existe un grupo con ese nombre en la ventana actual → se une a él o crea uno nuevo → solo permite redirigir a ^https?:// (evitando redirecciones maliciosas del tipo javascript: o file://):

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. Encapsular el comportamiento y casos borde en una Skill global (SKILL.md)

Tener el script y la extensión no basta: el agente no se acordará de invocarlos por iniciativa propia. Hace falta añadir una Skill global en ~/.gemini/config/skills/browser-tab-group/SKILL.md que deje fijados los casos borde encontrados en uso real:

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.

Tres problemas reales en los que conviene detenerse:

  • El sandbox bloquea el bucle local (loopback): con el sandbox de terminal activado, el acceso a puertos locales queda restringido por defecto y session-tab-url.py falla al llamar a GetConversation. Por eso el mensaje de error del script indica explícitamente reejecutar fuera del sandbox solo ese comando auxiliar, sin permitir nunca que el agente recurra al nombre del directorio del workspace (de lo contrario, tres sesiones en el mismo repositorio volverían a mezclar sus pestañas en un único grupo).
  • Condición de carrera en la redirección: cuando new_page retorna, es posible que la pestaña siga en group.html ejecutando chrome.tabs.update. Llamar inmediatamente a click o take_snapshot fallaría sobre la página puente, así que la regla 3 de la Skill exige confirmar primero que la URL ya llegó al destino.
  • isolatedContext es incompatible con páginas de extensión: los contextos aislados o de incógnito no pueden ejecutar chrome-extension://; cuando una verificación requiera explícitamente un contexto limpio sin sesión iniciada, pasa directamente la URL objetivo.