Getting Started·
intermediate
·12 min read·Sep 24, 2026·Updated Nov 12, 2026
·Lead AI Systems Architect·Verification Charter

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.

MCPGeminiGoogleAntigravityCodexClaudesetuptools
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 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:

code
+-----------------------------------------------------------------------+
|                    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:

  1. ▸Process Lifecycle Management: Booting the upstream MCP server binary with isolated environment variables and non-blocking stdio descriptors.
  2. ▸Schema Ingestion: Fetching tool metadata from tools/list and restructuring JSON Schema draft-07 types into Gemini-compatible OpenAPI schemas.
  3. ▸Execution Relay: Converting Gemini functionCall parameters into standard tools/call JSON-RPC frames.
  4. ▸Context Injection: Packaging the MCP tool output into a types.Part.from_function_response structure 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:

DependencyMinimum VersionRecommended VersionDescription
Python3.10.03.12.3Modern asynchronous event loop support
Google GenAI SDK1.0.01.2.0Official google-genai Python library
Node.jsv20.18.0 LTSv22.12.0 LTSRuntime for official TypeScript MCP servers
npm10.8.210.9.0Package manager for @modelcontextprotocol binaries
Google Antigravity2.0.02.2.4Google agentic coding environment

You must also obtain a valid Gemini API key from Google AI Studio and export it into your operating system shell:

bash
export GEMINI_API_KEY="AIzaSyYourGeminiApiKeyHere"

On Windows PowerShell:

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:

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):

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"
      ]
    }
  }
}

Cursor IDE Configuration

In Cursor's .cursor/mcp.json settings:

json
{
  "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:

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:

python
# 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:

python
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():
    code
    google.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, or anyOf) that the Gemini function calling engine rejects.
  • ▸Fix: Sanitize the schema dictionary before instantiating types.FunctionDeclaration. Remove $schema, $id, and resolve $ref pointers into inline object definitions:
    python
    def 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 executing create_subprocess_exec on Windows.
  • ▸Root Cause: On Windows, npx is not an executable binary file; it is a batch script (npx.cmd). asyncio.create_subprocess_exec does not invoke the Windows shell by default and fails to locate npx.
  • ▸Platform-Specific Terminal Fixes:
    • ▸Windows (PowerShell): Use npx.cmd explicitly or pass shell=True using asyncio.create_subprocess_shell:
      python
      executable = "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 nvm or fnm are included in the environment PATH passed to the subprocess.

3. Stream Desynchronization from Logger Contamination

  • ▸Symptom: json.decoder.JSONDecodeError: Extra data or Unrecognized token when reading from stdout.
  • ▸Root Cause: The MCP server printed diagnostic output (such as [INFO] Connected to database) directly to process.stdout instead of process.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 use console.error() for diagnostic logging and reserve process.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:

Security Best Practices

  1. ▸API Key Isolation: Never hardcode GEMINI_API_KEY into application source code or commit it to version control. Pass keys exclusively via runtime environment variables.
  2. ▸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.
  3. ▸Execution Guardrails: Enforce confirmation checks before executing state-mutating tool calls such as file deletions or outbound HTTP requests.
Ready to Deploy?

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.

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:

RT✓

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.

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

Related Guides