Skip to main content
Glama
raydollete

Gemini MCP Server for Claude Code

by raydollete

Gemini MCP Server for Claude Code

Claude Code MCP TypeScript License Node.js

Give Claude Code access to Google's Gemini AI models. Get second opinions, compare approaches, and leverage Gemini's capabilities—all from within your Claude Code session.


Table of Contents


Related MCP server: Claude Code + Gemini MCP Server

Quick Start

# 1. Clone and build
git clone https://github.com/Raydius/gemini-for-claude-mcp.git
cd gemini-for-claude-mcp
npm install && npm run build

# 2. Authenticate to Google Cloud (one-time)
gcloud auth application-default login

# 3. Add to Claude Code (replace project ID and absolute path)
#    GOOGLE_CLOUD_LOCATION is optional and defaults to `global`. The newest
#    preview models (gemini-3-pro-preview, gemini-3.1-pro-preview) require
#    `global` — regional endpoints return 404 for those models.
claude mcp add gemini \
  -e GOOGLE_CLOUD_PROJECT=your-gcp-project-id \
  -e GEMINI_DEFAULT_MODEL=gemini-2.5-pro \
  -- node $(pwd)/dist/app.js

# 4. Start Claude Code and try it out
claude

Then ask Claude:

"Ask Gemini to explain the tradeoffs between microservices and monoliths"


Features

  • Built for Claude Code - Seamlessly integrates with your Claude Code workflow

  • Streaming Responses - Enabled by default for real-time output

  • Multi-turn Conversations - Maintain context across multiple Gemini queries

  • Configurable Model - Set your preferred Gemini model via environment variable

  • Token Counting - Estimate costs before making queries

  • Type-Safe - Built with strict TypeScript

  • Well-Tested - 100% domain layer test coverage


Prerequisites

  • Claude Code - Installation guide

  • Node.js 20+ - Download

  • Google Cloud project with the Vertex AI API enabled. See Enable the Vertex AI API.

  • IAM role: the principal running this server needs roles/aiplatform.user (or higher) on the project.

  • Authentication: either Application Default Credentials via gcloud auth application-default login (recommended for local dev), or a service-account JSON key referenced by GOOGLE_APPLICATION_CREDENTIALS.

  • gcloud CLI - Install (only needed for ADC login).


Installation & Setup

Step 1: Clone and Build

git clone https://github.com/Raydius/gemini-for-claude-mcp.git
cd gemini-for-claude-mcp
npm install
npm run build

Step 2: Authenticate to Google Cloud

gcloud auth application-default login

This stores Application Default Credentials that the server uses to call Vertex AI. Alternatively, set GOOGLE_APPLICATION_CREDENTIALS to the path of a service-account JSON key.

Step 3: Add to Claude Code

Option A: Using the CLI (Recommended)

# Basic setup (substitute default model for any valid Gemini model designation string)
# GOOGLE_CLOUD_LOCATION defaults to `global` and is omitted here. See "Vertex AI
# location" below if you need to pin a regional endpoint.
claude mcp add gemini \
  -e GOOGLE_CLOUD_PROJECT=your-gcp-project-id \
  -e GEMINI_DEFAULT_MODEL=gemini-2.5-pro \
  -- node /absolute/path/to/gemini-for-claude-mcp/dist/app.js

Option B: Manual Configuration

Edit your Claude Code settings file (~/.claude.json):

{
  "mcpServers": {
    "gemini": {
      "command": "node",
      "args": ["/absolute/path/to/gemini-for-claude-mcp/dist/app.js"],
      "env": {
        "GOOGLE_CLOUD_PROJECT": "your-gcp-project-id",
        "GEMINI_DEFAULT_MODEL": "gemini-2.5-flash"
      }
    }
  }
}

See Configuration for all available options and supported models.

Step 4: Verify Installation

Start Claude Code and verify the server is connected:

claude

Then ask:

"What Gemini models are available?"

If configured correctly, Claude will use the list_gemini_models tool and show you the available models.


Using with Claude Code

Once installed, you can ask Claude to use Gemini in natural language. Here are some examples:

Get a Second Opinion

You: I'm implementing a rate limiter. Can you ask Gemini for its approach?

Claude: I'll query Gemini for an alternative perspective on rate limiting...
[Uses query_gemini tool]

Gemini suggests using a token bucket algorithm. Here's the comparison:
- My approach: Sliding window...
- Gemini's approach: Token bucket with...

Compare Solutions

You: Here's my sorting algorithm. Have Gemini review it and compare approaches.

Claude: Let me get Gemini's analysis of your sorting implementation...
[Uses query_gemini tool]

Gemini's feedback: ...

Leverage Gemini's Strengths

You: Ask Gemini to analyze this mathematical proof for logical errors.

Claude: I'll have Gemini examine the proof...
[Uses query_gemini tool]

Check Token Usage Before Querying

You: How many tokens would this prompt use with Gemini?

Claude: Let me count the tokens...
[Uses count_gemini_tokens tool]

This text would use approximately 1,250 tokens.

Multi-turn Conversations

You: Start a conversation with Gemini about Rust's ownership model.

Claude: [Uses query_gemini tool]
Gemini explains: Rust's ownership model is based on three rules...

You: Ask Gemini to give an example of borrowing.

Claude: [Uses query_gemini with history from previous turn]
Gemini continues: Here's an example of borrowing...

Configuration

Configure the server using environment variables:

Variable

Required

Default

Description

GOOGLE_CLOUD_PROJECT

Yes

-

Google Cloud project ID hosting Vertex AI

GOOGLE_CLOUD_LOCATION

No

global

Vertex AI location. Newer preview models (e.g. gemini-3-pro-preview, gemini-3.1-pro-preview) are only served from global — regional endpoints like us-central1 return 404 for those models. Override only if every model you call is available in that region.

GOOGLE_APPLICATION_CREDENTIALS

No

-

Path to a service-account JSON key. Falls back to Application Default Credentials when unset.

GEMINI_DEFAULT_MODEL

Yes

-

Gemini model to use for queries

GEMINI_MAX_OUTPUT_TOKENS

No

65536

Max output tokens injected into requests

GEMINI_TIMEOUT_MS

No

300000

Request timeout in milliseconds

LOG_LEVEL

No

info

Log level (fatal, error, warn, info, debug, trace)

Vertex AI location (GOOGLE_CLOUD_LOCATION)

This server defaults to global because the newest preview Gemini models — including gemini-3-pro-preview and gemini-3.1-pro-preview — are only served from the global location. Pointing the client at a regional endpoint (us-central1, europe-west4, etc.) will return a 404 for those models, which surfaces as a GEMINI_MODEL_NOT_FOUND error.

Override GOOGLE_CLOUD_LOCATION only if every model you intend to call is available in that region. Check per-model availability at https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations before pinning a region.


Other MCP Clients

While this server is optimized for Claude Code, it works with any MCP-compatible client.

Claude Desktop

Add to your Claude Desktop configuration:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "gemini": {
      "command": "node",
      "args": ["/absolute/path/to/gemini-for-claude-mcp/dist/app.js"],
      "env": {
        "GOOGLE_CLOUD_PROJECT": "your-gcp-project-id",
        "GEMINI_DEFAULT_MODEL": "gemini-2.5-flash"
      }
    }
  }
}

Generic stdio Clients

This server uses stdio transport. Start it with:

GOOGLE_CLOUD_PROJECT=your-gcp-project-id \
GEMINI_DEFAULT_MODEL=gemini-2.5-flash \
node dist/app.js

This relies on Application Default Credentials. To use a service-account key instead, also export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json.

The server communicates via stdin/stdout using the MCP protocol.


Development

Available Scripts

Command

Description

npm run build

Compile TypeScript to JavaScript

npm run dev

Run in development mode with hot reload

npm start

Run the compiled server

npm test

Run all tests

npm run test:coverage

Run tests with coverage report

npm run lint

Check code with ESLint

npm run lint:fix

Fix ESLint issues automatically

npm run typecheck

Type-check without emitting files

Project Structure

src/
├── domain/           # Business logic (zero external dependencies)
│   ├── entities/     # Business objects (GeminiModel, GeminiPrompt, etc.)
│   ├── ports/        # Interfaces for external services
│   ├── use-cases/    # Application logic
│   └── errors/       # Domain-specific errors
├── infrastructure/   # External integrations
│   ├── adapters/     # Port implementations
│   ├── controllers/  # MCP request handlers
│   ├── schemas/      # Zod validation schemas
│   └── mcp/          # MCP server and tool definitions
├── config/           # Environment validation
├── shared/           # Cross-cutting utilities
└── app.ts            # Entry point

Tool Reference

Technical details for developers integrating with or extending the MCP tools.

query_gemini

Query Google's Gemini AI models for text generation, reasoning, and analysis tasks. The model is configured via the GEMINI_DEFAULT_MODEL environment variable.

Parameters:

Parameter

Type

Required

Default

Description

prompt

string

Yes

-

The prompt to send to Gemini (1-100,000 chars)

history

array

No

-

Previous conversation turns for multi-turn conversations

stream

boolean

No

true

Stream response progressively

History Array Item Schema:

{
  "role": "user" | "model",
  "content": "string"
}

Example Response:

{
  "success": true,
  "data": {
    "response": "Recursion is a programming technique where a function calls itself...",
    "model": "gemini-3-pro-preview",
    "finishReason": "STOP",
    "tokenUsage": {
      "prompt": 12,
      "completion": 150,
      "total": 162
    }
  }
}

list_gemini_models

List popular Gemini AI models that can be configured via the GEMINI_DEFAULT_MODEL environment variable.

Parameters: None

Example Response:

{
  "success": true,
  "data": {
    "count": 4,
    "models": [
      {
        "name": "gemini-3-pro-preview",
        "displayName": "Gemini 3 Pro Preview",
        "description": "Most advanced reasoning model with 1M context - best for complex tasks"
      },
      {
        "name": "gemini-2.5-pro",
        "displayName": "Gemini 2.5 Pro",
        "description": "Capable thinking model for complex reasoning, code, math, and STEM"
      },
      {
        "name": "gemini-2.5-flash",
        "displayName": "Gemini 2.5 Flash",
        "description": "Fast and efficient for most tasks with excellent performance"
      },
      {
        "name": "gemini-2.0-flash",
        "displayName": "Gemini 2.0 Flash",
        "description": "Multimodal model optimized for speed and cost-efficiency"
      }
    ]
  }
}

count_gemini_tokens

Count the number of tokens in a text string for the configured Gemini model.

Parameters:

Parameter

Type

Required

Default

Description

text

string

Yes

-

The text to count tokens for (1-1,000,000 chars)

Example Response:

{
  "success": true,
  "data": {
    "totalTokens": 10,
    "model": "gemini-3-pro-preview"
  }
}

Architecture

This project follows Clean Architecture (Ports and Adapters) principles:

  • Domain Layer - Core business logic with zero external dependencies

  • Infrastructure Layer - External integrations (Gemini SDK, MCP SDK)

  • Strict Dependency Rule - Dependencies always point inward

For detailed architectural documentation, see ARCHITECTURE.md.


Troubleshooting

Claude Code Issues

"Server not found" or tools not appearing

  • Verify the MCP server is added: claude mcp list

  • Check the path to dist/app.js is absolute and correct

  • Ensure the project has been built: npm run build

"GOOGLE_CLOUD_PROJECT is required"

  • Verify the project ID is set in the MCP configuration

  • Check with: claude mcp list to see environment variables

"Could not load the default credentials" / 401 Unauthorized

  • Run gcloud auth application-default login to refresh ADC

  • Or set GOOGLE_APPLICATION_CREDENTIALS to a valid service-account JSON key

  • Confirm the principal has roles/aiplatform.user on the project

"Permission denied on resource project ..."

  • The Vertex AI API may not be enabled. See Enable the API.

  • The service account or user lacks roles/aiplatform.user.

Server crashes on startup

  • Check Node.js version: node --version (must be 20+)

  • Verify dependencies are installed: npm install

API Issues

"Rate limit exceeded"

  • Gemini API has rate limits; wait and retry

  • Consider using gemini-2.0-flash for higher rate limits

"Content filtered" error

  • Gemini has content safety filters

  • Rephrase your prompt to avoid triggering filters

Streaming not working

  • Streaming is enabled by default

  • Set stream: false in your query if needed

Debug Mode

Enable debug logging for troubleshooting:

claude mcp add gemini \
  -e GOOGLE_CLOUD_PROJECT=your-gcp-project-id \
  -e GEMINI_DEFAULT_MODEL=gemini-2.5-pro \
  -e LOG_LEVEL=debug \
  -- node /path/to/dist/app.js

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository

  2. Create a feature branch: git checkout -b feat/your-feature

  3. Make your changes following the code standards in CLAUDE.md

  4. Run tests: npm test

  5. Run linting: npm run lint

  6. Commit with conventional commits: git commit -m "feat: add new feature"

  7. Push and create a Pull Request

Code Standards

  • TypeScript strict mode required

  • All exported functions need explicit return types

  • Use neverthrow Result pattern for error handling

  • Validate inputs with Zod at boundaries

  • 100% test coverage for domain layer


License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


Acknowledgments

Available Tools

3 tools
count_gemini_tokensA

Count the number of tokens in a text string for the configured Gemini model.

Use this tool to:

  • Estimate prompt costs before making queries

  • Ensure prompts fit within model context limits

  • Optimize prompt length for efficiency

ParametersJSON Schema
NameRequiredDescriptionDefault
textYesThe text to count tokens for

TDQS

A4.4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It describes the tool's purpose and use cases but lacks behavioral details such as rate limits, error handling, or whether it's a read-only operation (though implied by 'count'). It adds value by explaining the practical applications but misses some operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose in the first sentence, followed by a bulleted list of use cases that are directly relevant and efficient. Every sentence earns its place without redundancy, making it highly concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (single parameter, no output schema, no annotations), the description is mostly complete. It covers purpose, usage, and parameter context, but lacks details on output format or error handling, which would be helpful for full completeness. It's adequate but has minor gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, so the baseline is 3. The description adds value by clarifying that the text is for 'the configured Gemini model,' which provides context beyond the schema's generic 'text to count tokens for.' However, it doesn't detail tokenization specifics or model dependencies, keeping it at 4.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Count the number of tokens') and resource ('text string for the configured Gemini model'), distinguishing it from siblings like list_gemini_models (listing models) and query_gemini (making queries). It avoids tautology by explaining what counting tokens means rather than just restating the name.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly provides three use cases (estimating costs, ensuring context limits, optimizing length), which clearly indicate when to use this tool. It implicitly distinguishes from query_gemini by focusing on pre-query analysis rather than actual querying, though it doesn't explicitly name alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_gemini_modelsA

List available Gemini AI models and their capabilities.

Use this tool to:

  • Discover available Gemini models

  • Understand model capabilities and limitations

  • Choose the appropriate model for a specific task

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'capabilities and limitations' which hints at behavioral traits, but doesn't specify whether this is a read-only operation, whether it requires authentication, what format the output takes, or if there are rate limits. The description adds some context but leaves important behavioral aspects unspecified.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly structured with a clear opening statement followed by three specific bullet points. Every sentence earns its place by providing distinct value: the first establishes purpose, the bullets provide concrete usage scenarios. No wasted words or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given zero parameters and no output schema, the description provides adequate purpose and usage guidance. However, for a tool with no annotations, it should ideally mention whether this is a read operation, what the output format looks like (list of models with metadata), and any authentication requirements. The current description is complete enough for basic understanding but lacks operational details.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters with 100% schema description coverage, so the schema already fully documents the parameter situation. The description appropriately doesn't discuss parameters since none exist, maintaining focus on the tool's purpose and usage. This earns a baseline 4 for zero-parameter tools.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verb ('List') and resource ('available Gemini AI models and their capabilities'). It distinguishes from sibling tools count_gemini_tokens (token counting) and query_gemini (model querying) by focusing on model discovery and capability assessment.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly provides three bullet points detailing when to use this tool: to discover models, understand capabilities/limitations, and choose appropriate models for tasks. This gives clear guidance on its intended context and distinguishes it from alternatives like query_gemini which would be used after model selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

query_geminiA

Query Google's Gemini AI models for text generation, reasoning, and analysis tasks.

Use this tool when you need to:

  • Get a second opinion or alternative perspective on a problem

  • Leverage Gemini's specific capabilities for certain reasoning tasks

  • Generate content using a different AI model

  • Compare responses between AI models

The tool supports conversation history for multi-turn interactions. Streaming is enabled by default for better responsiveness.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesThe prompt to send to Gemini. Be specific and clear.
historyNoPrevious conversation turns for multi-turn conversations
streamNoStream response progressively. Enabled by default. Set to false only if you need the complete response at once.

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: supports conversation history for multi-turn interactions, streaming enabled by default for better responsiveness. It doesn't mention rate limits, authentication needs, or error behaviors, but provides substantial operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and front-loaded with the core purpose, followed by usage guidelines and behavioral details. Every sentence earns its place - no redundant information, and the bulleted list efficiently communicates usage scenarios without verbosity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a query tool with no annotations and no output schema, the description provides good context about when to use it and behavioral characteristics. It could be more complete by mentioning response format, error handling, or model selection options, but covers the essential operational aspects well given the complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description adds minimal parameter semantics beyond the schema - it mentions 'conversation history for multi-turn interactions' which relates to the history parameter, but doesn't provide additional context about prompt construction or streaming implications beyond what's in the schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Query Google's Gemini AI models for text generation, reasoning, and analysis tasks' - a specific verb+resource combination. It distinguishes from sibling tools (count_gemini_tokens, list_gemini_models) by focusing on querying rather than token counting or model listing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage scenarios in a bulleted list: 'Get a second opinion or alternative perspective', 'Leverage Gemini's specific capabilities', 'Generate content using a different AI model', and 'Compare responses between AI models'. These give clear guidance on when to use this tool versus alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A4.4/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap. count_gemini_tokens handles token counting, list_gemini_models provides model information, and query_gemini performs AI queries. The descriptions reinforce these distinct roles, making misselection unlikely.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern with snake_case naming. The verbs (count, list, query) are appropriately chosen for their actions, and the noun (gemini) is consistently included, creating a predictable and readable naming convention throughout.

Tool Count4/5

Three tools is reasonable for a Gemini-focused server, covering token counting, model listing, and querying. While slightly minimal, each tool earns its place and provides distinct functionality. A potential fourth tool for model configuration or advanced settings might be missing, but the core operations are well-represented.

Completeness4/5

The toolset covers the essential Gemini operations: token management, model discovery, and query execution. Minor gaps include lack of direct model configuration tools or advanced query parameters, but agents can work around these. The surface supports basic to intermediate Gemini interactions effectively.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol server that enables Claude to collaborate with Google's Gemini AI models, providing tools for question answering, code review, brainstorming, test generation, and explanations.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables Claude Desktop to interact with Google's Gemini API, allowing users to query Gemini models directly or facilitate conversations between Claude and Gemini with conversation history management.
    70
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/raydollete/gemini-for-claude-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server