Skip to content

Latest commit

 

History

History
825 lines (704 loc) · 89.7 KB

MCP.md

File metadata and controls

825 lines (704 loc) · 89.7 KB

Model Context Protocol (MCP) Server for gflow-cli

The gflow-cli MCP server connects Claude Code, Claude Desktop, Cursor, VS Code, Codex and any other MCP client to Google Flow. Its tools generate Veo 3.1 and Omni video and Nano Banana and Imagen images, create local speech narration, manage reusable Characters, upscale, download, and read the Flow credit balance, over stdio (gflow mcp run) or Streamable HTTP (gflow serve). gflow mcp run --no-spend registers no credit-spending tool. Quick setup: uv tool install gflow-cli, gflow auth login --browser chrome, then gflow mcp setup (Claude Desktop) or the Claude Code plugin (§ 4).

This document describes the design, configuration, security model, and developer setup for the gflow-cli MCP server.


1. Architecture

The gflow-cli MCP server acts as a type-safe JSON-RPC interface, supporting two transport mechanisms:

  1. stdio Subprocess Transport (gflow mcp run): Runs over standard input/output (stdio), ideal for direct integration with local desktop agents like Claude Desktop, Cursor, or VS Code.
  2. Streamable HTTP Transport (gflow serve): Runs as a background web daemon over HTTP at /mcp, ideal for decoupled web UI dashboards, concurrent scripts, or external clients. The legacy HTTP+SSE transport remains available for one deprecation cycle via gflow serve --transport sse.

Protocol versions

The server is built on the mcp>=2 Python SDK and negotiates the protocol per connection, serving both eras from one binary:

Era Versions Notes
Handshake (legacy) 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25 initialize/initialized exchange, Mcp-Session-Id
Modern (stateless) 2026-07-28 No handshake, no session id; protocol version and client capabilities ride in _meta on every request

We write no protocol code for this — the SDK's low-level Server.run drives serve_dual_era_loop, and the client's first request decides the era.

The 2026-07-28 stateless core costs us nothing structurally: the server holds no per-connection state. Cross-call continuity lives in SQLite (gflow.db) and the Chromium profile directory, keyed by the profile argument that every tool already takes — which is exactly the "server-minted handle passed as an ordinary tool argument" pattern the spec now prescribes. ProfileLease is a cross-process file lock, not a session, so it is unaffected. We use none of the features the spec deprecated (Roots, Sampling, Logging).

Dependency bound. pyproject.toml pins mcp>=2.0.0,<3. The upper bound is mandatory, not cosmetic: MCP SDK majors carry breaking protocol-era changes (2.0.0 deleted mcp.server.fastmcp outright, which an unbounded mcp>=1.0.0 happily resolved into — breaking every fresh install of this surface while CI stayed green on the lockfile). The resolve-drift CI job installs from the declared ranges without the lockfile and smoke-imports this surface, so the next such break fails CI instead of reaching users.

Response caching. 2026-07-28 added ttlMs/cacheScope to list results. Our listing surfaces are decided at import time by decorators, so tools/list, prompts/list, and resources/list advertise a one-hour TTL. resources/read gets five minutes because it is not static — the known-issues resource reads KNOWN_ISSUES.md off disk. cacheScope is private throughout: gflow is a local, single-user daemon driving one user's authenticated browser profile, so public would authorize shared caching of user-scoped responses.

┌────────────────────────────────────────────────────────────┐
│      Client AI Agent (Claude / Cursor / Web Dashboard)     │
└─────────────┬───────────────────▲──────────────────────────┘
              │ JSON-RPC          │ JSON-RPC
              │ (stdio / HTTP)    │ (stdout / SSE)
┌─────────────▼───────────────────┴──────────────────────────┐
│        MCP Server Adapter (MCPServer / FastAPI app)         │
│  Exposes: Tools, Prompts, Resources                        │
└─────────────┬──────────────────────────────────────────────┘
              │ internal calls
              ▼
┌────────────────────────────────────────────────────────────┐
│                       gflow-cli Core                       │
│  - FlowApiClient (Playwright / REST requests)               │
│  - SQLite operations catalog (DataStore)                   │
├──────────────────────────────┬─────────────────────────────┤
│   Chromium Profile Lock      │      Direct SQLite Read     │
│   (asyncio & file-based)     │      (Fast read paths)      │
└─────────────┬────────────────┴──────────────┬──────────────┘
              │ writes cookies                │ queries history
              ▼                               ▼
     [profile_<name>/]                  [gflow.db]

Adapters side-by-side

Both Click CLI (src/gflow_cli/cli.py) and MCP Server (src/gflow_cli/mcp/) are thin adapter layers that drive the core application services (FlowApiClient and repository.py), ensuring zero duplication of business logic.


2. Tools, Prompts, and Resources

gflow_video_transcribe(file, out_file, language, profile) transcribes a local video or catalog UUID to timed SRT using the configured OpenAI-compatible /audio/transcriptions route. gflow_video_captions(file, srt, language, out_file, profile, position, margin, font_size, box_opacity) burns an authored SRT into a local clip or transcribes first when srt is omitted (position: 'bottom'/'top'/'middle', margin px from edge, explicit font_size px, box_opacity 0.0–1.0). The input schema declares those bounds (margin >= 0, font_size 1–1000, box_opacity 0.0–1.0), and a value outside them, or a boolean, is refused by the protocol's argument validation with isError: true and a plain validation message rather than a problem-details envelope; nothing is rendered or spent. Both tools are direct, credit-free calls and need the chain extra (install); output files stay inside GFLOW_CLI_OUTPUT_DIR. The Google Gemini default is refused before audio is sent. Configure an OpenAI, Groq, or local Whisper-compatible URL. gflow_video_assemble needs the chain extra too.

gflow_narrate(text, out_file, provider, voice, rate, pitch) is the direct, credit-free twin of gflow audio narrate; the Edge provider needs the tts extra (install). It stays registered under --no-spend. Narration text is sent to the selected provider, Edge Read Aloud or Gemini; Gemini uses the separate GFLOW_CLI_GEMINI_TTS_API_KEY. Output paths are confined to GFLOW_CLI_OUTPUT_DIR.

The server registers three protocol surfaces:

Tools (Executable actions)

  • gflow_extend_video(source, prompt, duration, reference_images, aspect, max_credits, profile, project, project_name, out_file, wait, browser_visibility): Worker-queued single-segment video extend on flow.google.com. source accepts either a local video path (.mp4/.m4v/.mov/.3gp/.avi, auto-creating a project if project is omitted) or an existing Flow clip UUID (requires project or a catalogued clip). Supports optional duration (3-10 seconds; omitted, Flow's current setting is kept and the result reports the length sent), 0-3 reference_images (local image paths or catalogued UUIDs in caller order), optional aspect (9:16/16:9 verification), and max_credits pre-submit quote cap. Gated by --no-spend; out_file must resolve inside the configured output directory.
  • gflow_video_assemble(clips, out_file, music, voiceover, clip_volume, music_volume, voiceover_volume, duck, profile): Direct, credit-free local processing; joins local files or catalog video IDs with verified local copies, optionally mixes local music and voiceover audio files, and returns the same result fields as gflow video assemble --json. Ducking lowers music and clip audio while voiceover is present by default. out_file must be inside the configured output directory, uses the first clip's size and frame rate, and refuses existing files (an empty file left by an interrupted run is cleared once older than 60 s). It runs in-process on a background thread, not through the worker queue. Example: {"clips":["clip-a.mp4","clip-b.mp4"],"out_file":"assembled.mp4","music":"score.wav","voiceover":"narration.wav","duck":true}. out_file is relative to the configured output directory; music and voiceover are local audio paths.

gflow_generate_video and gflow_edit_video add max_credits: int | null = null as a per-command cap. The worker checks Flow's own pre-submit quote and returns CreditCapExceededError (exit 45, charged: no) if the quote is missing or above the cap; queued payloads preserve the parameter. It defaults to the GFLOW_CLI_MAX_CREDITS setting when omitted. An omitted parameter cannot clear that environment default for one MCP call.

Browser visibility. gflow_generate_image, gflow_generate_video, gflow_extend_video and gflow_upscale_video take browser_visibility (auto / headless / headed, case-insensitive; any other value is a 400 problem-details envelope), the twin of the CLI's --browser-visibility; omitted, the server's GFLOW_CLI_BROWSER_VISIBILITY applies. Under auto, a measured shape runs with a headless browser that only mints the reCAPTCHA token and is sent over direct HTTP; any other shape, and every video with a max_credits cap, opens a headed browser, except a capped text-to-video of an explicit measured model, duration and resolution, which runs headless (#1554). A gflow_generate_video reference-to-video from exactly one local image (no saved asset, character or @ mention, count 1) runs headless too. Another exception is gflow_extend_video on flow.google.com: it drives Flow's UI, which is measured headless, so auto runs it headless (#1554), as do the page fallback of gflow_media_trash / gflow_media_restore, a gflow_generate_image call whose only reference is one local file in an existing project, when the request would go direct once the file is uploaded, and the gflow_upscale_video download-menu scales (720p, 270p, and 4K, whose headless run is unmeasured). A refusal Flow did not charge is retried once from a new headless browser; a second one is final (WafRejectionError, charged: "no", retryable: false, next_action: "wait"). headless for any other Flow UI shape is unsupported in v0.108.0 (#1554). The completed result (blocking and queued alike) carries route (direct / ui), visibility (headless / headed) and retried (true when the single retry ran). The per-command list is BROWSER_MODES.

  • gflow_generate_image(prompt, model, aspect, count, reference_images, reference_entities, reference_entity_names, tools, profile, project, project_name, instructions, ui_mode, thinking_level, out_file, wait, browser_visibility): Triggers text-to-image / image-to-image (Imagen / Nano Banana). thinking_level (low/medium/high, matched case-insensitively, mirroring CLI --thinking-level) binds Flow's image thinking-level toggle in the settings pane (omitting leaves Flow's existing setting untouched). out_file sets an explicit destination file path (mirrors CLI --out-file; legacy output removed in #1158). There is no seed parameter: Flow picks the seed and the image request cannot carry one (removed in #1013, as the CLI's --seed was in v0.8.0). A completed result reports the catalogued seed under seed: the seed Flow chose on the classic image paths, 0 on the agentic / agent-only arms (which observe none), null if none was recorded — the MCP twin of gflow image t2i --json's images[].seed. instructions is an optional list of ephemeral agent-instruction strings (agentic cohort only). reference_images switches to i2i and accepts either a local file path or a generated image's Flow media UUID. A UUID reference is attached by selecting the already-existing asset in Flow's reference picker — no duplicate copy is uploaded (locating the tile by the media id in its thumbnail URL, and searching the recorded display name to surface it when needed); gflow falls back to uploading the asset's on-disk local file only when it can't be located in place (e.g. it lives in a different project's picker). project generates into an existing Flow project id (mirrors CLI --project; when omitted, GFLOW_CLI_PROJECT is used unless project_name asks for a new project, #1039) — pass the reference's project to keep it selectable in place. ui_mode selects the Flow UI arm (auto/classic/agentic, mirroring CLI --ui-mode, matched case-insensitively). Since #595 auto means "no arm was asked for" and resolves to classic — the arm that can satisfy an image request — so an account in Flow's agentic cohort aborts pre-submit (exit-28 equivalent envelope, zero credits) instead of failing mid-run with selector drift or video bytes; the agentic arm is bound only when named. Passing instructions forces agentic automatically, so ui_mode="classic" + instructions is a hard conflict rather than a silent drop. An unknown value returns a 400 problem-details envelope. See CONFIGURATION § GFLOW_CLI_UI_MODE. model is nano2 (Nano Banana 2.1 on flow.google.com; nano2.1 also accepted), nano2-lite (Nano Banana 2 Lite), nano-pro (Nano Banana Pro) or image4 (Imagen 4, no longer in Flow's menu); other aliases are accepted too. On migrated flow.google.com accounts, T2I and local-file I2I are supported with Nano Banana 2.1 (nano2, #958) / 2 Lite / Pro, all five aspects (16:9, 4:3, 1:1, 3:4, 9:16) and count 1–4; the measured shapes are sent as a direct ogiZ0b request with a token from a headless browser, and the rest are submitted by Flow's own page (DIRECT_TRANSPORT). @Name character mentions in the prompt are attached through the composer's @ picker and verified as character chips before submit (#723). reference_entities must be paired with reference_entity_names there (an id alone is refused, exit 36); a reference_images UUID is referenced in place when the catalog records it in the same project (#995), and a local reference_images file is uploaded into the project once and mentioned in place on later calls with the same file, like the CLI's --ref (#772); an output path gflow cannot write ends in the exit-11-equivalent envelope, with the image still in the Flow project (#1091); other UUID references, instructions and Imagen 4 remain pre-submit refusals there. An agent-only composer (see below) takes T2I only. When Flow returns fewer images than count, the reply is still completed, files lists the images produced, and the warnings list includes the object {"type": "images_missing", "requested": 4, "returned": 3} (a failed reply carries it too when the images came back short before the failure) (#1489). Each saved image is checked against the request at no cost, and a mismatch adds a warnings entry carrying its media_name: aspect_mismatch (decoded width/height more than 10 % off the requested aspect), echoed_reference (byte-identical to a local reference image) or tiny_file (under 8 KB, with bytes and min_bytes); the reply stays completed and the file is kept, and wait=true and tasks/get report the same entries (#1534). A path that reads the images off the page (Agent mode, an agent-only composer, or a lost reply) fails instead when some are missing. The queued (wait=false) and blocking (wait=true) calls use the same typed payload and worker path.

  • gflow_generate_video(prompt, mode, aspect, initial_frame, end_frame, reference_images, reference_entities, reference_entity_names, model, duration, resolution, count, tools, profile, project, project_name, ui_mode, out_file, max_credits, wait, browser_visibility): Triggers vertical or landscape video generation (Veo). out_file sets an explicit destination file path (mirrors CLI --out-file; legacy output removed in #1158). mode is t2v/i2v/r2v; model (veo_lite/veo_fast/veo_quality/omni_flash/omni_1_2_flash, aliases accepted), duration (seconds — 4/6/8 for Veo 3.1, 4/6/8/10 for omni_flash, every integer 3–15 for omni_1_2_flash, at most 10 with an end_frame; with no model, 4/6/8/10), resolution ('360p' or '720p', supported on the Omni models; on any other model, or on the labs editor, the job fails pre-submit with the exit-11-equivalent envelope and no credits spent). Whether Flow renders a duration control at all is account/cohort-dependent: on an account that renders none, the job is accepted here and fails in the worker pre-submit (exit 23 equivalent on the labs driver, exit 11 equivalent on the migrated flow.google.com host — now the default t2v route, #650 — no credits spent either way) rather than being rejected up front — see KNOWN_ISSUES (#451/#288/#630), and count mirror the CLI gflow video flags — an omitted model lets the transport apply its i2v veo-lite default (issue #125), and every model — omni_flash included — accepts i2v with a start frame and with an end frame (wire-verified 2026-09-02, issue #626); i2v requires initial_frame, r2v requires reference_images or reference_entities; project generates into an existing Flow project id (mirrors CLI --project; when omitted, GFLOW_CLI_PROJECT is used unless project_name asks for a new project, #1039); on an account Google has moved to flow.google.com (GFLOW_CLI_FLOW_HOST, read from the server/daemon environment, not per call — see CONFIGURATION § GFLOW_CLI_FLOW_HOST) omitting project creates one there first (#864); there, on the classic migrated composer (an agent-only one takes text-to-video only — see below), the ported modes are text-to-video; image-to-video with a local initial_frame (at the measured key, 9:16 with the default Veo 3.1 Lite and no duration / resolution / end_frame, the frame is uploaded and the request sent over direct HTTP with a headless browser; see DIRECT_TRANSPORT), optionally with a local end_frame (start+end interpolation, #639 — on the UI path local files are uploaded under a run-unique name like hero-a1b2c3d4.png, #792), or captioned image UUIDs the local catalog records in the same project (#1542, bound in place on the UI path via /asb/<token> — the UUID frame skips upload, including Start+End and mixed local+UUID pairs where only the local frame uploads); and reference-to-video with local reference_images (each file is uploaded the same way — run-unique name included — and attached as an @ mention of that name in the prompt; duration there accepts every integer from 3 through 15 with explicit model="omni_1_2_flash" (set through its duration slider; Google AI plans are required above 10) and 4/6/8/10 with explicit omni_flash; Veo or an unspecified model accepts only 8, because measured shorter Veo requests dropped the references and billed text-to-video, so any other value returns the exit-11-equivalent envelope. An omitted r2v duration still pins 8 to avoid inheriting the editor's previous setting). A cross-project Flow media UUID (or an un-captioned UUID with a verified local fallback) as initial_frame/end_frame, a character on t2v or i2v, and reference_entities without paired reference_entity_names return the exit-36-equivalent envelope (an uncatalogued/unusable UUID or a non-path string such as @Name returns 400 before dispatch); r2v takes a saved character when each reference_entities id is paired with its reference_entity_names entry, with or without local reference_images (#723). initial_frame, end_frame, and reference_images each accept either a local file path or the Flow image UUID of a generated asset — pass a generated image's id straight in to chain image→video, and gflow attaches it for you. Since v0.58.0 (#529) the CLI and MCP surfaces are unified for i2v frames: the UUID keeps its identity and is enriched with the catalog's recorded display name plus an integrity-verified local fallback, so both transports prefer selecting the exact asset in the project's media picker (no duplicate upload). On labs.google, a missing tile falls back to re-uploading the recorded local file only if its byte count/SHA-256 still match; on flow.google.com (#1542), there is no local-file upload fallback — a missing or unrendered same-project tile reloads the grid up to ~90 s (plus at most one reload cycle) and fails with the exit-32-equivalent envelope. A UUID that isn't in your local asset catalog is rejected up front with a clear "Reference Not Found" error; a catalogued asset with neither a display name nor a verified local file gives a "Reference Not Usable" error (re-generate it or pass a local path). r2v UUID refs are resolved to the recorded local file for upload. ui_mode selects the Flow UI arm (#299 PR-A, mirroring CLI --ui-mode) and applies to every mode of this tool, including r2v — unlike the CLI, where video r2v/chain have no flag and follow the env-only path. On labs and the classic migrated composer, video generation has only a classic driver, so auto ≡ classic: both verify the classic editor pre-submit and abort before spending credits if it is unreachable. ui_mode="agentic" is rejected with a 400 problem-details envelope, because no agentic video driver exists yet. (An agent-only migrated composer is routed before this check: text-to-video runs through its chat agent under ui_mode auto or classic — "agentic" is still rejected with the 400 above, before any browser work — and other video forms return the exit-36-equivalent envelope before anything is clicked.) Values are matched case-insensitively. (MCP tools return envelopes, never process exit codes — the CLI equivalents of these aborts are exit 28 and exit 2 respectively.) See CONFIGURATION § GFLOW_CLI_UI_MODE. On a model Flow is retiring, the reply (the wait=true result and the queued task's tasks/get result alike) also carries "warnings": [{"type": "model_retiring", "model": "<name>", "retires_on": "<ISO date>"}] (#1375); the job still runs, and once Flow's menu stops offering the model it fails before submit, charged nothing.

  • gflow_edit_video(source, prompt, reference_images, model, aspect, resolution, max_credits, tools, profile, project, project_name, out_file, wait): Edits a local video file (.mp4/.m4v/.mov/.3gp/.avi, up to 1 GB) or an existing Flow clip media UUID on flow.google.com (jIps6, Omni models only, default omni-1.2, single-clip output) with 0–5 optional reference_images (local paths or catalog image UUIDs resolved to local files) for a local source file. With a media UUID source, reference_images are refused before the queue (exit 11, charged: no): references are not ported to editing an existing clip yet; download the clip with gflow data download MEDIA_ID --out DIR and pass the file. max_credits enforces Flow's pre-submit credit quote (refusing missing or over-cap quotes at zero spend). Local files support optional aspect (16:9/9:16) and resolution (360p/720p); existing Flow media UUIDs need a project (project, else the catalog's record, else GFLOW_CLI_PROJECT, the CLI's resolution) and keep source aspect at 720p. The worker refuses a missing or unsupported file (exit 11), GFLOW_CLI_FLOW_HOST=labs.google (exit 36) and a mistyped queued payload (QueueSchemaError, exit 30) before it creates a project, all charged: no. out_file must stay inside the configured output directory. Gated by --no-spend with the other credit-spending tools.

Attaching a saved character (the identity axis). Three routes reach Flow's referenceEntities wire and they dedupe against each other: an @Name mention inside the prompt, reference_entities by entity id, and reference_entity_names as the display names paired with those ids (required on flow.google.com). Prefer the id when a display name could be ambiguous — Flow does not enforce unique names. reference_images is a different axis entirely: it buys a look, not an identity. Use gflow_character_list to discover ids and display names on flow.google.com. On flow.google.com an id must be paired with its name in reference_entity_names (an id alone is exit 36). See REFERENCE_STRATEGIES.

wait and long generations (#481, #1097). Both generation tools take wait (default true), and its schema description in tools/list says what follows. With wait=true the tool runs the job inside the call, so the call stays open for the whole generation — minutes for a video — which can outlast an MCP client's tool timeout. Raise the client's tool timeout, or use wait=false. If the job has not finished when a wait=true call returns, the reply has status: "failed" plus task_status: "pending" or "processing": the job is unfinished, not failed, and its task_id can still be read back later. With wait=false the tool returns {"status": "pending", "task_id": ...} at once and runs the job in the background of the same server process, one job at a time per profile within that server. Read it back with the SEP-2663 Tasks extension (io.modelcontextprotocol/tasks): poll tasks/get. While the job runs it answers working; once it has finished it answers completed, and its result field holds the same reply wait=true returns (files, project id, seed). A failed generation is completed too, with result.isError: true — SEP-2663 keeps failed for protocol errors — so check isError before you use the files. tasks/cancel aborts the job locally and answers with an empty acknowledgement; tasks/get then answers cancelled. It is the same abort as the CLI's gflow cancel <id> (#1198), whichever server runs the job: a job not yet submitted to Flow (pending, or claimed but stopped at its submit gate) is stored cancelled, statusMessage saying nothing was charged; a job a gflow worker already submitted is stored abandoned, statusMessage saying it may still be charged, because Flow cannot be told to cancel it; a finished job is left as it is. Either way the task stays cancelled, even if its generation finishes later. tasks/get reports the charge only in statusMessage; the charged/next_action members are on the CLI's --json. There is no tasks/result: SEP-2663 removed it, and the server answers it -32601. Two limits: tools/call returns gflow's own {status, task_id} handle, not a SEP-2663 resultType: "task", so a client's built-in task support will not pick the job up; and a task id is a bearer capability — any client that can reach the server and knows the id can read or cancel it. The job lives only as long as the server: when the client closes a stdio server, or gflow serve stops, running jobs are stopped and stored by how far they got: failed before the submit, indeterminate after it (a credit may have been spent, so check the Flow project before you retry); tasks/get reads both as cancelled. A job that fails with an unexpected (untyped) error follows the same rule: after its submit it is stored indeterminate with next_action: reconcile; tasks/get reads that job as completed (an isError result), with a statusMessage saying a credit may have been spent. A gflow error keeps the job failed with its own charged and next_action. A server killed outright leaves its row processing — see Known issues. Jobs queued with wait=false by v0.90.0 or earlier were never run and are not picked up now: they stay pending, and tasks/cancel clears them. tasks/get sends ttlMs: null, because gflow keeps task rows with no expiry.

  • gflow_auth_status(profile): Credit-free, non-interactive Flow session probe (#497) — wraps the same fail-closed verify_flow_profile check as gflow auth status. Returns {"status": "authenticated", "profile", "user_email"} or a problem-details error with a remediation_hint, and only authenticated has isError: false (#1464); a verification_error outcome (HTTP 503, retryable: true) means a network/endpoint problem, which re-login does not fix, and a profile_marker_missing outcome (HTTP 409, retryable: false, #796) means the profile lost its .gflow_browser_strategy marker so its cookies cannot be read — a retry does not help, and neither does a plain gflow auth login; re-run gflow auth login --browser chrome for that profile. A cookie_store_unreadable outcome (HTTP 409, retryable: false, #796) means the profile's Chrome cookie database is corrupt or unreadable — a local file fault, not the network; close any Chrome window using that profile, then re-run gflow auth login for it. A profile_unavailable outcome (HTTP 409, retryable: true, #1400) means the headless Chrome cookie read, or the flow.google.com session probe, could not run (#1640); detail names the error class. It is local, not the network; close any Chrome window using that profile and retry. A profile another gflow process or a Chrome window holds returns the profile-locked error (next_action: wait) with that holder's remediation. Any other unauthenticated outcome is a dead session (HTTP 401). Call it before a generation tool to fail fast on dead auth, before a long blocking generation call. Every session result also carries wire: {status, build} (#1229): the health of the direct, browser-free credits read, probed first with one GET and one POST to flow.google.com; nothing is sent while GFLOW_CLI_WIRE_READS is off, while any proxy is configured, or inside a throttle window. status is accepted, or the reason credit reads fall back to the browser (signed_out_shell, http_401, store_unreadable, disabled, proxy_configured, throttled, no_chrome_version, network, redirect, http_400, http_error, unparseable, unexpected); build is Flow's build label, else null. It never changes the session status, except throttled: Flow is rate-limiting the account, so the browser probe is skipped and the tool returns status: "throttled" with a retryable 429 error carrying retry_after seconds. store_unreadable means the profile's cookies could not be read (Chrome has it open, it has no saved session, or the read did not finish within 5 s). gflow doctor reports the same probe for the default profile as its auth.wire_read check (doctor itself has no MCP twin, #542). Login/logout remain CLI-only (genuinely interactive).
  • gflow_get_credits(profile, all_profiles, refresh): Current Flow balance query; spends no credits. With all_profiles=true, inspects every saved profile sequentially and preserves successful balances plus total_credits when another profile fails. The balance is the number flow.google.com itself loads, which is the one Flow's account menu shows (#795). A zero balance returns credits: 0, not a wire-format error (#1632). It is read directly, with no browser, when Flow accepts the profile's saved session; otherwise it is read in the profile's browser, one browser launch per profile (#1229; when the direct read runs, and how to turn it off with GFLOW_CLI_WIRE_READS=0: CONFIGURATION). When Flow throttles the account (HTTP 429/503) the read for that profile fails with the rate-limit or network error rather than falling back to the browser, which would send the same requests. The tier fields (sku, service_tier, user_paygate_tier, subscription_credits) are always null. With refresh=true, a profile that lands on a sign-in page is renewed in a headless browser and read again: one more Chrome launch per such profile, no credits. This is the MCP twin of gflow credits user|list --refresh. It runs the same renewal as gflow auth renew, but only for a profile whose credits read lands on a sign-in page. auth renew itself has no MCP tool; see the exemption in tests/mcp/test_cli_parity.py. Without refresh the call is read-only; with it, an expired profile's saved cookies are rewritten. This tool spends no credits and returns no cookies, bearer tokens, or browser API keys. The balance funds Veo video generation; image generation uses separate per-model daily quotas. A page that loads but never fetches the balance is a FlowAppError (exit 31), never an auth error.
  • gflow_character_list(project, profile): Lists a project's saved Flow CHARACTER entities with their entity ids — read-only, spends no credits, drives a browser session. On flow.google.com, returns each character's entity_id, display_name, voice, personality, workflow_ids, and thumbnail_media_id (#875, #987). This is how an agent discovers what it can attach: pass entity_id in reference_entities paired with display_name at the same position in reference_entity_names (for image generation and video r2v on flow.google.com). On flow.google.com, @Name mention resolution keeps the pre-#987 character read (migrated_read=False), so an image @Name behaves as it did before — when the character source fails and no media asset matches, it attaches the first whitespace-delimited word after @ by name through the composer's @ picker — while video @Name is not supported there yet (exit 29, mention index unavailable); video r2v takes reference_entities plus reference_entity_names. Trashed characters are omitted from this catalog. An empty list means the project genuinely has none.
  • gflow_character_show(project, entity_id, name, profile): Shows one character by id or exact display name (exactly one selector required), returning its entity_id, display_name, voice, personality, workflow_ids, and thumbnail_media_id on flow.google.com (#875, #987). An ambiguous name is refused rather than resolved arbitrarily — which is the reason to prefer the id. Read-only; drives a browser session.
  • gflow_character_create(project, name, image, body_image, voice, personality, profile): Creates a character from local image files on flow.google.com (the twin of gflow character create --image): image is the portrait and body_image an optional body image, both paths on the machine running the server. Nothing is generated, so it spends no credits and stays available under GFLOW_MCP_NO_SPEND. Returns status, project and a nested character object holding entity_id, name, voice, workflow_ids and primary_media_ids; with GFLOW_CLI_FLOW_HOST=labs.google it is refused (exit 11, charged: no), because building from local files is not ported there yet (#639); a failure after the portrait upload names the character's entity id in remediation_hint when it is known, otherwise says a character may exist, and is marked not retryable (next_action reconcile): check gflow_character_list before calling again. gflow deletes nothing. An unknown voice is refused before a browser opens. Generating the face from a prompt (--face-prompt) stays CLI-only (#691).
  • gflow_character_voices(): Lists the preset voices available for Character TTS (name, description, sample URL). A static in-process lookup — no network, no browser, no profile, no cost. Call it to pick a valid voice name.
  • gflow_list_projects(profile, limit, offset): Queries the SQLite catalog for recent generation folders, paginated — the response carries count (rows in this page), offset, has_more, and next_offset (pass it back as offset for the next page; null on the last page).
  • gflow_usage_stats(weeks): Summarize local gflow-cli usage statistics over the last N weeks (default 12, range 1..53). Returns command invocation counts across surfaces from local telemetry (or null when telemetry is off) and generation counts by command, model, status, and month from the local catalog. Its telemetry block includes state, switch, upload (enabled and reason), and the current report (#1164). The tool reads local data and spends no credits; like other MCP calls, its telemetry hook may start a separate weekly upload when eligible. MCP does not expose telemetry on or off; those controls are CLI-only by design.
  • gflow_download_media(media_id, out_dir, profile): Fetches an already-generated asset from Flow by its media ID and writes it to disk — the recovery path for a generation that was billed but whose download failed. Spends no credits. The bytes are verified against the size Flow reports before the file is written, and the catalog's local_files row is updated. Returns path, bytes, media_id, workflow_id, project_id and profile. The transfer retries a dropped connection internally (#895), so a failure marked retryable means pause and call again — not immediately, and not in a tight loop: each call opens a browser under a per-profile lease, and a second concurrent call fails on that lease instead (exit 11).
  • gflow_upscale_image(media_id, scale, project, out_dir, profile): Upscales an already-generated image to 2K or 4K; it opens a headed browser under auto (a headless 2K upscale was refused as unusual activity on one of two accounts, #1554). scale is 2k or 4k (4K requires Ultra; Pro accounts support 2K). A scale the download menu does not list is exit 22 (upscale-unavailable), naming the listed scales. 2K spends no credits; whether 4K does has not been measured, so a 4K refusal reads charged: maybe / next_action: reconcile.
  • gflow_upscale_video(media_id, scale, project, out_dir, profile, browser_visibility): Upscales or exports an already-generated video to 4K Ultra (spends credits), 1080p Full HD, downloads it at 720p (the original, or for a clip with a smaller original Flow's 720p upscale), or exports a 270p animated GIF. scale is 4k, 1080p, 720p, or 270p. Flow decides which scales each clip offers (a Veo 3.1 Lite clip lists no 1080p; 4k requires Flow Ultra); a scale the clip's download menu does not list returns UpscaleUnavailableError (exit 22) naming the listed scales (#1338). With scale omitted, the tool exports 1080p, else 720p, else the 270p GIF, whichever the clip's menu lists enabled (never 4k, which needs an explicit scale), and the result's scale names the scale exported (#1344). Driven on flow.google.com only; 1080p was measured free (2026-10-07), as were 720p and the 270p GIF (2026-11-29) while 4K spends credits (measured 50 credits on Omni 1.2 Flash, 2026-11-23). A 1080p upscale of a clip the local catalog records as Omni 1.2 Flash, 4 s, 16:9 goes over direct HTTP with a headless browser that only mints the reCAPTCHA token; 1080p planned through the menu drives it in a headed browser. The result names the route the upscale took (ui when a planned direct attempt fell back to the menu) and the visibility. Under auto, the download-menu scales (720p, 270p, and 4K unmeasured) run in a headless browser (#1554).
  • gflow_list_tools(): Lists the prompt tools (name/title/description/category) accepted by the generate tools' tools param. Each tools item is {"name": <slug>, "options": {...}}, e.g. [{"name": "creative-director"}].
  • gflow_list_models(): The image and video model catalog, the same object as gflow models --json (#883); each model entry is what gflow models show <id> --json prints (#1196): per model name, label (image: Flow's menu name), the CLI's --model aliases (the generate tools accept each of them as model, plus wider spellings such as narwhal or veo_lite), ref_cap, default (image), and max_duration, durations (video: the clip lengths duration accepts for that model) and retires_on (video: the ISO date Flow retires the model, or null; #1375). aspects and video tiers sit on each section (image / video), not on the per-model entry, so models show --json does not carry them. Built from the same enums the generate tools use, so every alias it lists is accepted back. Static: no profile, no browser, no spend.
  • gflow_instructions_list(project, profile): Lists a project's persistent Agent-Mode instruction cards (live server brief; credits-free).
  • gflow_instructions_add(project, title, text, refs, enabled, profile): Adds a persistent instruction card. Each ref is classified automatically — local image path → uploaded image reference, asset UUID → image reference, anything else → character id/name (mirrors CLI instructions add --ref).
  • gflow_instructions_set_enabled(project, enabled, title|card_id, profile): Enables/disables one card selected by title or stable card id (covers CLI instructions enable/disable).
  • gflow_instructions_rm(project, title|card_id, profile): Removes one card from the brief.
  • gflow_instructions_toggle_mode(project, enabled, profile): Flips the brief-level master switch; cards are left untouched.
  • gflow_instructions_apply(project, cards, profile): Declarative full-sync — REPLACES all cards with the given set (destructive; same entry shape as the CLI instructions apply file).
  • gflow_doctor_composer(project, profile): Read-only, credit-free twin of gflow doctor --composer PROJECT_ID (#1386). Opens the project on flow.google.com in the profile's browser under the profile lease, waits at most 30 s, clicks nothing on the project page (the usual browser startup may pick the profile's own account on Google's account chooser), and returns {"status": "ok", "project", "composer"} with composer one of classic, agent_mode (the Agent switch is on), agent_panel (the agent panel is open), agent_only (#799: text-to-image and text-to-video only) or unknown. It never closes the panel or switches agent mode off; one page load is a snapshot. The rest of gflow doctor has no MCP twin (#542).
  • gflow_media_trash(media_id, project_id, profile, confirm): Moves a generated media item to Flow's Trash over the wire using batchexecute RPC pGCYOe. Credit-free (0 credits). With the direct read off or unavailable, the RPC is sent from a headless flow.google.com page under auto; the result reports route (direct / ui) and visibility (both apply to gflow_media_restore too). Requires explicit confirm=true (returns a 400 confirmation-required Problem Details error if false or omitted) to guard against accidental deletion. Trashed items are hidden from Flow project views and collections without permanent deletion, and can be restored using gflow_media_restore.
  • gflow_media_restore(media_id, project_id, profile): Restores a trashed media item back to its Flow project over the wire using batchexecute RPC pGCYOe. Credit-free (0 credits). Clears the metadata.archived flag, resets collection_id, and restores the catalog asset status to ready.

CLI↔MCP parity is enforced programmatically: tests/mcp/test_cli_parity.py walks every CLI leaf command and fails when one has neither a mapped MCP tool nor an explicit exemption with a stated reason. Note the deliberate asymmetry: gflow_generate_video has no instructions param (unlike gflow_generate_image) because the video pipeline (GenerateVideoRequest / the worker) has no instructions support — agentic-video is a typed divergence, and a dead parameter would be silently dropped. Both gflow_generate_image and gflow_generate_video support an out_file parameter mirroring the CLI --out-file flag (#414, #415, #1158), decoding explicit output destinations in the worker path (legacy output parameter removed in #1158). Both tools refuse an output path that names a directory (including the output directory itself) with a 400 Invalid Output envelope before anything is queued, as the CLI's --out-file refuses one (#1114). Unlike the CLI's --out-file, an MCP out_file — and the out_dir of gflow_download_media, gflow_upscale_image and gflow_upscale_video — must resolve inside the configured output directory (GFLOW_CLI_OUTPUT_DIR): a relative value is taken relative to it, and a value that resolves outside it (.., an absolute path elsewhere, a link leading out) is refused with a 400 Invalid Output / Invalid out_dir envelope before anything runs. An MCP client may be steered by untrusted content, so it cannot choose where on disk the server writes; for the same reason a tool that opens a browser profile takes profile only as a plain name, never a path (GHSA-hqfj-4jww-76f2). gflow update is a considered exemption, not a backlog item: the package manager would replace the venv under a live gflow mcp run and write its output onto the JSON-RPC stdout channel — the operator runs it and restarts the server. A read-only twin of gflow update --check would be harmless; it is the upgrade path if agents ever need version awareness beyond the initialize handshake.

Prompts (Orchestration templates)

  • expand_prompt: Helps the agent structure simple ideas into Google's official 5-component prompt formula (Subject + Action + Location + Composition + Style) before sending them to the generation tools.
  • create_character: Assists agents in defining face, body, and voice parameters for consistent subject generation.

Resources (Context feeds)

  • gflow://docs/mcp-guide: A specialized, agent-targeted guide instructing the LLM to use the registered MCP tools (rather than running raw shell wrapper commands).
  • gflow://docs/known-issues: Bounded index of KNOWN_ISSUES.md (titles + status, a few KB — #501); read gflow://docs/known-issues/{slug} for one issue's full text (capped at 16 KB). The old behavior injected the whole ~70 KB file per fetch.
  • gflow://db/schema: Exposes SQLite schema definitions, allowing agents to understand project and media tables.
  • capabilities://self: What gflow can drive, as yes/no/partial/unknown per capability with a note on every partial — the same JSON document as gflow capabilities --json (#1197), except on a no-spend server, where generate.image, generate.video and submit.no_wait are no (no generate tool is registered). Read it before planning: cancel.server and idempotent_submit are no, and submit.no_wait/status/wait are reached here through wait=false and tasks/get, which need a client with the SEP-2663 Tasks extension. Makes no call to Flow: reads only GFLOW_CLI_FLOW_HOST, and host reports that setting, not the host Flow serves. Key meanings: CAPABILITIES.md.

3. The Dilemma: Why we need the MCP Server (vs. Pure Skill)

We analyzed whether a terminal-driven CLI guided by a text skill (e.g., skills/gflow-cli/SKILL.md) is sufficient. The LLM Council concluded that the MCP server is fully justified for these reasons:

Dimension Direct CLI via Terminal Execution Native MCP Server Daemon
Output Fragility Ephemeral stdout/stderr log outputs are fragile to format adjustments, progress bars, and ANSI colors. Strictly structured JSON payloads containing explicit metadata and absolute output file URIs.
Process Lifecycle High process startup overhead (Python import latency) on every individual execution. Warm daemon process. Retains active caching of database metadata.
Concurrency A second concurrent process against the same profile is rejected immediately by the cross-process ProfileLease with ProfileLockedError (exit code 11) — a clean fail-fast, never a crash, never a wait. Different profiles run fully in parallel. Calls on one profile inside one server run one at a time — a second call waits for the first instead of failing. A profile held by a different process (a CLI run, another server) is waited out for up to 180 s (GFLOW_CLI_LEASE_WAIT_SECONDS, which a value you set yourself overrides) before ProfileLockedError; different profiles still run fully in parallel.
Error Handling Agent must scan logs for strings or parse exit codes to check status. A failed call is a tool result, not a JSON-RPC error: its structuredContent is a typed error envelope with mapped codes and clear remediation, and a plain call whose envelope has a failure status (error, failed, rate_limited, invalid_tools, or an unverified gflow_auth_status; see Error envelope) sets isError: true. A queued failure carries exit_code (in the server's active mode, GFLOW_CLI_EXIT_CODES, #1202) and exit_code_legacy.
Transport Safety Volatile console printing. Stdout is strictly isolated for JSON-RPC; all logs and warnings route to stderr.

Error envelope

A failed tool call is a tool result, not a JSON-RPC error. A plain (not task-augmented) tools/call whose envelope has a failure status (error, failed, rate_limited or invalid_tools, and every gflow_auth_status status but authenticated, throttled included) comes back with isError: true, and structuredContent carries the same envelope (#1453, #1464); a successful call has isError: false. These are the statuses the tool-use telemetry counts as failures, so a wait=true generation that ends failed reads isError: true, as the same job does on tasks/get. Other statuses keep isError: false, including pending, so read status as well. A wait=false job reports its own flag: its finished result on tasks/get has isError: true unless the job completed (see Tools).

MCP tool failures return a structured error object built from the same RFC 9457 Problem Details as the CLI, plus a retryable boolean. retryable: true marks a transient failure a scheduler can re-run without operator intervention — WAF/reCAPTCHA bounce (WafRejectionError), rate-limit (RateLimitError), transport timeout (TransportTimeoutError — but one raised after a submit click is false, see below), network blip (NetworkError — but not a failed download of media Flow already made, see below), a dropped browser session (BrowserSessionClosedError), a Flow web-app crash (FlowAppError), an agentic-cohort flap (FlowAgentUiError — but see the agent-only exception in § 6.1, which overrides it to false), an unreachable UI arm (UiModeUnavailableError), and a partially-completed sync (SyncPartialError). That list is errors.RETRYABLE_ERRORS, but it is no longer the whole answer: errors.is_retryable consults the instance first, so a raise site can override its class. Among them, Flow's /about redirect raises FlowAppError with retryable: false, and since 2026-09-11 that is a measurement, not a preserved default: caught during a live occurrence, 5/5 consecutive attempts over ~3 minutes landed on /about again, on the account's own project with a healthy session — so a retry is doomed and costs ~35 s each (#756). The A video submit gflow refuses on flow.google.com (#1178) is WireFormatError, retryable: false, aborted before it was sent (its hint says nothing was billed): re-running the same inputs usually repeats the refusal, so check the frames or references first. The second is the migrated agent-only composer (#799), which gflow drives through its chat agent: there FlowAgentUiError carries retryable: false because it means the agent did something other than what was asked — a credit confirmation quoting more than requested (gflow rejects it, nothing is approved; #988), a video confirmation whose count gflow cannot read (not approved, and left open in Flow for you to reject), a second credit confirmation, more results than requested, or an image turn that made nothing (a video turn that makes nothing ends in TransportTimeoutError, also retryable: false there, since the request was already sent) — and a blind re-run repeats the ask. Its detail may include the agent's last reply. The cause, and whether it ever clears, remain unmeasured. The same holds on the classic flow.google.com composer for any TransportTimeoutError raised after the submit click (#1010): an unreadable or missing submit reply, or a generation that is not terminal in time, is retryable: false, because Flow may already have made and billed it. An unreadable reply on a video run that uploaded a file (reference_images, initial_frame or end_frame) is followed to its clip instead and completes normally (#1112), and so is a one-clip text-to-video run, found by its exact prompt and model (#1141). Text-to-video with count above 1, a character-only run, or a clip the project listing cannot name exactly once still gets the retryable: false error. Likewise a failed download of a finished generation (MediaDownloadError, exit 6, type …/errors/media-download) is retryable: false (#941): the clip exists and was billed, so the recovery is gflow_download_media with its media_id, which spends nothing and stays retryable: true. The override also runs the other way: a reCAPTCHA mint failure (type …/errors/recaptcha-mint, exit 1, no request sent, no credit spent) is retryable: true when a navigation raced the mint or the page was a Flow page whose script had not loaded yet, and false on a page that is not a web page — each measured live (#915). Read the flag off the envelope; never re-derive it from the class list. Everything else (auth, content-policy, configuration, security) is terminal (retryable: false): retrying the identical request fails the same way. This flag is the same shared classification the CLI --json payload and the worker-queue error record use (errors.is_retryable) — the three surfaces cannot drift. On a captured failure the envelope also carries a remote-safe incident object ({id, capture_status} only — never a local path); see DEBUGGING § Automatic incident bundles.

The envelope also carries charged (no / maybe / yes: whether Flow may have billed) and next_action (retry, retry_after, wait, reauth, fix_input, reconcile, none), plus operation_id when an id exists (#1201). next_action always agrees with retryable: a billed clip's failed download reads charged: yes, next_action: reconcile, with its media id as operation_id. Envelopes the server builds by hand (bad parameter, no profile, an interrupted task) carry them too. Every type, its exit code and its defaults are listed in ERRORS.md.

Every tool routes through one error funnel. Unexpected (non-gflow) exceptions are masked: the client sees only the exception class name ("Unexpected RuntimeError; details were logged server-side.", status: 500, retryable: false) — raw exception text can embed filesystem paths, profile names, or token material and never leaves the server; the full message and traceback go to the server-side structured log (mcp.tool.unexpected_error).

The params echo of gflow_generate_video is the request as the caller made it. Its model, duration and resolution are the arguments passed, null when omitted. They are not the values the direct path resolved and sent; the CLI --json payload reports those (resolution and the sent request, see USAGE).

A failed generation task can still name its media. When Flow generated the media and only the download failed (a video whose transfer dropped, #895; an image whose local write failed, #1035), the status: "failed" reply of gflow_generate_image / gflow_generate_video also carries flow_media_id and, when the catalog knows it, flow_project_id. Both keys are absent when the task failed before Flow named any media. With count > 1, flow_media_id is the first image's id only; every image's id is in the catalog (gflow data list images; there is no MCP twin for that listing). A video is then recoverable with gflow_download_media; an image is not (that tool is video-only, #877), so open the project in Flow. The catalog keeps the image's asset row, with no local copy, under one FAILED operation.

A multi-image task that saved some of its images completes as a partial result (#1477). When gflow_generate_image asks for count > 1 and a download fails after at least one image was saved, the task is completed, not failed: files lists the saved images, and the reply (on wait=true and tasks/get alike) adds partial: true, requested, returned (images saved), missing_media_ids, charged: "no", next_action: "reconcile" and retryable: false. The missing images stay in the Flow project; fetch them from there rather than generating again, which spends the daily image quota again. A complete task carries none of these keys. When no image was saved the task still fails as described above. The CLI reports the same run with exit 80 (ERRORS).


4. Setup Instructions

Claude Code — the plugin (one step)

/plugin marketplace add ffroliva/gflow-cli
/plugin install gflow@gflow-cli

This installs the gflow-cli and video-production skills and registers this MCP server, so there is nothing further to configure.

It ships disabled on purpose. Claude Code starts a plugin's MCP servers automatically when the plugin is enabled — there is no separate prompt for the server itself. This server drives your own signed-in Google account, and Veo video generation bills your credits. So the plugin sets defaultEnabled: false: installing it does not start anything, and enabling it is a deliberate act. Images and composition cost nothing; only video spends.

The plugin also declares a required userConfig acknowledgement, which Claude Code prompts for when you enable it in the UI. Be aware that it is a prompt, not an enforcement gate — claude plugin enable on the command line succeeds without it. defaultEnabled: false is the control that actually holds.

The hard guarantee, if you want one, is --no-spend. It is not a policy the model is asked to respect: the credit-spending tools are never registered, so they do not appear in tools/list at all. Register the server yourself with gflow mcp run --no-spend (see the manual setup below) instead of using the bundled entry.

The plugin runs gflow mcp run, so gflow must be on your PATH (uv tool install gflow-cli) and you must have authenticated once with gflow auth login --browser chrome.

Which revision you get. /plugin marketplace add ffroliva/gflow-cli reads the marketplace from the repository's default branch, which in this project is develop — the integration branch, not the last release. So the plugin you install tracks develop, while the version string in its manifest and the documentation links inside its skills both point at the last released state. If you want a released revision, install from a tag instead of the default branch, or use the manual MCP setup below and a pinned gflow-cli from PyPI.

Claude Desktop Integration

Run the configuration helper command in your terminal:

gflow mcp setup

This merges the server entry into your Claude Desktop configuration file — existing content is preserved, and a pre-existing file is backed up as <name>.gflow-backup first. A corrupt config fails loud (exit 11) and is never overwritten:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

Other targets: gflow mcp setup --target cursor (~/.cursor/mcp.json) and --target vscode (the user-profile mcp.json, written with VS Code's servers + "type": "stdio" schema).

Existing entries are preserved: if your config already has a gflow or gflow-cli server entry (including the local-clone uv --directory variant below), gflow mcp setup leaves it completely untouched and reports "Already configured" — it only ever adds a missing entry.

Manual Configuration

Depending on how you installed gflow-cli, add one of the following configuration blocks under the mcpServers key of your claude_desktop_config.json:

Option A: Global Installation (Recommended)

Use this if you installed gflow-cli globally (e.g. via uv tool install gflow-cli or pip install gflow-cli):

{
  "mcpServers": {
    "gflow-cli": {
      "command": "gflow",
      "args": [
        "mcp",
        "run"
      ]
    }
  }
}
Option A2: Read-only server

Use this when the agent must never be able to spend credits (#496). The two credit-spending tools (gflow_generate_image, gflow_generate_video, gflow_upscale_video, gflow_extend_video, gflow_edit_video) are then never registered, so they do not appear in tools/list at all — invisible rather than refused. Every read-only tool stays available.

{
  "mcpServers": {
    "gflow-cli": {
      "command": "gflow",
      "args": [
        "mcp",
        "run",
        "--no-spend"
      ]
    }
  }
}

Setting GFLOW_MCP_NO_SPEND=1 in the environment does the same thing and also covers gflow serve. gflow mcp setup writes the plain (spending) block above — add the flag or the env var yourself if you want the read-only server.

Option B: Local Clone (Development)

Use this if you cloned the repository locally and run it via uv:

{
  "mcpServers": {
    "gflow-cli": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/gflow-cli",
        "run",
        "gflow",
        "mcp",
        "run"
      ]
    }
  }
}

Cursor Setup

  1. Open Cursor Settings -> Features -> MCP.
  2. Click + Add New MCP Server.
  3. Configure depending on your installation:
    • Global Installation:
      • Name: gflow-cli
      • Type: command
      • Command: gflow mcp run
    • Local Clone (Development):
      • Name: gflow-cli
      • Type: command
      • Command: uv --directory /path/to/gflow-cli run gflow mcp run

HTTP Daemon Setup (gflow serve)

For decoupled clients, local web interfaces, or multi-process frontends, run the daemon as an HTTP service:

gflow serve --port 8000 --host 127.0.0.1 --profile default

# Read-only daemon — the credit-spending tools are never registered (#496):
gflow serve --port 8000 --host 127.0.0.1 --profile default --no-spend

This serves the MCP server over Streamable HTTP, the current spec transport:

  • Endpoint: http://127.0.0.1:8000/mcp

The legacy HTTP+SSE transport is still available for one deprecation cycle:

gflow serve --transport sse --port 8000   # deprecated; logs a warning
  • Connection endpoint (SSE stream): http://127.0.0.1:8000/sse
  • Command posting endpoint: http://127.0.0.1:8000/messages/

Deprecated: the MCP 2026-07-28 spec reclassified HTTP+SSE as deprecated. Prefer the default --transport http. The spec's lifecycle policy guarantees a minimum twelve months between deprecation and removal.

stateless_http is deliberately not enabled. The stateless core exists so servers can scale out across interchangeable instances; gflow's value is the opposite — a warm daemon holding one live Chromium profile, serialized by ProfileLease. The protocol is stateless either way; that flag only governs transport bookkeeping we want to keep.

Authentication

Set GFLOW_DAEMON_TOKEN (alias GFLOW_CLI_DAEMON_TOKEN) and every request to the daemon must present it:

Authorization: Bearer <token>

A missing header, a non-Bearer scheme, or a wrong token is answered 401 with WWW-Authenticate: Bearer — on /mcp and on both halves of the deprecated SSE surface (/sse, /messages/). The comparison is constant-time (hmac.compare_digest), and auth is the outermost layer, so an unauthenticated caller learns nothing about the transport's DNS-rebinding allow-list. The same token guards the OpenAI-compatible route below.

Non-loopback binds (e.g. --host 0.0.0.0) require the token — gflow serve refuses to start without one (exit 11). A loopback bind with no token stays unauthenticated, which is the local single-user default.

OpenAI-compatible image endpoint

gflow serve (either transport) also answers POST /v1/images/generations in the OpenAI Images schema (#1365), so OpenAI SDK code can generate Flow images by changing its base URL:

import base64

from openai import OpenAI

# max_retries=0: the route keeps generating after a client disconnect, so an SDK retry on
# a timeout or proxy error can bill a second generation.
client = OpenAI(
    base_url="http://127.0.0.1:8000/v1",
    api_key="<GFLOW_DAEMON_TOKEN or any string>",
    max_retries=0,
)
image = client.images.generate(prompt="a paper boat", size="1792x1024", n=1)
png_bytes = base64.b64decode(image.data[0].b64_json)

It is the gflow_generate_image tool behind another door: the same profile resolution, rate limit (429 when the bucket is empty) and GFLOW_MCP_NO_SPEND (403 no_spend). Without GFLOW_CLI_PROJECT set on the daemon, every request creates a new Flow project, as the tool does when it is given no project. The account is the daemon's: gflow serve --profile <name> pins it (it sets GFLOW_CLI_PROFILE for the server process, as gflow mcp run --profile does), otherwise the default profile is used.

The route refuses up front, before any quota is spent:

  • A prompt with an @-mention and no pinned project. gflow reads @Name as a Flow character name, and names resolve inside a project, so "a logo for @acme" is 400 param: "prompt" unless the daemon sets GFLOW_CLI_PROJECT; with a pinned project, mentions resolve as they do on the CLI. An @ inside a word (user@example.com) is not a mention.
  • Cloud storage. With GFLOW_CLI_STORAGE_URI set to s3:// or gs://, outputs have no local file to read back, so every request is 500 server_misconfigured naming the setting.
Field Accepted
prompt required, non-empty
model Google Flow image models only: nano2 (default), nano2-lite, nano-pro, image4 and their aliases; anything else, OpenAI's own names included, is 400
n 1–4
size WIDTHxHEIGHT → the nearest of Flow's aspects (1:1, 9:16, 16:9, 4:3, 3:4); an aspect string itself; auto or absent → 1:1
response_format b64_json only (the default here; OpenAI's default url is 400 — gflow does not host files)
stream absent, null, false or 0; true is 400 (streaming is not supported), any other value is 400 (not a boolean)
quality, style, user, background, output_format ignored

An explicit JSON null counts as an absent field. Video is not exposed yet. Flow can return fewer images than n; the response is then still 200 with the images produced (they are billed), and the x-gflow-images-returned header, present on every 200, carries the count, so data stays in OpenAI's schema.

Contract decision — Flow models only. The endpoint is a facade over Google Flow, not an OpenAI emulator: it speaks OpenAI's request and response schema, but the images come from Flow's models. A request naming an OpenAI model (gpt-image-1, dall-e-3, …) is refused with 400 param: "model" and a message listing the accepted Flow model names, rather than silently substituting one. A caller that keeps OpenAI's model name gets an error that says what to send instead, and a generation is never billed under a model it did not name.

Request checks. Every request must be a POST (405 otherwise) with Content-Type: application/json (415) and a body of at most 4 MiB, the MCP SDK's own request-body cap, whether the length is declared or the body is chunked (413). With no token configured, the route also refuses a non-loopback Host (421, DNS rebinding) and a non-loopback Origin (403): a web page in the user's browser can send a text/plain POST without a CORS preflight, and these checks keep it from starting a generation. With a token, a browser cannot attach the Authorization header cross-site.

Errors. gflow's RFC 9457 problem details stay the source of truth; the route translates them at the edge into OpenAI's error object, which the OpenAI SDKs parse into their exception classes:

{"error": {"message": "...", "type": "server_error", "param": null, "code": "generation_timeout",
           "gflow_type": "https://gflow-cli.dev/errors/transport-timeout", "charged": "maybe",
           "retryable": false, "next_action": "reconcile", "task_id": "..."}}

gflow_type, exit_code, charged, retryable, next_action, operation_id, retry_after and task_id are gflow's facts, present when known; OpenAI clients ignore keys they do not know. The mapping (src/gflow_cli/mcp/openai_errors.py):

gflow problem HTTP type code
content-policy 400 invalid_request_error content_policy_violation
bad-parameter, reference-not-found 400 invalid_request_error invalid_value
rate-limit, a 429, status: rate_limited 429 rate_limit_error rate_limit_exceeded
insufficient-credits 429 rate_limit_error insufficient_quota
auth-expired, auth-missing, aisandbox-auth, auth-browser-rejected, any other 401/403 from Flow 502 server_error upstream_auth_failed
waf-rejection, recaptcha-mint 502 server_error upstream_rejected
any other 4xx from Flow 502 server_error upstream_error
no-profile, no-default-profile, configuration, profile-access, profile-engine-downgrade, browser-engine-unavailable, and a bad-parameter about the profile or GFLOW_CLI_PROJECT 500 server_error server_misconfigured
transport-timeout, a task wait=true left pending/processing (task_status) 504 server_error generation_timeout
any 5xx, or no usable status the 5xx, else 500 server_error generation_failed

A 401 or 403 from Flow concerns the daemon's saved Google session, so it becomes a 502 whose message says to run gflow auth renew; passing it through would make an OpenAI client treat its daemon token as invalid. A WAF or reCAPTCHA refusal is Flow rejecting the daemon's request, not an expired session, so its 502 does not suggest a renewal. A 4xx from Flow answers the daemon's request, never the caller's, so only the route's own parameter validation and gflow's bad-parameter produce a 400. A missing profile, an ambiguous default profile or a GFLOW_CLI_PROJECT that belongs to another profile is a fault in the daemon's configuration: a 500 whose message names it, which the caller cannot fix by changing the request. The message is the problem's detail, else its message, else its title, else Generation failed.. The refusals made before the tool runs use the same object and carry charged: "no" (400s also gflow_type bad-parameter): 400 invalid_value with param, 401 authentication_error/invalid_api_key (a missing or wrong daemon token), 403 permission_error (no_spend, invalid_origin), 405 method_not_allowed, 413 request_too_large, 415 unsupported_media_type, 421 invalid_host and 500 server_misconfigured (cloud storage). Two failures come after a generation Flow reported as finished and carry charged: "yes": 502 no_output (no file) and 500 output_unreadable (the file could not be read; the path and the OS error are logged on the server, not returned).

Retries. The OpenAI SDKs retry 429 and 5xx responses twice by default, and a retried generation is a second generation. Every error response therefore carries x-should-retry: false, which the SDKs obey, except the local rate-limit refusal (status: rate_limited): it is answered before anything runs and the bucket refills on its own. That refusal carries retry-after: 20, one refill of the bucket. Any other 429 carries retry-after only when the problem has a retry_after (a Flow quota names its own wait); insufficient_quota and a Flow 429 without one carry none, and neither is retried by the SDK. These requests are counted in telemetry under the client name openai-http, apart from MCP clients' tool calls.

Note: the background FlowWorker queue manager and the REST /api/v1 surface are built as internal foundation but are not yet wired into gflow serve — it currently runs the MCP server (Streamable HTTP or SSE) and the OpenAI-compatible image route above. See the CHANGELOG for the roadmap.

Settings reach the server through its environment, not your shell's .env. An MCP client starts gflow mcp run in a directory of its own choosing, so a .env beside your shell is not read. Put settings such as GFLOW_CLI_BROWSER_PROXY in $GFLOW_CLI_HOME/.env or in the client's env block, and restart the server after changing them.

However you register it, that server then gates your upgrades. Every client above starts a long-lived gflow mcp run — one per session — and on Windows it holds the install open, so a package manager can abort part-way through gflow update and leave the environment broken. Stop the servers first: USAGE § gflow update.


5. Security & Anti-Bot Mitigations

Because the MCP server runs locally, inheriting the host user's permissions and access to their authenticated browser cookies, the following security constraints are enforced:

  1. Profile Pre-flight: Before enqueuing work, each tool resolves and validates the target profile directory (_resolve_and_validate_profile — existence and home-boundary checks). There is no session-validity probe before launching Chromium: expired cookies surface as a typed AuthExpiredError from the generation run itself, with the remediation Run 'gflow auth login' in your local terminal.
  2. Channel Isolation: All internal structlog configurations are forced to write to sys.stderr. The standard output stream (sys.stdout) is globally captured and redirected to sys.stderr for any unexpected prints, preserving the integrity of the stdio JSON-RPC pipe.
  3. Windows Stdio Encoding: During startup, stdio streams are explicitly reconfigured:
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stdin.reconfigure(encoding='utf-8')
    This prevents crashes caused by non-ASCII prompt strings on Windows.
  4. Local Rate-Limiting: Enforces a token-bucket rate limiter with a capacity of 8 tokens and a refill rate of 1 token every 20 seconds (allowing burst filmmaking tasks without timeouts). It limits call rate, not spend. Spend is bounded per call by max_credits on gflow_generate_video (or the server's GFLOW_CLI_MAX_CREDITS default), which refuses before submit when Flow's quote is unreadable or exceeds the cap (exit 45, #1355), and --no-spend (item 6) removes the credit-spending tools altogether. There is no per-session or daily cap (#495).
  5. CLI-MCP Parameter Symmetry: Two CI layers guard the surfaces against drift: tests/mcp/test_cli_parity.py forces an explicit MCP decision (mapped tool or stated exemption) for every CLI leaf command, and tests/mcp/test_server.py::TestCliMcpParameterSymmetry compares CLI Click parameters against registered tool signatures for the two generate tools. Parameter-level comparison does not yet cover the other tools.
  6. No-Spend Mode (#496): gflow mcp run --no-spend (or GFLOW_MCP_NO_SPEND=1, which also covers gflow serve) never registers the credit-spending tools — gflow_generate_image, gflow_generate_video, gflow_upscale_video, gflow_extend_video and gflow_edit_video are absent from tools/list entirely, rather than present-but-refusing. Both are gated because image generation is only empirically free and no-spend is a hard guarantee. Listing, instructions, and other read-only tools remain available, and every other tool stays registered.

6. Troubleshooting a failed tool call

A failing MCP tool call gives an agent much less to go on than a CLI run gives a human: there is no --help to re-read, no stderr to scroll, and the envelope is deliberately narrow (no local paths, no raw exception text — see § Error envelope). This section is the decoder.

Read the envelope in this order: retryable → status → title → detail. Never re-derive retryable from the class name; a raise site can override its class, and one does today.

6.1 First question: what state is this account's Flow in?

Google has moved Flow from labs.google/fx/tools/flow onto flow.google.com, and the move is not one step. Measured 2026-09-14 (3 accounts x 2 entry points x 2 runs): the old labs URL answers HTTP 308 Permanent Redirect on every account tested, yet those same accounts differ in which capabilities work. So the host you are served does not tell you what works — several capability states coexist behind one frontend, they change without notice, and most confusing failures here are really "this account is in a different state than the one the message assumes". Establish the state before diagnosing anything else — it is a $0, read-only check:

gflow auth status          # which host minted the session, and for whom
gflow credits user         # reads the balance from flow.google.com (#795)

History. The credits user column describes builds before the #795 fix, when the balance came from a labs.google token. Since that fix, credits user reads the balance from flow.google.com (#795), so it no longer tells these rows apart. The table is kept for the auth status column.

auth status credits user What you are on Consequence
verified a balance labs session alive Everything documented works
verified fails, "the labs.google session returned no access token" migrated; labs authenticates but never mints the ya29 Bearer credits cannot work. Since v0.73.2 the remediation says so (#795)
verified fails, "credits endpoint returned 401" a token exists but aisandbox-pa rejects it — most often labs' token has lapsed (ACCESS_TOKEN_REFRESH_NEEDED) Until 2026-10-22, usually fixable (labs' session URL is gone now, see the note above): gflow_get_credits(refresh=true) (CLI: --refresh or gflow auth renew) renews it headlessly and reads again. Measured 2026-10-14: 7 of 10 such profiles, all served flow.google.com, recovered. The rest were held at Flow's public /about page, which renewal reports and cannot clear (#795)
"Signed in to Google, but not to the Flow app" forever — migrated; labs no longer mints a Flow session at all Login cannot complete on the released build. Tracked in #791
"Signed in to Google, but not to the Flow app" — or the account has no Flow access at all Same sentence, second cause. The session endpoint answers 200 with an empty user for an abandoned sign-in and for an account with no Google AI Plus/Pro/Ultra (or qualifying Workspace) plan, so auth status cannot tell them apart. Open https://flow.google.com in a browser on that account: a landing on /unavailable means this row. A generation command says so directly — exit 39, FlowAccessUnavailableError

In every migrated row above except the no-Flow-access one, generation over the migrated composer still works — only the aisandbox REST reads fail (credits no longer is one, #795). On the agent-only composer described below that holds for text-to-image and text-to-video only.

A credits failure names its cause. Since #795 the balance is read from flow.google.com's own reply, not from a labs.google token. A sign-in landing is exit 3 (AuthExpiredError, renewable with refresh=true / --refresh). Flow's public /about page, or an app that loads without a readable balance reply, is exit 31 (FlowAppError). An account with no Flow access is exit 39. A balance reply in an unexpected shape is exit 7 (WireFormatError; a zero balance is not one: it reads as credits: 0, #1632), and a profile another gflow process holds is exit 11 (ProfileLockedError). Only exit 3 is about your session. The other codes do not mean "re-run gflow auth login". If the profile has no browser-strategy marker yet, a re-login can make things worse, because a failed first login rolls that marker back. History: before #795, two raise sites in the since-deleted api/credits.py (labs issuing no token, aisandbox-pa rejecting the token) produced every credits failure. Through v0.73.2 the second one carried the class-default SAPISID advice; see the CHANGELOG.

The migrated composer itself also comes in more than one shape. An account whose composer is agent-only — no classic composer at all — is driven through its chat agent for gflow_generate_image (text-to-image) and gflow_generate_video (text-to-video): aspect, count and model are set in Agent settings for the run and restored afterwards, and "Confirm before generating" follows the server's GFLOW_CLI_AGENT_CONFIRM. On Flow's 2026-11-20 build an account with no Agent switch is still reported as selector drift (exit 23) before submit: none has been observed there (#1387). Other forms on that composer (references, image-to-video, instructions, Omni 1.2 Flash, more than one video) return an exit-36-equivalent envelope before anything is clicked (#799), after up to three free page reloads in case Flow serves the classic composer on the next load (#1142). Through v0.73.2 such an account got a generic selector-drift envelope (exit 23); v0.74.0 and v0.75.0 named it with exit 25.

The distinction that matters, because the DOM is identical either way: a pressed Agent toggle (a chip, or since Flow's 2026-11-20 build a switch) means the classic arm exists and gflow turns it off itself (#749). An open agent panel hides the toggle from the page; gflow closes the panel first and looks again (#1374, #1384). Only no toggle at all, with the panel closed, means there is no classic arm to return to: aspect / model / count are Agent-settings defaults rather than per-request controls, and no flag or profile change helps. Generating from the Flow web UI still works.

6.2 Envelope → cause → what to do

What you see Almost always Do this
retryable: true, WAF / rate-limit / timeout Transient Re-run once. If it repeats immediately, stop — it is not transient
selector drift, "the frame picker stayed open … and stayed open after its confirm was clicked" Flow changed the Frames picker again File it with the verbatim detail; the raise sites are textually distinct and the string identifies which one
selector drift, "… and carries no confirm" A cohort whose picker neither commits nor offers a confirm As above — this is a new shape, not #792
"the Start chip did not bind" The search and the click both landed; the chip still did not take the thumbnail Not retryable (retryable: false) — gflow refuses to submit rather than let it go out as text-to-video. File it with the verbatim detail. (Late server-side indexing is a different failure — "lists no asset named …" — and that path already retries internally)
exit-27-equivalent, upload rejected, a dialog opened and no request left the page Flow's one-time "rights to use this image" confirmation Open the project on flow.google.com, upload any image by hand, accept it. gflow will not click it for you: it affirms that you hold the rights. Once per account, then uploads run unattended
exit-39-equivalent, "This Google account cannot reach Flow" The account has no Flow access — it needs a Google AI Plus/Pro/Ultra or qualifying Workspace plan, an age-verified account and a supported region Stop. Do not retry, and do not call gflow_auth_status or suggest a re-login — this is the one envelope where a retry is guaranteed futile, because the editor does not exist for this account. Relay the remediation_hint and its link verbatim; only the human can fix it. Note auth status will separately claim the Flow sign-in was not completed, which is the same sentence with a second cause
exit-36-equivalent The capability is not ported to the migrated host See CONFIGURATION § GFLOW_CLI_FLOW_HOST for exactly what is served there
"Profile is missing its browser-strategy marker" (409, retryable: false, from gflow_auth_status) The profile's browser-strategy marker is gone — typically after a failed first login gflow auth login --browser chrome. It is not a network problem, whatever an older build told you
"Unexpected <Class>; details were logged server-side." (500) A non-gflow exception; the text is masked on purpose Read the server's structured log for mcp.tool.unexpected_error — the traceback is there, not in the envelope

6.3 Getting evidence an agent can actually send

The envelope carries an incident object ({id, capture_status} only — never a path). Resolve it on the machine running the server:

<GFLOW_CLI_HOME>/incidents/<YYYY-MM-DD>/<stamp>-<incident-id>-<rand>/

Layout and what triggers a capture are in DEBUGGING § Automatic incident bundles.

Judge the bundle before you trust it. A bundle whose ui.json has all tag counts at 0 and a blank white screenshot photographed an about:blank page, not your failure — that was a real defect in gflow (fixed in v0.73.2), so a bundle with that signature from an older build carries no information about what went wrong. It is not evidence that the page was blank.

For a run you can reproduce, raise the log level on the server process (GFLOW_CLI_LOG_LEVEL=DEBUG) and capture stderr — MCP writes every structured log line there, never to the stdio pipe.

6.4 Before filing

Include the verbatim detail string, the retryable/status pair, the two cohort commands from §6.1, and gflow --version. Redact account identifiers, cookie and token values, and signed media URLs before pasting anything into an issue. If you have an incident bundle, say so — but do not paste it: it contains prompts and can contain identity-bearing attributes.

Omni 1.2 uses model="omni_1_2_flash" (alias omni-1.2-flash), integer durations 3–15 (at most 10 with an end_frame: above that Flow drops the end frame and bills a start-only clip, so it is refused before queueing, #1178) and optional 360p/720p. CLI, direct MCP and queued MCP preserve the explicit model and duration. Unavailable account durations fail before Send; no model fallback or rounding is performed.