Gemini 2.5 and 3.0 MCP Client Setup Guide
Connect Google Gemini 2.5 and 3.0 models to MCP servers via Python SDK and Antigravity. Full schema translation, stdio bridge, and config. Verified working.
Generate & Validate Multi-Client MCP Config
One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.
Gemini 2.5 and 3.0 MCP Client Setup Guide
Google Gemini 2.5 Flash, 2.5 Pro, and Gemini 3.0 models process external tools via the Google GenAI SDK (google-genai) using native FunctionDeclaration objects. By contrast, the Model Context Protocol (MCP) exposes tools via JSON-RPC 2.0 messages over standard input/output (stdio) or Server-Sent Events (sse). Bridging these interfaces enables Gemini models to query local databases, execute terminal scripts, and access local developer environments within million-token context windows.
The bridge architecture detailed below translates MCP tools/list declarations into Gemini function definitions, intercepts model tool calls, and relays execution results back into multi-turn conversation loops with zero hallucinations.
Problem Statement and Architecture
When invoking external tools in Gemini applications, the model does not communicate directly with operating system processes. Instead, the application layer sends a list of declared functions in the generation request payload. When Gemini decides to invoke a tool, it suspends text generation and emits a structured functionCall event containing the target function name and serialized argument dictionary.
MCP servers, by contrast, run as isolated sub-processes or remote network daemons. They communicate strictly via JSON-RPC 2.0 framing where standard input and output streams are reserved exclusively for formatted JSON strings. If a server process writes unformatted debug strings or logger warnings to stdout, the JSON-RPC parser fails.
The Gemini MCP Bridge acts as a bidirectional translation layer:
+-----------------------------------------------------------------------+
| DEVELOPER / GOOGLE ANTIGRAVITY IDE |
| User Prompt: "Analyze active PostgreSQL tables" |
+-----------------------------------+-+---------------------------------+
|
v
+-----------------------------------------------------------------------+
| GEMINI MCP CLIENT RUNTIME |
| |
| 1. Spawns MCP server sub-processes via stdio pipes |
| 2. Sends JSON-RPC "initialize" and requests "tools/list" |
| 3. Translates JSON Schema into Gemini FunctionDeclaration objects |
| 4. Submits prompt + FunctionDeclarations to Gemini 2.5/3.0 API |
+-------------------+-------------------------------+-------------------+
| ^
Function Schema| | Function Call Event
v |
+-----------------------------------+ +-------------------------------+
| GOOGLE GEMINI FOUNDATION API | | UPSTREAM MCP SERVER |
| (Gemini 2.5 Pro / Flash) | | (@modelcontextprotocol/ |
| | | server-postgres) |
| - Ingests user prompt & schemas | | |
| - Generates functionCall: | | - Receives tools/call frame |
| "query(sql='SELECT...') | | - Runs safe SQL in container |
+-----------------------------------+ | - Emits JSON-RPC result |
+-------------------------------+The runtime handles four sequential responsibilities:
- ▸Process Lifecycle Management: Booting the upstream MCP server binary with isolated environment variables and non-blocking stdio descriptors.
- ▸Schema Ingestion: Fetching tool metadata from
tools/listand restructuring JSON Schema draft-07 types into Gemini-compatible OpenAPI schemas. - ▸Execution Relay: Converting Gemini
functionCallparameters into standardtools/callJSON-RPC frames. - ▸Context Injection: Packaging the MCP tool output into a
types.Part.from_function_responsestructure and returning it to Gemini to complete response generation.
Prerequisites and Environment Matrix
Ensure your development workstation meets the required runtime prerequisites before installing the Gemini MCP toolchain:
| Dependency | Minimum Version | Recommended Version | Description |
|---|---|---|---|
| Python | 3.10.0 | 3.12.3 | Modern asynchronous event loop support |
| Google GenAI SDK | 1.0.0 | 1.2.0 | Official google-genai Python library |
| Node.js | v20.18.0 LTS | v22.12.0 LTS | Runtime for official TypeScript MCP servers |
| npm | 10.8.2 | 10.9.0 | Package manager for @modelcontextprotocol binaries |
| Google Antigravity | 2.0.0 | 2.2.4 | Google agentic coding environment |
You must also obtain a valid Gemini API key from Google AI Studio and export it into your operating system shell:
export GEMINI_API_KEY="AIzaSyYourGeminiApiKeyHere"On Windows PowerShell:
$env:GEMINI_API_KEY="AIzaSyYourGeminiApiKeyHere"Multi-Host Configuration Snippets
To ensure consistent server access across all developer tools in your workflow, configure your upstream servers identically across Antigravity IDE, Claude Desktop, Cursor, and OpenAI Codex CLI.
Google Antigravity IDE Configuration
In Google Antigravity IDE, MCP servers are declared in ~/.gemini/antigravity-ide/mcp_config.json:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres@0.6.2",
"postgresql://postgres_user:secret_password@/production_db"
]
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem@2026.8.31",
"/Users/developer/projects/app"
]
}
}
}Claude Desktop Configuration
Claude Desktop reads from claude_desktop_config.json located in ~/Library/Application Support/Claude/ (macOS) or %APPDATA%\Claude\ (Windows):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres@0.6.2",
"postgresql://postgres_user:secret_password@/production_db"
]
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem@2026.8.31",
"/Users/developer/projects/app"
]
}
}
}Cursor IDE Configuration
In Cursor's .cursor/mcp.json settings:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres@0.6.2",
"postgresql://postgres_user:secret_password@/production_db"
]
}
}
}OpenAI Codex CLI Configuration
In ~/.codex/config.toml:
# ~/.codex/config.toml
[mcp_servers.postgres]
command = "npx"
args = [
"-y",
"@modelcontextprotocol/server-postgres@0.6.2",
"postgresql://postgres_user:secret_password@/production_db"
]
[mcp_servers.filesystem]
command = "npx"
args = [
"-y",
"@modelcontextprotocol/server-filesystem@2026.8.31",
"/Users/developer/projects/app"
]Step-by-Step Tool Discovery and Invocation
Here is a complete, production-ready Python client connecting Google Gemini 2.5 Pro to any stdio-based MCP server using the official google-genai SDK:
# gemini_mcp_runner.py
import asyncio
import json
import os
import sys
from google import genai
from google.genai import types
class GeminiMCPBridge:
def __init__(self, command: str, args: list[str]):
self.command = command
self.args = args
self.client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
self.process = None
self._request_id = 0
async def connect(self):
"""Spawn the MCP server process and establish stdio communication."""
self.process = await asyncio.create_subprocess_exec(
self.command,
*self.args,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=sys.stderr
)
# 1. Initialize MCP handshake
init_res = await self._send_rpc("initialize", {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "Gemini-MCP-Bridge", "version": "1.0.0"}
})
# 2. Acknowledge initialization
await self._send_notification("notifications/initialized", {})
return init_res
async def list_tools_for_gemini(self) -> list[types.FunctionDeclaration]:
"""Fetch MCP tools and convert to Gemini FunctionDeclaration format."""
rpc_response = await self._send_rpc("tools/list", {})
mcp_tools = rpc_response.get("tools", [])
declarations = []
for tool in mcp_tools:
# Map JSON Schema types to OpenAPI schemas compatible with Gemini
schema = tool.get("inputSchema", {})
declarations.append(
types.FunctionDeclaration(
name=tool["name"],
description=tool.get("description", ""),
parameters=schema
)
)
return declarations
async def execute_tool(self, tool_name: str, arguments: dict) -> dict:
"""Forward Gemini tool execution request to MCP tools/call."""
return await self._send_rpc("tools/call", {
"name": tool_name,
"arguments": arguments
})
async def _send_rpc(self, method: str, params: dict) -> dict:
self._request_id += 1
payload = {
"jsonrpc": "2.0",
"id": self._request_id,
"method": method,
"params": params
}
encoded = json.dumps(payload) + "\n"
self.process.stdin.write(encoded.encode("utf-8"))
await self.process.stdin.drain()
raw_line = await self.process.stdout.readline()
if not raw_line:
raise RuntimeError("MCP server closed stdout stream unexpectedly.")
response = json.loads(raw_line.decode("utf-8"))
if "error" in response:
raise RuntimeError(f"MCP RPC Error: {response['error']}")
return response.get("result", {})
async def _send_notification(self, method: str, params: dict):
payload = {"jsonrpc": "2.0", "method": method, "params": params}
encoded = json.dumps(payload) + "\n"
self.process.stdin.write(encoded.encode("utf-8"))
await self.process.stdin.drain()
async def run_prompt(self, prompt: str):
"""Execute a prompt with Gemini, handling tool calls iteratively."""
tools = await self.list_tools_for_gemini()
gemini_tool_config = types.Tool(function_declarations=tools)
chat = self.client.chats.create(
model="gemini-2.5-pro",
config=types.GenerateContentConfig(tools=[gemini_tool_config])
)
response = chat.send_message(prompt)
# Check if Gemini requested a function call
if response.function_calls:
for call in response.function_calls:
print(f"[*] Gemini invoking tool: {call.name} with args {call.args}")
tool_result = await self.execute_tool(call.name, call.args)
# Send tool execution result back to Gemini
followup = chat.send_message(
types.Part.from_function_response(
name=call.name,
response={"result": tool_result}
)
)
print("[*] Gemini Response:\n", followup.text)
else:
print("[*] Gemini Response:\n", response.text)To run a verified query against your PostgreSQL MCP server:
async def main():
bridge = GeminiMCPBridge(
command="npx",
args=["-y", "@modelcontextprotocol/server-postgres@0.6.2", "postgresql://user:pass@/app"]
)
await bridge.connect()
await bridge.run_prompt("List all table names and row counts in the public schema.")
if __name__ == "__main__":
asyncio.run(main())Common Errors and Production Troubleshooting
When integrating Gemini with MCP servers over standard input and output streams, developers commonly encounter three specific errors.
1. Error Code 400: Invalid Schema Format for Function Calling
- ▸Symptom: The Gemini API throws an exception during
client.chats.create():codegoogle.genai.errors.APIError: 400 Invalid argument: 'tools[0].function_declarations[0].parameters' contains unsupported JSON schema keyword '$schema' - ▸Root Cause: MCP servers frequently generate JSON schemas containing draft-07 metadata (
$schema,definitions, oranyOf) that the Gemini function calling engine rejects. - ▸Fix: Sanitize the schema dictionary before instantiating
types.FunctionDeclaration. Remove$schema,$id, and resolve$refpointers into inline object definitions:pythondef clean_schema(schema: dict) -> dict: cleaned = schema.copy() cleaned.pop("$schema", None) cleaned.pop("$id", None) return cleaned
2. Error: spawn npx ENOENT on Windows Subprocesses
- ▸Symptom: Python raises
FileNotFoundError: [Errno 2] No such file or directory: 'npx'when executingcreate_subprocess_execon Windows. - ▸Root Cause: On Windows,
npxis not an executable binary file; it is a batch script (npx.cmd).asyncio.create_subprocess_execdoes not invoke the Windows shell by default and fails to locatenpx. - ▸Platform-Specific Terminal Fixes:
- ▸Windows (PowerShell): Use
npx.cmdexplicitly or passshell=Trueusingasyncio.create_subprocess_shell:pythonexecutable = "npx.cmd" if sys.platform == "win32" else "npx" self.process = await asyncio.create_subprocess_exec(executable, *self.args, ...) - ▸macOS / Linux: Ensure Node.js binaries installed via
nvmorfnmare included in the environment PATH passed to the subprocess.
- ▸Windows (PowerShell): Use
3. Stream Desynchronization from Logger Contamination
- ▸Symptom:
json.decoder.JSONDecodeError: Extra dataorUnrecognized tokenwhen reading fromstdout. - ▸Root Cause: The MCP server printed diagnostic output (such as
[INFO] Connected to database) directly toprocess.stdoutinstead ofprocess.stderr. - ▸Fix: Configure your MCP server logging settings or wrapper script to redirect all non-JSON logger output to
stderr. In TypeScript MCP servers, always useconsole.error()for diagnostic logging and reserveprocess.stdout.write()strictly for the JSON-RPC transport stream.
External Citations and Security Guardrails
For additional architecture details and SDK updates, refer to the official documentation and repositories:
- ▸Google GenAI Python SDK: Review function calling APIs in the google-gemini/generative-ai-python repository (opens in a new tab) and the Google AI Studio Gemini Documentation (opens in a new tab).
- ▸Model Context Protocol Specification: Read the official transport and message framing specifications at the MCP Specification (opens in a new tab).
- ▸Model Context Protocol TypeScript SDK: View source code and type definitions in the modelcontextprotocol/typescript-sdk repository (opens in a new tab).
Security Best Practices
- ▸API Key Isolation: Never hardcode
GEMINI_API_KEYinto application source code or commit it to version control. Pass keys exclusively via runtime environment variables. - ▸Read-Only Database Permissions: When providing database access to Gemini models, configure dedicated read-only database roles (
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_reader;) to prevent accidental data modifications. - ▸Execution Guardrails: Enforce confirmation checks before executing state-mutating tool calls such as file deletions or outbound HTTP requests.
Build your full agent toolstack in the Visual Generator
Combine verified 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:
Written by Rad Tome
Lead AI Systems Architect & 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
Configure 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
Production-grade MCP security: stdin/stdout isolation, OAuth 2.1 for SSE, path traversal prevention, SQL injection defense, rate limiting, and audit logging. Includes TypeScript implementation patterns.
Getting StartedHow to Set Up Your First MCP Server
Learn how to set up your first Model Context Protocol server in minutes: Step-by-step configuration for Claude Desktop, Cursor, and OpenAI Codex CLI.