Getting Started·
intermediate
·12 min read·Nov 19, 2026·Updated Nov 24, 2026
·Independent maintainer·Verification Charter

Gemini 3.8 Flash & GenAI SDK Native MCP Setup Guide

Connect Gemini 3.8 Flash to MCP servers with native google-genai SDK ClientSession binding, human approval gates, and Antigravity MCP configuration.

MCPGeminiGoogleAntigravityCodexClaudePythonsetup
Interactive Tool
1-Click Export

Generate & Validate Multi-Client MCP Config

One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.

Open in Generator

Gemini 3.8 Flash & Google GenAI SDK Native MCP Client Guide

Early integrations between Google Gemini models and the Model Context Protocol (MCP) required writing custom subprocess wrappers that manually parsed tools/list JSON Schema payloads into types.FunctionDeclaration objects—an approach documented in our archived Gemini 2.x manual bridge guide.

Native MCP support was added in the official google-genai Python SDK v1.16.0 (see the 1.16.0 changelog entry (opens in a new tab)), and is also available in Google Antigravity IDE. Manual schema translation and hand-rolled JSON-RPC stdin/stdout loops are no longer necessary: google-genai accepts an active MCP ClientSession inside GenerateContentConfig.tools, discovers tools automatically, filters the tool's JSON Schema down to fields Gemini supports, and executes multi-turn tool calls within a single async context. The filter keeps additionalProperties, anyOf, oneOf, $defs and $ref and drops unsupported keys such as $schema — see _filter_to_supported_schema in the SDK (opens in a new tab).

Google now recommends the Interactions API for new applications. The native ClientSession binding below still describes the generateContent path; for remote servers with deferred tool loading on Gemini 4, see our Gemini 4 MCP tool retrieval guide.


Native Architecture: Zero-Boilerplate Session Binding

Instead of manually serializing tools/call frames and intercepting response.function_calls, the Google GenAI SDK integrates directly with the official mcp Python package (ClientSession):

diagram

Key Advantages of Native Session Binding

  1. ▸Automatic Schema Sanitization: The SDK strips Draft-07 properties that previously triggered 400 Invalid argument errors on the Gemini API gateway.
  2. ▸Automatic Tool Execution Loop: By passing session directly to tools=[session], client.aio.models.generate_content resolves multi-step tool chains automatically unless automatic function calling is explicitly disabled.
  3. ▸First-Class Async Lifecycle: Uses Python AsyncExitStack to manage multiple concurrent MCP servers without orphaned child processes.

Prerequisites & Runtime Matrix

ComponentMinimum VersionRecommended VersionVerification Command
Python3.113.12.7python3 --version
Google GenAI SDK1.16.0 (first release with MCP support)1.16.0+pip show google-genai
MCP Python SDK1.3.01.6.0+pip show mcp
Node.js / npxv20.18.0v22.12.0 LTSnode -v
Google AntigravityMCP-capable releaseLatestNative IDE MCP host

Install the official Python packages:

bash
pip install google-genai mcp

Export your Gemini API key from Google AI Studio:

bash
export GEMINI_API_KEY="AIzaSyYourVerifiedGeminiKey"

1. Native Python SDK Implementation (Single & Multi-Server)

The following production script connects Gemini 3.8 Flash (the model Google says gemini-2.5-pro requests will route to from December 1, 2026; gemini-2.5-pro is deprecated, not yet shut down — see the Gemini API changelog (opens in a new tab)) to the PostgreSQL and Filesystem MCP servers simultaneously using AsyncExitStack and native session binding. The pinned @modelcontextprotocol/server-postgres@0.6.2 reproduces the legacy example; npm flags that package as "Archived and unmaintained; no security guarantees," so choose a maintained server for new deployments:

python
import asyncio
import os
import sys
from contextlib import AsyncExitStack
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def run_gemini_mcp_agent(prompt: str) -> None:
    # Initialize the official Google GenAI client (reads GEMINI_API_KEY from env)
    client = genai.Client()
    npx_bin = "npx.cmd" if sys.platform == "win32" else "npx"

    postgres_params = StdioServerParameters(
        command=npx_bin,
        args=[
            "-y",
            "@modelcontextprotocol/server-postgres@0.6.2",
            os.environ.get("DATABASE_URL", "postgresql://mcp_reader:secret@localhost:5432/analytics"),
        ],
    )

    filesystem_params = StdioServerParameters(
        command=npx_bin,
        args=[
            "-y",
            "@modelcontextprotocol/server-filesystem@2026.8.31",
            os.path.abspath("./workspace"),
        ],
    )

    async with AsyncExitStack() as stack:
        # 1. Spawn and initialize both MCP servers
        pg_read, pg_write = await stack.enter_async_context(stdio_client(postgres_params))
        pg_session = await stack.enter_async_context(ClientSession(pg_read, pg_write))
        await pg_session.initialize()

        fs_read, fs_write = await stack.enter_async_context(stdio_client(filesystem_params))
        fs_session = await stack.enter_async_context(ClientSession(fs_read, fs_write))
        await fs_session.initialize()

        # 2. Pass the active MCP ClientSession instances directly into tools=[]
        response = await client.aio.models.generate_content(
            model="gemini-3.8-flash",
            contents=prompt,
            config=types.GenerateContentConfig(
                tools=[pg_session, fs_session],
            ),
        )

        print(response.text)

if __name__ == "__main__":
    asyncio.run(
        run_gemini_mcp_agent(
            "Inspect the public schema tables in PostgreSQL and write a markdown summary to ./workspace/schema-report.md"
        )
    )

2. Enforcing Human-in-the-Loop Approval (Disabling Auto-Execution)

In production environments where an MCP server exposes state-mutating tools, you can disable automatic tool invocation so your application inspects and approves every tool call before execution:

python
config = types.GenerateContentConfig(
    tools=[pg_session],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(
        disable=True
    ),
)

response = await client.aio.models.generate_content(
    model="gemini-3.8-flash",
    contents="Run a diagnostic count on the active_users table.",
    config=config,
)

for call in response.function_calls or []:
    print(f"[Approval Gate] Model requested tool: {call.name} with args: {call.args}")
    result = await pg_session.call_tool(call.name, arguments= dict(call.args))
    print(f"[Tool Result]: {result.content}")

3. Multi-Host IDE Configuration (Google Antigravity, Claude & Codex)

Google Antigravity IDE and JSON-based hosts

Antigravity documents a standardized mcp_config.json with a mcpServers map for the App, CLI and IDE; servers are managed under Customizations → MCP Servers, and the exact config path is shown in the UI via Copy Config File Path. The Antigravity SDK reads a workspace .agents/mcp_config.json (Antigravity MCP docs (opens in a new tab)). Antigravity bundles the Gemini API skills plugin (a google-gemini project, not an officially supported Google product), which can also be installed with agy plugin install https://github.com/google-gemini/gemini-skills; the Gemini Docs MCP server is a separate plugin (for example, Google Developer Knowledge). The same mcpServers JSON shape below applies to Claude Desktop and Cursor, whose config paths are covered in our multi-client configuration guide:

json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres@0.6.2",
        "postgresql://mcp_reader:secret@localhost:5432/analytics"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github@2025.4.8"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "github_pat_your_scoped_token"
      }
    }
  }
}

OpenAI Codex CLI (~/.codex/config.toml)

toml
[mcp_servers.postgres]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-postgres@0.6.2", "postgresql://mcp_reader:secret@localhost:5432/analytics"]

Troubleshooting Common Integration Errors

1. FileNotFoundError: [Errno 2] No such file or directory: 'npx' on Windows

  • ▸Root Cause: Python's asyncio.create_subprocess_exec does not resolve .cmd batch shims on Windows unless explicitly specified.
  • ▸Fix: Always resolve npx.cmd on Windows ("npx.cmd" if sys.platform == "win32" else "npx") when constructing StdioServerParameters.

2. McpError: Connection closed During Startup

  • ▸Root Cause: The target MCP server wrote non-JSON startup text to stdout or failed to authenticate with its upstream database.
  • ▸Fix: Run the exact command in your terminal first and verify that all diagnostic logs route strictly to stderr.

3. Timeout Exceeded on Multi-Server Initialization

  • ▸Root Cause: When launching multiple Node.js or Python servers via npx or uvx inside the same AsyncExitStack, cold package downloads can exceed the default initialization timeout on constrained CI runners or fresh containers.
  • ▸Fix: Pre-cache packages during container image build (npm install -g @modelcontextprotocol/server-postgres@0.6.2) or pass explicit local binary paths inside StdioServerParameters. Separate fast local servers from remote Streamable HTTP servers so a transient remote outage does not stall local tool registration.

Connecting Gemini to Remote Streamable HTTP MCP Servers

While stdio_client handles local workstation tools, production backend services and serverless cloud workers often expose MCP over unified Streamable HTTP (/mcp). In recent mcp 1.x releases the Python SDK exposes both streamablehttp_client (deprecated, accepts headers=) and streamable_http_client; in mcp 2.x only streamable_http_client remains and headers are configured by passing an http_client (SDK source (opens in a new tab)). Both attach to the same ClientSession interface accepted by google-genai; pin your SDK version accordingly:

python
from mcp.client.streamable_http import streamablehttp_client  # mcp 1.x; 2.x uses streamable_http_client

async def connect_remote_gemini_mcp(prompt: str) -> None:
    client = genai.Client()
    headers = {"Authorization": f"Bearer {os.environ['MCP_GATEWAY_TOKEN']}"}

    async with streamablehttp_client("https://mcp.internal.example.com/mcp", headers=headers) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            response = await client.aio.models.generate_content(
                model="gemini-3.8-flash",
                contents=prompt,
                config=types.GenerateContentConfig(tools=[session]),
            )
            print(response.text)

Production Security Guardrails for Gemini Tool Execution

  1. ▸API Key & Secret Separation: Keep GEMINI_API_KEY isolated from the environment dictionary passed into child MCP servers. By default, StdioServerParameters inherits a fixed allow-list of variables — on non-Windows: HOME, LOGNAME, PATH, SHELL, TERM, USER (a larger Windows-specific list on Windows) — and merges any env you supply (SDK source (opens in a new tab)); explicitly enumerate only the secrets required by each server (for example, DATABASE_URL for PostgreSQL and GITHUB_PERSONAL_ACCESS_TOKEN for GitHub).
  2. ▸Read-Only Database Enforcement: Never pass superuser credentials into a Gemini-connected database server. Provision a dedicated mcp_reader role restricted to SELECT queries with statement_timeout set to 8 seconds so unindexed analytical queries cannot lock production tables.
  3. ▸Context Window & Payload Budgeting: Although Gemini 2.5 Pro and 3.0 offer million-token context windows, injecting raw unprojected JSON tables or 50,000-line log files degrades tool-calling accuracy and inflates inference latency. Cap returned rows and file reads on the MCP server side before responses return to the GenAI client.
  4. ▸Explicit Approval for Mutating Tools: Disable automatic function calling (AutomaticFunctionCallingConfig(disable=True)) whenever any connected MCP server exposes destructive operations such as file writes, git commits, or outbound API mutations.

External References

Model identifiers and API guidance cross-checked against Google's published documentation on 2026-11-20. gemini-3.8-flash is the destination for deprecated gemini-2.5-pro requests from 2026-12-01; sampling parameters temperature, top_p, and top_k are deprecated on current models (changelog (opens in a new tab)).

Ready to Deploy?

Build your full agent toolstack in the Visual Generator

Combine MCP servers with databases, search APIs, and memory graphs in a single configuration file.

Customize in Generator
Developer Verification & Feedback
0 reports

Did this setup guide work with your AI host?

Help test this configuration across Claude, Cursor, and Codex CLI. Be the first to report:

Gemini 3.8 Flash & GenAI SDK Native MCP Setup Guide FAQ

Do I still need a custom JSON Schema sanitizer when connecting Gemini to MCP?

No, when using 'google-genai' v1.12.0+ with native MCP 'ClientSession' binding ('tools=[session]'), the SDK automatically converts MCP 'tools/list' schemas and strips unsupported Draft-07 keywords like '$schema' and '$id' that previously triggered HTTP 400 errors.

How do I require human approval before Gemini executes an MCP tool?

Pass 'automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)' inside 'GenerateContentConfig'. The API will return pending 'response.function_calls' so your application can inspect arguments, prompt the operator, and manually call 'await session.call_tool(...)'.

How do I configure MCP servers in Google Antigravity IDE?

Antigravity documents a standardized 'mcp_config.json' with an 'mcpServers' map. Manage servers under Customizations then MCP Servers, and use 'Copy Config File Path' in the UI to find the exact file instead of assuming a fixed location; the Antigravity SDK reads a workspace '.agents/mcp_config.json'. The Gemini API skills plugin is a separate 'google-gemini' project (install with 'agy plugin install https://github.com/google-gemini/gemini-skills'), and the Gemini Docs MCP server is a separate plugin.

RT✓

Written by Rad Tome

Independent maintainer, MCP Codex

Specializing in Model Context Protocol (MCP) integrations, autonomous AI agent orchestration, and distributed developer toolchains. Researches and benchmarks production MCP client-server architectures across OpenAI Codex, Claude, and Cursor.

Editorial Integrity: Package names verified via npm registry API. Repositories verified via GitHub REST API.
Verification Charter →

Related Guides