agy에 전역 MCP를 한꺼번에 설정해 두면 곧바로 두 가지 현실적인 부작용에 부딪히게 됩니다.

  1. 세션을 열자마자 백그라운드 리소스가 치솟습니다: 기본 mcp_config.json에 chrome-devtools-mcp나 docker run ... mcp-atlassian을 그대로 걸어 두면, 단순히 Go 단위 테스트 두 줄만 고치려고 들어와 브라우저도 Jira도 전혀 쓰지 않는데도 agy를 실행할 때마다 디버그용 Chrome이 뜨고 Docker 컨테이너가 올라옵니다. 터미널 분할 창을 서너 개만 동시에 열어도 메모리와 컨테이너 목록이 순식간에 불어납니다.
  2. 멀티 세션이 디버그 Chrome 하나를 공유하면 탭 표시줄이 뒤엉킵니다: 겨우 Chrome을 단일 인스턴스 재사용 구조로 바꿨더니, 이제는 병렬 세션 세 개가 같은 창에 new_page를 날리면서 localhost, Swagger, 오류 페이지 십여 개가 한데 뒤섞입니다. 어느 탭이 어느 세션 소유인지 알 수 없어 함부로 닫지도 못합니다.

이 글은 제 로컬 머신에서 실제로 구동 중인 전체 해법을 정리한 기록입니다. 외부 의존성 없는 두 개의 Python stdio 프록시로 콜드 스타트 비용을 완전히 없애고, 70줄짜리 RPC 스크립트와 초경량 Chrome MV3 확장으로 각 AGY 세션이 여는 탭을 해당 세션 제목의 탭 그룹에 자동으로 모아 줍니다.

MCP 지연 로딩 stdio 프록시와 Chrome 세션 탭 그룹 연동 아키텍처


1. 두 가지 무거운 MCP의 지연 로딩 전략 구분하기

먼저 혼동하기 쉬운 개념부터 짚고 넘어가겠습니다. 기초 시리즈 8편에서 다룬 Antigravity 내장 Lazy Loading은 Schema 지연 로딩(프롬프트 토큰을 아끼는 용도이며 프로세스 자체는 세션 시작과 함께 뜸)이고, 이 글에서 구현하는 프록시는 프로세스/컨테이너 수준 지연 로딩(메모리, 디버그 Chrome 인스턴스, Docker 컨테이너 콜드 스타트 비용을 아끼는 용도)입니다.

전역 ~/.gemini/config/mcp_config.json에는 자주 쓰는 네 가지 서버를 등록해 두었습니다. 그중 context7과 memory는 가벼운 로컬 Node 프로세스라 바로 띄워도 무방하지만, 리소스를 크게 먹는 것은 chrome-devtools와 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"
}
}
}
}

같은 지연 로딩이라도 두 서버의 병목 지점이 다르기 때문에 서로 다른 두 가지 프록시 패턴을 적용했습니다.

서비스 실제 리소스 병목 프록시 전략
chrome-devtools chrome-devtools-mcp 자체는 가볍고, 연결 대상인 Chrome 인스턴스가 무거움 투명 패스스루 프록시: chrome-devtools-mcp --browserUrl=...를 먼저 띄워 핸드셰이크와 tools/list는 그대로 통과시키고, tools/call을 가로챌 때만 독립 디버그 Chrome 상태를 확인해 온디맨드 실행
jira-internal 서버 전체가 Docker 컨테이너 안에서 실행되어 tools/list 한 번 응답하는 데도 docker run이 필요함 로컬 핸드셰이크 프록시: 프록시 스크립트가 순수 Python으로 initialize, ping, tools/list, notifications/*를 직접 응답하고, 첫 tools/call을 받을 때 컨테이너를 띄워 핸드셰이크를 투명하게 재전송

두 패턴의 요청 경로를 비교하면 다음과 같습니다.


2. Chrome DevTools 지연 로딩 프록시 (chrome-devtools-mcp-lazy.py)

먼저 경로를 고정하고 인자를 그대로 전달하기 위해 아주 얇은 셸 진입점 ~/.gemini/bin/chrome-devtools-mcp.sh를 둡니다.

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

핵심 로직은 ~/.gemini/bin/chrome-devtools-mcp-lazy.py에 있습니다. 이 170줄짜리 코드를 작성하면서 전형적인 네 가지 함정을 겪었고, 모두 코드 안에 방어 로직을 넣었습니다.

  1. 로컬 포트 프로브는 반드시 프록시 환경 변수를 우회해야 합니다: 개발 머신에는 보통 HTTP_PROXY / ALL_PROXY가 설정되어 있습니다. urllib.request로 http://127.0.0.1:9223/json/version을 찌르면 요청이 프록시로 넘어가 502가 반환되고, 프록시 스크립트는 Chrome이 안 뜬 줄 알고 무한정 재실행하게 됩니다. 여기서는 환경 변수를 완전히 무시하는 저수준 http.client.HTTPConnection("127.0.0.1", 9223)을 직접 사용합니다.
  2. 파일 락으로 동시 중복 실행을 방지합니다: 두 세션이 동시에 브라우저 작업을 호출할 때 락이 없으면 두 개의 Chrome이 같은 --user-data-dir을 잡으려다 한쪽이 크래시합니다. fcntl.flock으로 <PROFILE_DIR>/.launch.lock을 잠그고(15초 타임아웃), 락을 획득한 뒤 is_ready()를 한 번 더 이중 확인합니다.
  3. systemd-run --user --collect로 CLI 생명주기에서 분리합니다: Chrome을 프록시의 일반 자식 프로세스로 띄우면 터미널 창 하나를 닫을 때 프로세스 그룹 전체가 SIGHUP으로 함께 종료되어 다른 디버깅 세션까지 끊길 수 있습니다. 가급적 systemd-run --user --unit=agy-debug-chrome --collect로 사용자 레벨 systemd에 위임하고, systemd가 없을 때만 start_new_session=True로 폴백합니다.
  4. 반드시 독립 --user-data-dir을 지정해야 합니다: 평소 쓰는 브라우저의 기본 Profile을 공유하면 Chrome이 기존 실행 인스턴스를 감지해 --remote-debugging-port 옵션을 무시해 버립니다.

전체 구현은 다음과 같습니다(경로 마스킹 적용).

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

진화 안내: 위 시그널 핸들러에는 SIGTERM을 수신한 뒤에도 블로킹 상태인 sys.stdin.buffer.readline()에 걸려 종료되지 않는 문제를 막기 위해 raise SystemExit(128 + signum)을 보강했습니다. 여러 터미널에서 동일한 디버그 Chrome을 병렬로 공유하고 있다면 #5 멀티 세션 Chrome 가드레일과 주황색 UI 상태를 이어서 읽어 보시기 바랍니다. 이 프록시가 CDP targetId 기반의 양방향 오조작 차단 가드레일로 어떻게 진화하는지 자세히 다룹니다.

참고로 실행 인자에 포함된 두 가지 유용한 플래그도 짚고 넘어갑니다.

  • --backgroundNewPages: 에이전트가 백그라운드에서 새 탭을 열 때마다 사용자의 데스크톱 포커스를 강제로 빼앗지 않습니다.
  • --categoryExtensions: 확장 프로그램 관리 도구를 열어 두어 디버그 Chrome에서 직접 만든 로컬 확장을 편하게 리로드할 수 있게 합니다.

3. Jira Docker MCP 로컬 핸드셰이크 프록시 (jira-mcp-lazy.py)

Jira MCP는 ghcr.io/sooperset/mcp-atlassian 이미지를 사용합니다(@sha256 다이제스트로 버전을 고정하고 READ_ONLY_MODE=true와 ENABLED_TOOLS=jira_get_issue,jira_search 두 가지 하드 바운더리를 걸어 에이전트가 절대 프로덕션 티켓을 수정하지 못하게 제한했습니다).

문제는 이를 mcp_config.json에 등록하는 순간 agy 시작 직후 MCP 디스커버리(initialize → notifications/initialized → tools/list)가 발생해 컨테이너가 바로 올라가 세션 종료 때까지 상주한다는 점입니다.

해법은 디스커버리 단계의 프로토콜을 Python 프록시 내부에서 전부 로컬로 소화하는 것입니다.

  • 프록시는 클라이언트가 보낸 initialize.params(protocolVersion, capabilities 포함)를 기억해 두고, 로컬에서 구성한 initialize 응답을 즉시 반환합니다.
  • tools/list는 미리 기록해 둔 jira_get_issue와 jira_search의 JSON Schema를 바로 반환하고, resources/list와 prompts/list에는 빈 배열을 돌려줍니다.
  • 실제 비즈니스 호출(예: tools/call)이 처음 들어오면 그제야 ensure_backend()로 Docker 컨테이너를 띄우고, 저장해 둔 initialize를 내부 ID __agy_jira_lazy_init__로 대신 재전송한 뒤 컨테이너 응답을 받아 notifications/initialized를 이어 보냅니다.
  • 핸드셰이크가 완료되면 데몬 스레드 _pump_stdout을 띄워 컨테이너 출력을 agy로 계속 전달하고, 메인 루프는 이후부터 json.loads 없이 바이트 단위로 그대로 패스스루합니다.
  • 종료 시에는 컨테이너 stdin을 닫고 wait(5) → terminate() → kill() 순으로 정리하며, docker run --rm과 맞물려 좀비 컨테이너 없이 깔끔하게 회수합니다.

핵심 코드 발췌입니다(100줄이 넘는 TOOLS 정적 스키마 정의는 생략했으며, 실전 적용 시 컨테이너에서 tools/list를 한 번 실행해 그대로 복사해 넣으면 됩니다).

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

# 컨테이너 콜드 스타트를 피하기 위해 사전 기록한 읽기 전용 도구 Schema (jira_get_issue / jira_search)
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

# 내부 ID로 initialize를 재전송해 컨테이너 응답을 소비한 뒤 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

이 프록시를 적용하면 코드 작업만 하는 agy 세션을 10개 띄워도 호스트의 docker ps에는 Jira 컨테이너가 단 하나도 나타나지 않습니다. 이슈 번호를 조회해야 할 때 첫 jira_get_issue 호출에서만 컨테이너 기동으로 약 1.5초의 지연이 발생하고, 이후 같은 세션 내 조회는 영구 연결을 통해 즉시 응답합니다.

MCP 이미지를 업그레이드하면서 도구 파라미터가 변경되었다면 프록시 스크립트의 TOOLS 목록도 함께 동기화해야 합니다. 다만 읽기 전용 조회 도구 두 개만 노출하는 Jira 서버의 경우 Schema가 몇 달씩 바뀌지 않아 유지보수 비용은 거의 0에 가깝습니다.


4. 멀티 세션 Chrome 공유: AGY 세션 제목별 탭 자동 그룹화

Chrome을 9223 포트의 단일 인스턴스로 모은 뒤에는 곧바로 “멀티 세션 탭 충돌” 문제를 해결해야 합니다.

Chrome의 네이티브 chrome.tabGroups API는 브라우저 확장 프로그램만 호출할 수 있고, CDP 프로토콜 자체는 탭 그룹을 직접 만들 수 없습니다. 이 제약을 따라 세 조각으로 나누어 조합하니 오히려 구조가 매우 깔끔해졌습니다.

  1. 현재 AGY 세션 제목 조회 (session-tab-url.py)
  2. 디버그 Chrome에 50줄짜리 JS MV3 확장 설치 (~/.gemini/chrome-tab-group-ext/)
  3. 에이전트가 새 탭을 열기 전에 반드시 래퍼 스크립트를 거치도록 강제하는 전역 Skill 작성 (~/.gemini/config/skills/browser-tab-group/SKILL.md)

전체 상호작용 시퀀스는 다음과 같습니다.

1. 현재 세션 제목 조회 및 중계 URL 생성 (session-tab-url.py)

agy는 명령을 실행할 때 ANTIGRAVITY_LS_ADDRESS, ANTIGRAVITY_CSRF_TOKEN, ANTIGRAVITY_CONVERSATION_ID 세 환경 변수를 주입합니다. 로컬 Connect-RPC 엔드포인트인 ConversationService/GetConversation을 직접 호출해 annotations.title을 우선 가져오고, 비어 있으면 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. 초경량 MV3 확장 (manifest.json + group.html + group.js)

확장 파일은 ~/.gemini/chrome-tab-group-ext/에 두고, 디버그 Chrome의 chrome://extensions에서 개발자 모드를 켜 한 번 로드한 뒤 생성된 확장 ID를 같은 디렉터리의 extension_id 파일에 기록하면 됩니다.

동일한 압축 해제 확장(unpacked extension)이 여러 머신에서 완전히 같은 확장 ID를 유지하도록 만들고 싶다면(머신마다 extension_id를 다시 복사할 필요가 없도록), manifest.json에 "key" 필드를 고정하면 됩니다. 구체적인 키 생성 방법은 #4 크로스 플랫폼 백업과 원클릭 초기화에서 다룹니다.

manifest.json에는 최소한의 두 가지 권한만 선언합니다.

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은 중계 페이지로서 상태 표시 요소 하나만 두고 group.js를 로드합니다(MV3에서는 인라인 스크립트가 금지됩니다).

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는 네 가지 작업을 수행합니다: 제목 기반 결정적 해시로 색상 선택 → 현재 창에서 같은 이름의 탭 그룹 조회 → 있으면 합류, 없으면 새로 생성 → ^https?:// 프로토콜만 리다이렉트 허용(javascript:나 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. 전역 Skill로 동작과 엣지 케이스 고정하기 (SKILL.md)

스크립트와 확장만 만들어 두면 에이전트가 알아서 호출하지 않으므로 전역 Skill ~/.gemini/config/skills/browser-tab-group/SKILL.md를 배치하고, 실전에서 겪은 엣지 케이스까지 규칙으로 못 박아 두어야 합니다.

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.

실제로 겪은 세 가지 시행착오를 별도로 정리해 둡니다.

  • 샌드박스의 로컬 루프백 차단: 터미널 샌드박스를 켜면 기본적으로 로컬 포트 접근이 차단되어 session-tab-url.py의 GetConversation 요청이 거절됩니다. 스크립트 오류 메시지에 “이 보조 명령어 하나만 샌드박스 밖에서 재실행할 것”을 명시해야 하며, 에이전트가 편의상 워크스페이스 디렉터리 이름으로 폴백하지 못하도록 막아야 합니다. 그렇지 않으면 같은 저장소에서 세션을 세 개 열었을 때 탭이 다시 하나의 그룹에 뒤섞여 버립니다.
  • 리다이렉트 레이스 컨디션: new_page가 반환된 직후에는 페이지가 아직 group.html에서 chrome.tabs.update를 수행 중일 수 있습니다. 바로 click이나 take_snapshot을 호출하면 헛치게 되므로 Skill 3번 항목에서 대상 URL로 이동 완료되었는지 먼저 확인하도록 명시했습니다.
  • isolatedContext와 확장 페이지 비호환: 시크릿/격리 컨텍스트에서는 chrome-extension:// 페이지가 실행되지 않으므로, 비로그인 상태 검증이 명시적으로 필요한 경우에만 대상 URL을 직접 전달합니다.

시리즈 내비게이션