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.
Generate & Validate Multi-Client MCP Config
One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.
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):
Key Advantages of Native Session Binding
- ▸Automatic Schema Sanitization: The SDK strips Draft-07 properties that previously triggered
400 Invalid argumenterrors on the Gemini API gateway. - ▸Automatic Tool Execution Loop: By passing
sessiondirectly totools=[session],client.aio.models.generate_contentresolves multi-step tool chains automatically unless automatic function calling is explicitly disabled. - ▸First-Class Async Lifecycle: Uses Python
AsyncExitStackto manage multiple concurrent MCP servers without orphaned child processes.
Prerequisites & Runtime Matrix
| Component | Minimum Version | Recommended Version | Verification Command |
|---|---|---|---|
| Python | 3.11 | 3.12.7 | python3 --version |
| Google GenAI SDK | 1.16.0 (first release with MCP support) | 1.16.0+ | pip show google-genai |
| MCP Python SDK | 1.3.0 | 1.6.0+ | pip show mcp |
| Node.js / npx | v20.18.0 | v22.12.0 LTS | node -v |
| Google Antigravity | MCP-capable release | Latest | Native IDE MCP host |
Install the official Python packages:
pip install google-genai mcpExport your Gemini API key from Google AI Studio:
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:
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:
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:
{
"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)
[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_execdoes not resolve.cmdbatch shims on Windows unless explicitly specified. - ▸Fix: Always resolve
npx.cmdon Windows ("npx.cmd" if sys.platform == "win32" else "npx") when constructingStdioServerParameters.
2. McpError: Connection closed During Startup
- ▸Root Cause: The target MCP server wrote non-JSON startup text to
stdoutor 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
npxoruvxinside the sameAsyncExitStack, 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 insideStdioServerParameters. 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:
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
- ▸API Key & Secret Separation: Keep
GEMINI_API_KEYisolated from the environment dictionary passed into child MCP servers. By default,StdioServerParametersinherits a fixed allow-list of variables — on non-Windows:HOME,LOGNAME,PATH,SHELL,TERM,USER(a larger Windows-specific list on Windows) — and merges anyenvyou supply (SDK source (opens in a new tab)); explicitly enumerate only the secrets required by each server (for example,DATABASE_URLfor PostgreSQL andGITHUB_PERSONAL_ACCESS_TOKENfor GitHub). - ▸Read-Only Database Enforcement: Never pass superuser credentials into a Gemini-connected database server. Provision a dedicated
mcp_readerrole restricted toSELECTqueries withstatement_timeoutset to 8 seconds so unindexed analytical queries cannot lock production tables. - ▸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.
- ▸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
- ▸Google GenAI Python SDK Repository (
googleapis/python-genai) (opens in a new tab) - ▸Google Gemini API Function Calling & MCP Docs (opens in a new tab)
- ▸Gemini model list and release notes (opens in a new tab)
- ▸Official Model Context Protocol Python SDK (
modelcontextprotocol/python-sdk) (opens in a new tab)
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)).
Build your full agent toolstack in the Visual Generator
Combine MCP servers with databases, search APIs, and memory graphs in a single configuration file.
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.
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.
Related Guides
Gemini 4 MCP: Deferred Tool Retrieval
Connect Gemini 4 to remote MCP servers with tool_search and defer_loading on the Interactions API. Covers Streamable HTTP, signatures, and exact error messages.
Getting StartedConfigure MCP Servers in OpenAI Codex CLI
Complete 2026 config.toml setup, CLI commands, and troubleshooting for connecting MCP servers to OpenAI Codex CLI.
Getting StartedMCP Security Best Practices: Sandboxing, Auth & Zero-Trust for Production
MCP security: stdin/stdout isolation, OAuth 2.1 for remote endpoints, path traversal prevention, SQL injection defense, rate limiting, and audit logging. Includes TypeScript implementation patterns.