The previous 14 parts covered Google Antigravity (AGY) as a daily CLI tool and a team customization platform. This closing installment tackles two practical engineering questions: first, how to use the official Python SDK when agy -p in shell scripts falls short and you need to embed an Agent directly inside a Python service or automated evaluation suite; second, how to migrate an existing setup of MCP servers, Skills, Subagents, and rules from Claude Code, Cursor, Codex, or Gemini CLI in one pass—with clean, zero-residue rollback at any time.

Every detail below has been verified directly against the official sdk.md reference and the built-in migrate-agent-settings Skill. Let’s get straight into the working patterns and edge cases that actually bite in practice.

1. When to Use the Python SDK Instead of agy -p

Part 2 covered headless mode via agy -p --output-format stream-json. For adding an automated review step in GitHub Actions or wiring text transformations into a shell pipeline, the CLI is plenty—there is no need to pull in a Python dependency.

Once you cross into the scenarios below, however, switching to the google-antigravity Python SDK pays off immediately:

Dimension agy -p --output-format stream-json google-antigravity Python SDK
Typical use cases Shell pipelines, single CI steps, quick scripts Embedded Python services, automated test & eval harnesses
Event consumption Manually parsing JSONL streams from stdout Native async iteration over text tokens, thoughts, and typed tool_calls
Policies & permissions Global config, repository config, and CLI flags Declared directly in code via LocalAgentConfig and CapabilitiesConfig
Interactive reuse Single-turn headless calls or --resume continuations Spin up a custom terminal assistant in two lines with run_interactive_loop

The rule of thumb is simple: use agy -p for external orchestration, and reach for the Python SDK whenever you need tight integration with existing Python application code, pytest assertions, or async logging pipelines.

google-antigravity Python SDK runtime architecture and four-ecosystem migration map from Claude Code, Codex, Cursor, and Gemini CLI

2. Inside the google-antigravity Python SDK

2.1 Installation: Always Use the PyPI Wheel, Never Copy Raw Source

The official SDK lives on GitHub at google-antigravity/antigravity-sdk-python, and installation is a single command:

1
pip install google-antigravity

Hard requirement: Do not copy .py files straight from the source repository into your project as a shortcut. The SDK relies on a compiled runtime binary that is only bundled inside the platform-specific wheel published to PyPI. Always install via pip install google-antigravity to pull the matching runtime binary.

2.2 Core Classes and Read-Only-by-Default Safety

The SDK surface is deliberately minimal, built around three classes: Agent, LocalAgentConfig, and CapabilitiesConfig.

  • Agent(config) is an async context manager invoked via async with Agent(config) as agent:. It owns runtime binary discovery, tool wiring, Hook registration, and default policy loading, cleaning up automatically on exit.
  • LocalAgentConfig(system_instructions=..., capabilities=...) defines system instructions and capability boundaries. It runs read-only by default: omit capabilities and the model can only read; pass capabilities=CapabilitiesConfig() explicitly to unlock write and execution tools such as edit_file and run_command.

Here is a minimal read-write example covering initialization and response token streaming:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asyncio
import sys
from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig


async def main() -> None:
# Read-only by default; pass CapabilitiesConfig() explicitly to enable edit_file / run_command
config = LocalAgentConfig(
system_instructions="You are an expert assistant for codebase navigation.",
capabilities=CapabilitiesConfig(),
)

async with Agent(config) as agent:
# agent.chat() returns a response handle immediately without blocking the event loop
response = await agent.chat("Write a short python script to list files.")

async for token in response:
sys.stdout.write(token)
sys.stdout.flush()
print()


if __name__ == "__main__":
asyncio.run(main())

2.3 Three Async Streams & a CI Audit Script

The response handle returned by await agent.chat(...) exposes three concurrent async streams—a clean fit for production observability and test assertions:

  1. Response token stream: async for token in response: yields the final answer incrementally.
  2. Reasoning stream: async for thought in response.thoughts: streams model reasoning deltas in real time, letting you route them to eval logs or debug panels without polluting user-facing output.
  3. Typed tool-call stream: async for call in response.tool_calls: yields strongly typed tool-call events with direct access to call.name and call.args.

Below is a complete template ready to drop into a CI audit job or evaluation harness. It intentionally omits capabilities to keep the Agent locked in read-only mode, consumes all three streams concurrently with asyncio.gather, persists the trace, and asserts that no write tool was ever called:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import asyncio
import json
import sys
from pathlib import Path
from google.antigravity import Agent, LocalAgentConfig


async def stream_answer(response) -> str:
chunks: list[str] = []
async for token in response:
sys.stdout.write(token)
sys.stdout.flush()
chunks.append(token)
print()
return "".join(chunks)


async def collect_thoughts(response) -> list[str]:
thoughts: list[str] = []
async for thought in response.thoughts:
thoughts.append(str(thought))
return thoughts


async def audit_tool_calls(response) -> list[dict]:
records: list[dict] = []
async for call in response.tool_calls:
print(f"[ToolCall] {call.name} args={call.args}", file=sys.stderr)
records.append({"name": call.name, "args": call.args})
return records


async def run_ci_audit() -> None:
# Omit capabilities to enforce the default read-only mode
config = LocalAgentConfig(
system_instructions=(
"You are a CI security auditor. Read repository configs and list risks; never modify files."
),
)

async with Agent(config) as agent:
response = await agent.chat(
"Inspect the repository's CI configs and scripts, and list high-privilege or credential-leak risks."
)
answer, thoughts, tool_calls = await asyncio.gather(
stream_answer(response),
collect_thoughts(response),
audit_tool_calls(response),
)

# Persist the full audit trace for evaluation and postmortem review
Path("audit-trace.json").write_text(
json.dumps(
{
"answer_length": len(answer),
"thought_chunks": len(thoughts),
"tool_calls": tool_calls,
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)

# Assert directly against typed tool_calls inside your test suite
write_tools = {"edit_file", "write_file", "run_command"}
violated = [c["name"] for c in tool_calls if c["name"] in write_tools]
assert not violated, f"Read-only audit triggered unexpected write tools: {violated}"


if __name__ == "__main__":
asyncio.run(run_ci_audit())

2.4 Launching a Custom Interactive CLI in Two Lines

If you are building an internal CLI assistant for your team—with baked-in system instructions and capability boundaries—rather than a headless batch job, skip hand-rolling an input() loop and reuse the SDK’s built-in run_interactive_loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import asyncio
from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig
from google.antigravity.utils.interactive import run_interactive_loop


async def main() -> None:
config = LocalAgentConfig(
system_instructions="You are this repository's release on-call assistant. Summarize blast radius before any change.",
capabilities=CapabilitiesConfig(),
)
async with Agent(config) as agent:
await run_interactive_loop(agent)


if __name__ == "__main__":
asyncio.run(main())

Running this script gives you a ready-to-use multi-turn terminal session without maintaining conversation state in your own application code.

Python SDK streaming of thoughts and tool_calls alongside a quick reference for reversible plugin migration

3. Frictionless Migration from Claude Code, Cursor, Codex, and Gemini CLI

Many experienced developers hesitate to try AGY because they have already invested months into MCP servers, slash commands, subagents, and rules across Claude Code or Cursor—rebuilding everything from scratch is tedious, and nobody wants a migration script mutating their existing tool setup.

3.1 The Official Strategy: Four-Step Reversible Single-Plugin Migration

AGY ships with a built-in migrate-agent-settings Skill. Trigger it right in chat by asking it to migrate your local Claude Code, Cursor, or Codex settings into Antigravity. Its design follows one strict principle: bundle every migrated asset into a single isolated plugin directory (default recommendation: ~/.gemini/config/plugins/migrated-settings/) without ever modifying a single file belonging to your existing tools.

The workflow enforces four sequential phases:

  1. Discover (read-only inventory): Scans configuration paths across all four ecosystems and diffs them against MCP servers, Skills, plugins, and active rules already loaded under ~/.gemini/config/ (for example, automatically skipping ~/.gemini/GEMINI.md if it is already active so instructions are never injected twice).
  2. Confirm (review the plan): Summarizes item counts and names grouped by source, lists what will be skipped, and never prints plaintext tokens or API keys in chat. Nothing is written to disk until you explicitly approve. If it detects workspace-scoped .mcp.json or .cursor/rules/ files, it flags upfront that placing them into a global plugin will make them active across all workspaces, letting you decide whether to include them.
  3. Write (generate a single plugin): Outputs plugin.json (keeping only the four valid fields: name, displayName, version, description), mcp_config.json, skills/, agents/, and rules/.
  4. Hand back (validate and deliver): Re-reads plugin.json and mcp_config.json to confirm valid JSON, then returns the plugin page link customization://migrated-settings.

The biggest win here is complete reversibility: to run an A/B comparison or roll back cleanly, simply toggle the plugin off on the plugin page or delete ~/.gemini/config/plugins/migrated-settings/. Your environment returns to a clean slate in one second, and your original Claude Code or Cursor setup stays completely untouched.

3.2 Four-Ecosystem Configuration Path Map

If you prefer to audit or migrate manually, the table below lists every source path scanned by migrate-agent-settings:

Source Tool MCP Config Paths Skills / Commands / Subagents Rules / Instruction Files
Claude Code ~/.claude.json (top-level mcpServers); <workspace>/.mcp.json ~/.claude/skills/*/SKILL.md; ~/.claude/commands/*.md; ~/.claude/agents/*.md ~/.claude/CLAUDE.md
Codex [mcp_servers.<name>] in ~/.codex/config.toml ~/.codex/skills/*/SKILL.md; ~/.codex/prompts/*.md ~/.codex/AGENTS.md
Cursor ~/.cursor/mcp.json; <workspace>/.cursor/mcp.json — <workspace>/.cursor/rules/*.mdc
Gemini CLI mcpServers in ~/.gemini/settings.json ~/.gemini/commands/**/*.toml ~/.gemini/GEMINI.md

3.3 Five Conversion Rules That Trip Up Most Migrations

Whether you rely on the migration Skill or convert files by hand, these five contract differences determine whether your migrated setup actually runs on the first try:

1. Claude Code Subagent Tool Remapping & Required Frontmatter

When moving ~/.claude/agents/*.md into agents/<name>.md, the Markdown body stays intact as the system prompt, but the YAML frontmatter needs four explicit adjustments:

  • Declare the role explicitly: Add subagent: true and mainAgent: false so it is never registered as a top-level main agent.
  • Declare tools explicitly: Omitting tools in AGY grants only a minimal read-only default set. If the original Claude agent omitted tools (meaning full access), populate it explicitly as [read_file, edit_file, write_file, run_command, manage_task, search_web].
  • Remap tool names: Map Read, Glob, and Grep to read_file; Edit and MultiEdit to edit_file; Write to write_file; Bash to run_command and manage_task; WebSearch and WebFetch to search_web. Drop any permission with no AGY equivalent and record the omission.
  • Strip proprietary fields and avoid name collisions: Remove model and color. If the agent name collides with a built-in or existing agent (self, browser, research, deepagent, review-agent), prefix it with its source—for example, claude-reviewer.

2. Converting Slash Commands & Prompts to Skills (and the Missing-Frontmatter Trap)

  • ~/.claude/commands/*.md, ~/.codex/prompts/*.md, and Gemini CLI’s ~/.gemini/commands/**/*.toml all convert into skills/<name>/SKILL.md. For nested Gemini CLI paths, join segments with - (e.g., git/commit.toml becomes git-commit), using the command body (or the TOML prompt field) as the Skill content.
  • Replace argument placeholders like $ARGUMENTS, $1, and {{args}} with natural-language instructions (for example, “apply the steps above to the user’s current request”).
  • Common pitfall: Claude Code tolerates a SKILL.md without frontmatter or without a name field, whereas AGY silently drops such files. Every migrated SKILL.md must include valid YAML frontmatter where name matches its parent directory name verbatim and description is non-empty. Copy sibling scripts/ and references/ directories over as-is.

3. Cursor .mdc to AGY Rules: Trigger Precedence & Glob Formatting

When converting <workspace>/.cursor/rules/*.mdc into standalone rules/<name>.md files, map triggers using this exact precedence order:

  1. alwaysApply: true → trigger: always_on
  2. Non-empty globs → trigger: glob
  3. Non-empty description → trigger: model_decision
  4. Both empty → trigger: manual

Handle two hard constraints upfront: AGY expects globs to be a single comma-separated string matched against absolute paths and filenames. Flatten YAML lists, expand brace expressions like **/*.{ts,tsx} into **/*.ts, **/*.tsx, and prepend **/ to relative paths (src/**/*.ts → **/src/**/*.ts). Individual rule files are also capped at 24 KB—do not silently truncate oversized rules; split them into path-scoped rules and strip legacy tool-specific wording such as “use the Bash tool”.

4. MCP Environment Variables & the Counterintuitive variables Behavior

This is the single most common source of broken MCP servers after migration: mcp_config.json inside an AGY plugin does not automatically expand OS environment variables.

  • Only command, args, env, cwd, url, headers, disabled, and variables are recognized (type, timeout, trust, and alwaysAllow are ignored; Gemini CLI’s httpUrl and Codex’s url both map to url; Codex’s http_headers maps to headers, while env_http_headers and bearer_token_env_var convert into ${X} entries inside headers paired with a variables declaration).
  • Delete pass-through env entries: If a stdio server’s env block contains "GITHUB_TOKEN": "${GITHUB_TOKEN}", "GITHUB_TOKEN": "$GITHUB_TOKEN", or Cursor’s "${env:GITHUB_TOKEN}", remove that line during migration. Without it, the child process automatically inherits the matching OS environment variable; leaving it in without declaring variables passes the literal string ${GITHUB_TOKEN} instead.
  • Declare variables for real interpolation: For placeholders that actually need substitution—such as "Authorization": "Bearer ${API_KEY}" on a remote MCP server—normalize $X, ${env:X}, and ${X:-default} to ${X} (documenting defaults in description), and add a variables array (name, title, description) on that server. Note one critical quirk: whenever any server in a plugin declares variables, the plugin starts disabled by default—you must fill in the values on the plugin page and enable it manually.
  • Expand every path to an absolute path upfront: cwd does not support variable substitution, and relative paths resolve against the plugin directory itself. Expand ${workspaceFolder}, $HOME, ~, relative paths, and ${CLAUDE_PLUGIN_ROOT} to concrete absolute paths before writing. If a server name conflicts with an existing AGY entry, add a source prefix (such as claude-github).

5. Four Asset Categories That Should Not Be Auto-Migrated

Do not try to force-convert the four categories below with scripts—route them directly to the right path instead:

Non-Auto-Migrated Asset Why Recommended Approach
hooks and permissions in Claude Code settings.json Different tool names (Bash/Edit) and protojson/rule syntax Rewrite manually following Part 7 (Hooks) and Part 14 (Permissions Engine)
~/.claude/plugins/ and ~/.gemini/extensions/ Complete plugin/extension bundles rather than loose user configs Run agy plugin import claude or agy plugin import gemini directly
Personal user rules in Cursor’s internal client database Stored in the app’s local DB rather than filesystem config files Copy the rule text from Cursor’s settings UI into ~/.gemini/config/rules/
Legacy SSE MCP servers ("type": "sse" or /sse) AGY remote MCP targets Streamable HTTP Point to the /mcp endpoint if available, or bridge via stdio using npx -y mcp-remote <url>

4. A Minimal Loop You Can Ship Today

That wraps up all 15 parts of the field guide. You do not need to adopt every feature on day one—pick the smallest closed loop that fixes your highest-friction bottleneck right now:

  • Switching your personal daily driver: Run migrate-agent-settings once to pull your existing MCP servers and Skills into the reversible migrated-settings plugin, set up ~/.gemini/config/AGENTS.md alongside /plan and your preferred keybindings, and start shipping the same day.
  • Standardizing a team repository: Commit a concise root AGENTS.md, split path-scoped .agents/rules/*.md files (staying under 24 KB each), and lock down sensitive files and destructive commands with hooks.json and permission deny rules so every teammate gets the baseline on git pull.
  • Engineering automation & evaluations: Wire simple CI checks with agy -p --output-format stream-json first. Once you need to embed an Agent inside a Python test suite, capture reasoning streams, and assert strictly against tool_calls, switch to the google-antigravity Python SDK—starting from default read-only mode and opening CapabilitiesConfig only when required.

Series Navigation