google-flow-api-mcp 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/auth_lab/mint_token.py +596 -0
- package/bin/google-flow-api +78 -0
- package/cookies.py +246 -0
- package/flow_api/__init__.py +43 -0
- package/flow_api/__main__.py +3 -0
- package/flow_api/cli.py +203 -0
- package/flow_api/client.py +881 -0
- package/flow_api/selftest.py +195 -0
- package/package.json +44 -3
- package/postinstall.js +98 -0
- package/scripts/clean-pycache.js +22 -0
- package/server.py +204 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Offline self-test for flow_api — validates de-framing, parsing and request
|
|
2
|
+
shapes against the captured fixtures. No network, no cookies, no tokens used.
|
|
3
|
+
|
|
4
|
+
python3 -m flow_api.selftest
|
|
5
|
+
python3 flow_api/selftest.py
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
HERE = Path(__file__).resolve().parent
|
|
17
|
+
sys.path.insert(0, str(HERE.parent))
|
|
18
|
+
|
|
19
|
+
from flow_api.client import ( # noqa: E402
|
|
20
|
+
IMAGE_MODEL,
|
|
21
|
+
IMAGE_RPC,
|
|
22
|
+
MEDIA_FETCH_RPC,
|
|
23
|
+
VIDEO_MODEL,
|
|
24
|
+
VIDEO_RPC,
|
|
25
|
+
VIDEO_STATUS_RPC,
|
|
26
|
+
asb_download_url,
|
|
27
|
+
build_image_inner,
|
|
28
|
+
build_video_inner,
|
|
29
|
+
collect_urls,
|
|
30
|
+
deframe,
|
|
31
|
+
pick_download_url,
|
|
32
|
+
slugify,
|
|
33
|
+
sniff_extension,
|
|
34
|
+
wrb_payloads,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
FIXTURES = HERE.parent / ".team-mode" / "teams" / "flow-api" / "fixtures"
|
|
38
|
+
PROJECT = "f73a2a1b-0904-4cec-8c9e-22ff6c858592"
|
|
39
|
+
TOKEN = "0cAFcWeA-selftest-token"
|
|
40
|
+
|
|
41
|
+
RESULTS: list[tuple[bool, str]] = []
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def check(name: str, condition: bool, detail: str = "") -> None:
|
|
45
|
+
RESULTS.append((bool(condition), name))
|
|
46
|
+
mark = "PASS" if condition else "FAIL"
|
|
47
|
+
print(f"[{mark}] {name}" + (f" — {detail}" if detail else ""))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_responses() -> list[dict]:
|
|
51
|
+
rows: list[dict] = []
|
|
52
|
+
for name in ("bx_resps.json", "bx_resps2.json"):
|
|
53
|
+
path = FIXTURES / name
|
|
54
|
+
if path.exists():
|
|
55
|
+
rows.extend(json.loads(path.read_text()))
|
|
56
|
+
return rows
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def rpc_of(row: dict) -> str | None:
|
|
60
|
+
match = re.search(r"rpcids=([^&]+)", row.get("u", ""))
|
|
61
|
+
return match.group(1) if match else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_deframe(rows: list[dict]) -> None:
|
|
65
|
+
for row in rows:
|
|
66
|
+
rpc = rpc_of(row)
|
|
67
|
+
body = row.get("body", "")
|
|
68
|
+
check(f"deframe {rpc} ({row.get('s')})", bool(deframe(body)))
|
|
69
|
+
# length line includes the trailing newline -> raw_decode, not json.loads
|
|
70
|
+
sample = rows[0]["body"]
|
|
71
|
+
frames = deframe(sample)
|
|
72
|
+
check("deframe handles trailing newline in length", isinstance(frames[0], list))
|
|
73
|
+
check("deframe blank input", deframe("") == [])
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_wrb(rows: list[dict]) -> None:
|
|
77
|
+
for row in rows:
|
|
78
|
+
rpc = rpc_of(row)
|
|
79
|
+
if not rpc:
|
|
80
|
+
continue
|
|
81
|
+
payloads = wrb_payloads(row["body"], rpc)
|
|
82
|
+
check(f"wrb payload for {rpc}", len(payloads) == 1 and payloads[0] is not None)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_image(rows: list[dict]) -> None:
|
|
86
|
+
row = next(r for r in rows if rpc_of(r) == IMAGE_RPC)
|
|
87
|
+
payload = wrb_payloads(row["body"], IMAGE_RPC)[0]
|
|
88
|
+
urls = collect_urls(payload)
|
|
89
|
+
url = pick_download_url(urls, "image")
|
|
90
|
+
check("image: signed flow-content URL found", bool(url and "flow-content.google/image/" in url))
|
|
91
|
+
check("image: URL keeps Expires+Signature", "Expires=" in (url or "") and "Signature=" in (url or ""))
|
|
92
|
+
check("image: media id parsed", payload[0][0][0] == "d4a70767-1b92-4b73-9932-a9d41ef3d11c")
|
|
93
|
+
check("image: size [1024,1024]", payload[0][0][6][2] == [1024, 1024], str(payload[0][0][6][2]))
|
|
94
|
+
|
|
95
|
+
inner = build_image_inner("a blue mug", PROJECT, TOKEN, seed=123, u1="U-1", u2="U-2")
|
|
96
|
+
gen = inner[1][0]
|
|
97
|
+
check("image inner: seed/model", gen[3] == 123 and gen[5] == IMAGE_MODEL)
|
|
98
|
+
check("image inner: prompt nesting", gen[8] == [[["a blue mug"]]])
|
|
99
|
+
check("image inner: project in both ctx", inner[3][5] == PROJECT and gen[7][5] == PROJECT)
|
|
100
|
+
check(
|
|
101
|
+
"image inner: recaptcha in both ctx",
|
|
102
|
+
inner[3][10] == [TOKEN, 1] and gen[7][10] == [TOKEN, 1],
|
|
103
|
+
)
|
|
104
|
+
check("image inner: uuids", gen[12] == "U-1" and gen[13] == "U-2")
|
|
105
|
+
freq = json.dumps([[[IMAGE_RPC, json.dumps(inner), None, "generic"]]], separators=(",", ":"))
|
|
106
|
+
check("image f.req envelope", freq.startswith('[[["ogiZ0b","'))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_video(rows: list[dict]) -> None:
|
|
110
|
+
row = next(r for r in rows if rpc_of(r) == VIDEO_RPC)
|
|
111
|
+
payload = wrb_payloads(row["body"], VIDEO_RPC)[0]
|
|
112
|
+
entry = payload[2][0]
|
|
113
|
+
check("video submit: job id", entry[0] == "a3fcae13-0671-44d3-9d89-c8487f895312")
|
|
114
|
+
check("video submit: poll media id", entry[3][4] == "f5922d4a-89c3-453b-94af-1f5d195ff68f")
|
|
115
|
+
urls = collect_urls(payload)
|
|
116
|
+
check("video submit: no download URL yet", pick_download_url(urls, "video") is None)
|
|
117
|
+
|
|
118
|
+
polls = [r for r in rows if rpc_of(r) == VIDEO_STATUS_RPC]
|
|
119
|
+
check("video poll: two frames captured", len(polls) == 2)
|
|
120
|
+
statuses = []
|
|
121
|
+
for poll in polls:
|
|
122
|
+
body = wrb_payloads(poll["body"], VIDEO_STATUS_RPC)[0]
|
|
123
|
+
statuses.append(body[2][0][5][8])
|
|
124
|
+
check("video poll: status array present", statuses == [[2], [2]], str(statuses))
|
|
125
|
+
|
|
126
|
+
inner = build_video_inner("a paper plane", PROJECT, TOKEN, u1="U-1", u2="U-2")
|
|
127
|
+
check("video inner: model key", inner[0][0][0][3] == VIDEO_MODEL)
|
|
128
|
+
check("video inner: prompt nesting", inner[0][0][0][2] == [[["a paper plane"]]])
|
|
129
|
+
check("video inner: project ctx", inner[1][5] == PROJECT and inner[1][10] == [TOKEN, 1])
|
|
130
|
+
check("video inner: uuids", inner[0][0][0][6][4] == "U-1" and inner[2][0] == "U-1")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_media_fetch(rows: list[dict]) -> None:
|
|
134
|
+
row = next(r for r in rows if rpc_of(r) == MEDIA_FETCH_RPC)
|
|
135
|
+
payload = wrb_payloads(row["body"], MEDIA_FETCH_RPC)[0]
|
|
136
|
+
urls = collect_urls(payload)
|
|
137
|
+
lh3 = [u for u in urls if "googleusercontent.com/asb/" in u]
|
|
138
|
+
check("as29s: lh3 asb URL found", bool(lh3))
|
|
139
|
+
check("as29s: content type jpeg", "image/jpeg" in json.dumps(payload))
|
|
140
|
+
proxy = asb_download_url(lh3[0]) if lh3 else None
|
|
141
|
+
check(
|
|
142
|
+
"as29s: asb rewrite to flow.google.com proxy",
|
|
143
|
+
proxy is not None
|
|
144
|
+
and proxy.startswith("https://flow.google.com/asb/")
|
|
145
|
+
and proxy.endswith("=mm,22,15")
|
|
146
|
+
and "googleusercontent" not in proxy,
|
|
147
|
+
proxy or "",
|
|
148
|
+
)
|
|
149
|
+
check("asb rewrite rejects non-asb urls", asb_download_url("https://example.com/x") is None)
|
|
150
|
+
inner = [payload[0], None, [1]]
|
|
151
|
+
check("as29s: request inner shape", inner[1] is None and inner[2] == [1])
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_helpers() -> None:
|
|
155
|
+
check("sniff jpeg", sniff_extension(Path(FIXTURES / "pear_proof.jpg").read_bytes()[:16]) == ".jpg")
|
|
156
|
+
check("sniff png", sniff_extension(b"\x89PNG\r\n\x1a\n" + b"\0" * 8) == ".png")
|
|
157
|
+
check("sniff mp4", sniff_extension(b"\0\0\0\x18ftypmp42") == ".mp4")
|
|
158
|
+
check("sniff html", sniff_extension(b"<!DOCTYPE html>") is None)
|
|
159
|
+
check("slug", slugify("A blue mug, soft light!") == "a-blue-mug-soft-light")
|
|
160
|
+
|
|
161
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
162
|
+
from flow_api.client import load_recaptcha_token
|
|
163
|
+
|
|
164
|
+
folder = Path(tmp)
|
|
165
|
+
(folder / "old.json").write_text(json.dumps({"action": "IMAGE_GENERATION", "token": "old", "ts": 1}))
|
|
166
|
+
(folder / "new.json").write_text(json.dumps({"action": "IMAGE_GENERATION", "token": "new", "ts": 2}))
|
|
167
|
+
(folder / "video.json").write_text(json.dumps({"action": "VIDEO_GENERATION", "token": "vid", "ts": 3}))
|
|
168
|
+
check("token dir: newest image token", load_recaptcha_token(folder, "IMAGE_GENERATION") == "new")
|
|
169
|
+
check("token dir: action filter", load_recaptcha_token(folder, "VIDEO_GENERATION") == "vid")
|
|
170
|
+
(folder / "plain.txt").write_text("raw-token\n")
|
|
171
|
+
check("token file: raw text", load_recaptcha_token(folder / "plain.txt", "IMAGE_GENERATION") == "raw-token")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def main() -> int:
|
|
175
|
+
if not FIXTURES.exists():
|
|
176
|
+
print(f"fixtures not found at {FIXTURES}", file=sys.stderr)
|
|
177
|
+
return 2
|
|
178
|
+
rows = load_responses()
|
|
179
|
+
check("fixtures loaded", len(rows) >= 10, f"{len(rows)} captured responses")
|
|
180
|
+
test_deframe(rows)
|
|
181
|
+
test_wrb(rows)
|
|
182
|
+
test_image(rows)
|
|
183
|
+
test_video(rows)
|
|
184
|
+
test_media_fetch(rows)
|
|
185
|
+
test_helpers()
|
|
186
|
+
failed = [name for ok, name in RESULTS if not ok]
|
|
187
|
+
print(f"\n{len(RESULTS) - len(failed)}/{len(RESULTS)} checks passed")
|
|
188
|
+
if failed:
|
|
189
|
+
print("failed: " + ", ".join(failed), file=sys.stderr)
|
|
190
|
+
return 1
|
|
191
|
+
return 0
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
raise SystemExit(main())
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "google-flow-api-mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "MCP server for Google Flow (flow.google.com) \u2014 Nano Banana Pro images and Omni video through the real Flow RPCs, with automatic re-login from the machine's browser cookies",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mcp",
|
|
7
|
+
"model-context-protocol",
|
|
8
|
+
"google-flow",
|
|
9
|
+
"nano-banana",
|
|
10
|
+
"image-generation",
|
|
11
|
+
"video-generation",
|
|
12
|
+
"flow.google.com",
|
|
13
|
+
"claude-desktop",
|
|
14
|
+
"cursor",
|
|
15
|
+
"npx"
|
|
16
|
+
],
|
|
17
|
+
"author": "Wael Bousfira",
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/vakandi/google-flow-api.git"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"bin": {
|
|
30
|
+
"google-flow-api": "bin/google-flow-api"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"bin/",
|
|
34
|
+
"scripts/",
|
|
35
|
+
"postinstall.js",
|
|
36
|
+
"server.py",
|
|
37
|
+
"cookies.py",
|
|
38
|
+
"flow_api/",
|
|
39
|
+
"auth_lab/",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"postinstall": "node postinstall.js",
|
|
45
|
+
"prepack": "node scripts/clean-pycache.js"
|
|
46
|
+
}
|
|
6
47
|
}
|
package/postinstall.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const { execSync } = require("child_process");
|
|
5
|
+
|
|
6
|
+
function log(msg) {
|
|
7
|
+
console.log(`\x1b[36m[google-flow-api]\x1b[0m ${msg}`);
|
|
8
|
+
}
|
|
9
|
+
function warn(msg) {
|
|
10
|
+
console.warn(`\x1b[33m[google-flow-api]\x1b[0m ${msg}`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function findPython() {
|
|
14
|
+
for (const cmd of ["python3", "python"]) {
|
|
15
|
+
try {
|
|
16
|
+
const out = execSync(
|
|
17
|
+
`${cmd} -c "import sys;print('%d.%d' % sys.version_info[:2])"`,
|
|
18
|
+
{ encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"] }
|
|
19
|
+
).trim();
|
|
20
|
+
const [major, minor] = out.split(".").map(Number);
|
|
21
|
+
if (major >= 3 && minor >= 10) return cmd;
|
|
22
|
+
} catch {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const python = findPython();
|
|
30
|
+
if (!python) {
|
|
31
|
+
warn("Python 3.10+ not found — install it, then rerun: node postinstall.js");
|
|
32
|
+
process.exit(0);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const packages = [
|
|
36
|
+
["mcp", "mcp"],
|
|
37
|
+
["requests", "requests"],
|
|
38
|
+
["browser_cookie3", "browser_cookie3"],
|
|
39
|
+
["playwright", "playwright"],
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
const missing = [];
|
|
43
|
+
for (const [moduleName, pipName] of packages) {
|
|
44
|
+
try {
|
|
45
|
+
execSync(`${python} -c "import ${moduleName}"`, { stdio: "ignore", timeout: 8000 });
|
|
46
|
+
} catch {
|
|
47
|
+
missing.push(pipName);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (missing.length) {
|
|
52
|
+
log(`installing Python deps: ${missing.join(" ")}`);
|
|
53
|
+
const attempts = [
|
|
54
|
+
`${python} -m pip install --quiet --user --no-warn-script-location ${missing.join(" ")}`,
|
|
55
|
+
`${python} -m pip install --quiet --no-warn-script-location ${missing.join(" ")}`,
|
|
56
|
+
];
|
|
57
|
+
let ok = false;
|
|
58
|
+
for (const cmd of attempts) {
|
|
59
|
+
try {
|
|
60
|
+
execSync(cmd, { stdio: "inherit", timeout: 300000 });
|
|
61
|
+
ok = true;
|
|
62
|
+
break;
|
|
63
|
+
} catch {
|
|
64
|
+
/* try the next strategy */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!ok) {
|
|
68
|
+
warn("pip install failed — run manually:");
|
|
69
|
+
warn(` ${python} -m pip install ${missing.join(" ")}`);
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
log("Python deps OK");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Chromium for token minting is optional: mint_token.py falls back to the
|
|
76
|
+
// system Google Chrome when Playwright's bundled browser is absent.
|
|
77
|
+
try {
|
|
78
|
+
execSync(`${python} -c "from playwright.sync_api import sync_playwright"`, {
|
|
79
|
+
stdio: "ignore",
|
|
80
|
+
timeout: 10000,
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
execSync(`${python} -m playwright install chromium`, {
|
|
84
|
+
stdio: "ignore",
|
|
85
|
+
timeout: 300000,
|
|
86
|
+
});
|
|
87
|
+
log("Playwright Chromium ready");
|
|
88
|
+
} catch {
|
|
89
|
+
log("Playwright Chromium not installed — will use system Google Chrome");
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
/* playwright import already failing is reported above */
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
log("Setup complete. Next:");
|
|
96
|
+
log(" 1) log into https://flow.google.com in Chrome/Edge/Safari");
|
|
97
|
+
log(" 2) node -e \"require('./cookies')\" (or call the flow_relogin MCP tool)");
|
|
98
|
+
log(" 3) add the server to your MCP client — see README.md");
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
// Remove __pycache__ dirs so they never land in the npm tarball.
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
|
|
7
|
+
function walk(dir) {
|
|
8
|
+
for (const entry of fs.readdirSync(dir)) {
|
|
9
|
+
const full = path.join(dir, entry);
|
|
10
|
+
if (entry === "__pycache__") {
|
|
11
|
+
fs.rmSync(full, { recursive: true, force: true });
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
if (fs.lstatSync(full).isDirectory()) walk(full);
|
|
16
|
+
} catch {
|
|
17
|
+
/* ignore */
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
walk(path.resolve(__dirname, ".."));
|
package/server.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""google-flow-api — MCP server for Google Flow (flow.google.com).
|
|
3
|
+
|
|
4
|
+
Exposes the reverse-engineered Flow RPCs as MCP tools:
|
|
5
|
+
|
|
6
|
+
flow_relogin pull a fresh .google.com cookie jar from the machine's default
|
|
7
|
+
browser (macOS) and validate it against Flow
|
|
8
|
+
flow_health config, cookies and session state
|
|
9
|
+
flow_generate_image Nano Banana Pro (GEM_PIX_2) -> 1024x1024 JPEG
|
|
10
|
+
flow_generate_video Omni 1.2 Flash (macaron_cookie_t2v_8s) -> 1280x720 H.264 MP4
|
|
11
|
+
flow_video_status poll an existing video job
|
|
12
|
+
flow_download fetch an existing media id (image or video), no generation
|
|
13
|
+
|
|
14
|
+
No browser tab is driven for generation: the RPCs are plain HTTP. A headless
|
|
15
|
+
Chromium is launched only to mint the single-use reCAPTCHA token.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from mcp.server.fastmcp import FastMCP
|
|
26
|
+
|
|
27
|
+
import cookies as cookie_lib
|
|
28
|
+
from flow_api import FlowClient, FlowError, RecaptchaRejected
|
|
29
|
+
from flow_api.client import DEFAULT_OUT_DIR, DEFAULT_PROJECT_ID
|
|
30
|
+
|
|
31
|
+
mcp = FastMCP("google-flow-api")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _client(project: str | None = None) -> FlowClient:
|
|
35
|
+
if not cookie_lib.COOKIE_FILE.exists():
|
|
36
|
+
raise FlowError(
|
|
37
|
+
f"no cookie jar at {cookie_lib.COOKIE_FILE}; run flow_relogin first"
|
|
38
|
+
)
|
|
39
|
+
tokens_dir = cookie_lib.CONFIG_HOME / "tokens"
|
|
40
|
+
tokens_dir.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
return FlowClient(
|
|
42
|
+
project_id=project
|
|
43
|
+
or os.environ.get("FLOW_PROJECT_ID")
|
|
44
|
+
or DEFAULT_PROJECT_ID,
|
|
45
|
+
cookie_file=str(cookie_lib.COOKIE_FILE),
|
|
46
|
+
wiz_file=str(cookie_lib.WIZ_FILE) if cookie_lib.WIZ_FILE.exists() else None,
|
|
47
|
+
token_file=str(cookie_lib.CONFIG_HOME / "tokens"),
|
|
48
|
+
out_dir=os.environ.get("GOOGLE_FLOW_API_OUT", str(DEFAULT_OUT_DIR)),
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _fail(exc: Exception) -> dict[str, Any]:
|
|
53
|
+
return {
|
|
54
|
+
"ok": False,
|
|
55
|
+
"error": str(exc),
|
|
56
|
+
"error_type": type(exc).__name__,
|
|
57
|
+
"hint": (
|
|
58
|
+
"reCAPTCHA rejected: re-run flow_generate_* (auto-mint retries), or flow_relogin "
|
|
59
|
+
"if cookies are stale"
|
|
60
|
+
if isinstance(exc, RecaptchaRejected)
|
|
61
|
+
else "run flow_relogin if the message mentions sign-in or cookies"
|
|
62
|
+
),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@mcp.tool()
|
|
67
|
+
def flow_relogin(browser: str | None = None, project: str | None = None) -> dict[str, Any]:
|
|
68
|
+
"""Re-login by copying the .google.com cookies from this Mac's browser.
|
|
69
|
+
|
|
70
|
+
Detects the default browser via macOS LaunchServices (Chrome, Edge, Brave, Arc,
|
|
71
|
+
Safari, Firefox, Opera, Vivaldi, Chromium), reads its Google cookie jar, writes
|
|
72
|
+
it to ~/.config/google-flow-api/cookies.json (mode 0600), then proves the session
|
|
73
|
+
by opening the Flow project page and scraping at/bl/fsid.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
browser: optional browser name to force (e.g. "Chrome", "Edge", "Safari").
|
|
77
|
+
project: optional Flow project id to validate against.
|
|
78
|
+
"""
|
|
79
|
+
try:
|
|
80
|
+
return cookie_lib.relogin(browser=browser, project=project)
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
return _fail(exc)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@mcp.tool()
|
|
86
|
+
def flow_health() -> dict[str, Any]:
|
|
87
|
+
"""Report config paths, cookie jar freshness and whether the Flow session is alive."""
|
|
88
|
+
info: dict[str, Any] = {
|
|
89
|
+
"ok": True,
|
|
90
|
+
"config_home": str(cookie_lib.CONFIG_HOME),
|
|
91
|
+
"cookie_file": str(cookie_lib.COOKIE_FILE),
|
|
92
|
+
"cookie_file_exists": cookie_lib.COOKIE_FILE.exists(),
|
|
93
|
+
"wiz_file_exists": cookie_lib.WIZ_FILE.exists(),
|
|
94
|
+
"out_dir": os.environ.get("GOOGLE_FLOW_API_OUT", str(DEFAULT_OUT_DIR)),
|
|
95
|
+
"project": os.environ.get("FLOW_PROJECT_ID") or DEFAULT_PROJECT_ID,
|
|
96
|
+
"default_browser": cookie_lib.default_browser_label(),
|
|
97
|
+
}
|
|
98
|
+
try:
|
|
99
|
+
client = _client()
|
|
100
|
+
wiz = client.refresh_wiz()
|
|
101
|
+
info["session"] = "ok"
|
|
102
|
+
info["at_prefix"] = wiz["at"][:18] + "…"
|
|
103
|
+
info["cookies"] = client.cookie_count
|
|
104
|
+
except Exception as exc:
|
|
105
|
+
info["session"] = "dead"
|
|
106
|
+
info["session_error"] = str(exc)
|
|
107
|
+
info["hint"] = "run flow_relogin"
|
|
108
|
+
return info
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@mcp.tool()
|
|
112
|
+
def flow_generate_image(
|
|
113
|
+
prompt: str,
|
|
114
|
+
out: str | None = None,
|
|
115
|
+
project: str | None = None,
|
|
116
|
+
) -> dict[str, Any]:
|
|
117
|
+
"""Generate one image with Nano Banana Pro and download the JPEG.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
prompt: the image prompt.
|
|
121
|
+
out: optional absolute output path; defaults to
|
|
122
|
+
~/Downloads/google-flow-api/<timestamp>_<slug>.jpg
|
|
123
|
+
project: optional Flow project id.
|
|
124
|
+
"""
|
|
125
|
+
try:
|
|
126
|
+
return {"ok": True, **_client(project).generate_image(prompt, out=out)}
|
|
127
|
+
except Exception as exc:
|
|
128
|
+
return _fail(exc)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@mcp.tool()
|
|
132
|
+
def flow_generate_video(
|
|
133
|
+
prompt: str,
|
|
134
|
+
out: str | None = None,
|
|
135
|
+
project: str | None = None,
|
|
136
|
+
timeout: int = 600,
|
|
137
|
+
poll: float = 5.0,
|
|
138
|
+
) -> dict[str, Any]:
|
|
139
|
+
"""Generate one 8s 720p video with Omni 1.2 Flash, wait for the render, download the MP4.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
prompt: the video prompt.
|
|
143
|
+
out: optional absolute output path.
|
|
144
|
+
project: optional Flow project id.
|
|
145
|
+
timeout: seconds to wait for the render before giving up.
|
|
146
|
+
poll: seconds between status polls.
|
|
147
|
+
"""
|
|
148
|
+
try:
|
|
149
|
+
return {
|
|
150
|
+
"ok": True,
|
|
151
|
+
**_client(project).generate_video(
|
|
152
|
+
prompt, out=out, timeout=timeout, poll_interval=poll
|
|
153
|
+
),
|
|
154
|
+
}
|
|
155
|
+
except Exception as exc:
|
|
156
|
+
return _fail(exc)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@mcp.tool()
|
|
160
|
+
def flow_video_status(media_id: str, project: str | None = None) -> dict[str, Any]:
|
|
161
|
+
"""Poll one video job: return its status codes and any download URL.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
media_id: the media/job id returned by flow_generate_video.
|
|
165
|
+
"""
|
|
166
|
+
try:
|
|
167
|
+
client = _client(project)
|
|
168
|
+
urls, status = client.video_status(media_id)
|
|
169
|
+
return {"ok": True, "media_id": media_id, "status": status, "urls": urls}
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
return _fail(exc)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@mcp.tool()
|
|
175
|
+
def flow_download(
|
|
176
|
+
media_id: str,
|
|
177
|
+
kind: str = "video",
|
|
178
|
+
out: str | None = None,
|
|
179
|
+
project: str | None = None,
|
|
180
|
+
) -> dict[str, Any]:
|
|
181
|
+
"""Download an existing Flow media id (no generation, no reCAPTCHA, spends nothing).
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
media_id: image or video media id.
|
|
185
|
+
kind: "video" or "image".
|
|
186
|
+
out: optional absolute output path.
|
|
187
|
+
project: optional Flow project id.
|
|
188
|
+
"""
|
|
189
|
+
if kind not in ("video", "image"):
|
|
190
|
+
return {"ok": False, "error": "kind must be 'video' or 'image'"}
|
|
191
|
+
try:
|
|
192
|
+
client = _client(project)
|
|
193
|
+
result = client.download_media(media_id, kind=kind, out=out)
|
|
194
|
+
return {"ok": True, "media_id": media_id, **result}
|
|
195
|
+
except Exception as exc:
|
|
196
|
+
return _fail(exc)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def main() -> None:
|
|
200
|
+
mcp.run()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
if __name__ == "__main__":
|
|
204
|
+
main()
|