Gemini AI

by bsmi021

11 stars
465 downloads
Not rated
GitHub

About

Provides a robust interface to Google's Gemini AI models with specialized tools for content generation, chat functionality, function calling, and file/cache management.

Details

Author
bsmi021
Repository
bsmi021/mcp-gemini-server
GitHub stars
11
Downloads
465
License
MIT License
Categories
Developer Tools, Design, File Management, AI, Community, Communication, Frontend, Infrastructure

Core Generation: Standard (gemini_generateContent) and streaming (gemini_generateContentStream) text generation with support for system instructions and cached content.
Function Calling: Enables Gemini models to request the execution of client-defined functions (gemini_functionCall).
Stateful Chat: Manages conversational context across multiple turns (gemini_startChat, gemini_sendMessage, gemini_sendFunctionResult) with support for system instructions, tools, and cached content.
URL-Based Multimedia Analysis: Analyze images from public URLs and YouTube videos without file uploads. Direct file uploads are not supported.
Caching: Create, list, retrieve, update, and delete cached content to optimize prompts with support for tools and tool configurations.
Image Generation: Generate images from text prompts using Gemini 2.0 Flash Experimental (gemini_generateImage) with control over resolution, number of images, and negative prompts. Also supports the latest Imagen 3.1 model for high-quality dedicated image generation with advanced style controls. Note that Gemini 2.5 models (Flash and Pro) do not currently support image generation.
URL Context Processing: Fetch and analyze web content directly from URLs with advanced security, caching, and content processing capabilities.
gemini_generateContent: Enhanced with URL context support for including web content in prompts
gemini_generateContentStream: Streaming generation with URL context integration
gemini_url_analysis: Specialized tool for advanced URL content analysis with multiple analysis types
MCP Client: Connect to and interact with external MCP servers.
mcpConnectToServer: Establishes a connection to an external MCP server.
mcpListServerTools: Lists available tools on a connected MCP server.
mcpCallServerTool: Calls a function on a connected MCP server, with an option for file output.
mcpDisconnectFromServer: Disconnects from an external MCP server.
writeToFile: Writes content directly to files within allowed directories.

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name Gemini AI
    Command (node, npx, python, etc.) node
    Arguments
    • Argument 1 /path/to/mcp-gemini-server/dist/server.js
    Environment
    • MCP_SERVER_HOST localhost
    • MCP_SERVER_PORT 8080
    • GOOGLE_GEMINI_MODEL gemini-1.5-flash
    • ALLOWED_OUTPUT_PATHS /var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs
    • MCP_CONNECTION_TOKEN YOUR_GENERATED_CONNECTION_TOKEN
    • GOOGLE_GEMINI_API_KEY YOUR_API_KEY

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

The server uses environment variables for configuration, passed via the env object in the MCP settings:

GOOGLE_GEMINI_API_KEY (Required): Your API key obtained from Google AI Studio.
GOOGLE_GEMINI_MODEL (Optional): Specifies a default Gemini model name (e.g., gemini-1.5-flash, gemini-1.0-pro). If set, tools that require a model name (like gemini_generateContent, gemini_startChat, etc.) will use this default when the modelName parameter is omitted in the tool call. This simplifies client calls when primarily using one model. If this environment variable is not set, the modelName parameter becomes required for those tools. See the Google AI documentation for available model names.
ALLOWED_OUTPUT_PATHS (Optional): A comma-separated list of absolute paths to directories where the mcpCallServerTool (with outputToFile parameter) and writeToFileTool are allowed to write files. If not set, file output will be disabled for these tools. This is a security measure to prevent arbitrary file writes.

1. Clone/Place Project: Ensure the mcp-gemini-server project directory is accessible on your system.
2. Install Dependencies: Navigate to the project directory in your terminal and run:

    npm install
    

3. Build Project: Compile the TypeScript source code:

    npm run build
    

This command uses the TypeScript compiler (tsc) and outputs the JavaScript files to the ./dist directory (as specified by outDir in tsconfig.json). The main server entry point will be dist/server.js.
4. Generate Connection Token: Create a strong, unique connection token for secure communication between your MCP client and the server. This is a shared secret that you generate and configure on both the server and client sides.

Generate a secure token using one of these methods:

Option A: Using Node.js crypto (Recommended)

    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Option B: Using OpenSSL

    openssl rand -hex 32

Option C: Using PowerShell (Windows)

    [System.Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32))

Option D: Online Generator (Use with caution)
Use a reputable password generator like 1Password or Bitwarden to generate a 64-character random string.

Important Security Notes:
- The token should be at least 32 characters long and contain random characters
- Never share this token or commit it to version control
- Use a different token for each server instance
- Store the token securely (environment variables, secrets manager, etc.)
- Save this token - you'll need to use the exact same value in both server and client configurations

5. Configure MCP Client: Add the server configuration to your MCP client's settings file (e.g., cline_mcp_settings.json for Cline/VSCode, or claude_desktop_config.json for Claude Desktop App). Replace /path/to/mcp-gemini-server with the actual absolute path on your system, YOUR_API_KEY with your Google AI Studio key, and YOUR_GENERATED_CONNECTION_TOKEN with the token you generated in step 4.

    {
      "mcpServers": {
        "gemini-server": { // Or your preferred name
          "command": "node",
          "args": ["/path/to/mcp-gemini-server/dist/server.js"], // Absolute path to the compiled server entry point
          "env": {
            "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY",
            "MCP_SERVER_HOST": "localhost",       // Required: Server host
            "MCP_SERVER_PORT": "8080",            // Required: Server port  
            "MCP_CONNECTION_TOKEN": "YOUR_GENERATED_CONNECTION_TOKEN", // Required: Use the token from step 4
            "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash", // Optional: Set a default model
            // Optional security configurations removed - file operations no longer supported
            "ALLOWED_OUTPUT_PATHS": "/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs" // Optional: Comma-separated list of allowed output directories for mcpCallServerTool and writeToFileTool
          },
          "disabled": false,
          "autoApprove": []
        }
        // ... other servers
      }
    }
    

Important Notes:
- The path in args must be the absolute path to the compiled dist/server.js file
- MCP_SERVER_HOST, MCP_SERVER_PORT, and MCP_CONNECTION_TOKEN are required unless NODE_ENV is set to test
- MCP_CONNECTION_TOKEN must be the exact same value you generated in step 4
- Ensure the path exists and the server has been built using npm run build
6. Restart MCP Client: Restart your MCP client application (e.g., VS Code with Cline extension, Claude Desktop App) to load the new server configuration. The MCP client will manage starting and stopping the server process.

Here are examples of how an MCP client (like Claude) might call these tools using the use_mcp_tool format:

Example 1: Simple Content Generation (Using Default Model)

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "prompt": "Write a short poem about a rubber duck."
    }
  </arguments>
</use_mcp_tool>

Example 2: Content Generation (Specifying Model & Config)

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-1.0-pro",
      "prompt": "Explain the concept of recursion in programming.",
      "generationConfig": {
        "temperature": 0.7,
        "maxOutputTokens": 500
      }
    }
  </arguments>
</use_mcp_tool>

Example 2b: Content Generation with Thinking Budget Control

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-1.5-pro",
      "prompt": "Solve this complex math problem: Find all values of x where 2sin(x) = x^2-x+1 in the range [0, 2π].",
      "generationConfig": {
        "temperature": 0.2,
        "maxOutputTokens": 1000,
        "thinkingConfig": {
          "thinkingBudget": 8192
        }
      }
    }
  </arguments>
</use_mcp_tool>

Example 2c: Content Generation with Simplified Reasoning Effort

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-1.5-pro",
      "prompt": "Solve this complex math problem: Find all values of x where 2sin(x) = x^2-x+1 in the range [0, 2π].",
      "generationConfig": {
        "temperature": 0.2,
        "maxOutputTokens": 1000,
        "thinkingConfig": {
          "reasoningEffort": "high"
        }
      }
    }
  </arguments>
</use_mcp_tool>

Example 3: Starting and Continuing a Chat

Start Chat:

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_startChat</tool_name>
  <arguments>
    {}
  </arguments>
</use_mcp_tool>

(Assume response contains sessionId: "some-uuid-123")

Send Message:

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_sendMessage</tool_name>
  <arguments>
    {
      "sessionId": "some-uuid-123",
      "message": "Hello! Can you tell me about the Gemini API?"
    }
  </arguments>
</use_mcp_tool>

Example 4: Content Generation with System Instructions (Simplified Format)

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-2.5-pro-exp",
      "prompt": "What should I do with my day off?",
      "systemInstruction": "You are a helpful assistant that provides friendly and detailed advice. You should focus on outdoor activities and wellness."
    }
  </arguments>
</use_mcp_tool>

Example 5: Content Generation with System Instructions (Object Format)

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-1.5-pro-latest",
      "prompt": "What should I do with my day off?",
      "systemInstruction": {
        "parts": [
          {
            "text": "You are a helpful assistant that provides friendly and detailed advice. You should focus on outdoor activities and wellness."
          }
        ]
      }
    }
  </arguments>
</use_mcp_tool>

Example 6: Using Cached Content with System Instruction

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "modelName": "gemini-2.5-pro-exp",
      "prompt": "Explain how these concepts relate to my product?",
      "cachedContentName": "cachedContents/abc123xyz",
      "systemInstruction": "You are a product expert who explains technical concepts in simple terms."
    }
  </arguments>
</use_mcp_tool>

Example 6: Generating an Image

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateImage</tool_name>
  <arguments>
    {
      "prompt": "A futuristic cityscape with flying cars and neon lights",
      "modelName": "gemini-2.0-flash-exp-image-generation",
      "resolution": "1024x1024",
      "numberOfImages": 1,
      "negativePrompt": "dystopian, ruins, dark, gloomy"
    }
  </arguments>
</use_mcp_tool>

Example 6b: Generating a High-Quality Image with Imagen 3.1

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateImage</tool_name>
  <arguments>
    {
      "prompt": "A futuristic cityscape with flying cars and neon lights",
      "modelName": "imagen-3.1-generate-003",
      "resolution": "1024x1024",
      "numberOfImages": 4,
      "negativePrompt": "dystopian, ruins, dark, gloomy"
    }
  </arguments>
</use_mcp_tool>

Example 6c: Using Advanced Style Options

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateImage</tool_name>
  <arguments>
    {
      "prompt": "A futuristic cityscape with flying cars and neon lights",
      "modelName": "imagen-3.1-generate-003",
      "resolution": "1024x1024",
      "numberOfImages": 2,
      "stylePreset": "anime",
      "styleStrength": 0.8,
      "seed": 12345
    }
  </arguments>
</use_mcp_tool>

Example 7: Message Routing Between Models

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_routeMessage</tool_name>
  <arguments>
    {
      "message": "Can you create a detailed business plan for a sustainable fashion startup?",
      "models": ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.5-pro"],
      "routingPrompt": "Analyze this message and determine which model would be best suited to handle it. Consider: gemini-1.5-flash for simpler tasks, gemini-1.5-pro for balanced capabilities, and gemini-2.5-pro for complex creative tasks.",
      "defaultModel": "gemini-1.5-pro",
      "generationConfig": {
        "temperature": 0.7,
        "maxOutputTokens": 1024
      }
    }
  </arguments>
</use_mcp_tool>

The response will be a JSON string containing both the text response and which model was chosen:

{
  "text": "# Business Plan for Sustainable Fashion Startup\n\n## Executive Summary\n...",
  "chosenModel": "gemini-2.5-pro"
}

Example 8: Using URL Context with Content Generation

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "prompt": "Summarize the main points from these articles and compare their approaches to sustainable technology",
      "urlContext": {
        "urls": [
          "https://example.com/sustainable-tech-2024",
          "https://techblog.com/green-innovation"
        ],
        "fetchOptions": {
          "maxContentKb": 150,
          "includeMetadata": true,
          "convertToMarkdown": true
        }
      },
      "modelPreferences": {
        "preferQuality": true,
        "taskType": "reasoning"
      }
    }
  </arguments>
</use_mcp_tool>

Example 9: Advanced URL Analysis

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_url_analysis</tool_name>
  <arguments>
    {
      "urls": ["https://company.com/about", "https://company.com/products"],
      "analysisType": "extraction",
      "extractionSchema": {
        "companyName": "string",
        "foundedYear": "number",
        "numberOfEmployees": "string",
        "mainProducts": "array",
        "headquarters": "string",
        "financialInfo": "object"
      },
      "outputFormat": "json",
      "query": "Extract comprehensive company information including business details and product offerings"
    }
  </arguments>
</use_mcp_tool>

Example 10: Multi-URL Content Comparison

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_url_analysis</tool_name>
  <arguments>
    {
      "urls": [
        "https://site1.com/pricing",
        "https://site2.com/pricing", 
        "https://site3.com/pricing"
      ],
      "analysisType": "comparison",
      "compareBy": ["pricing models", "features", "target audience", "value proposition"],
      "outputFormat": "markdown",
      "includeMetadata": true
    }
  </arguments>
</use_mcp_tool>

Example 11: URL Content with Security Restrictions

<use_mcp_tool>
  <server_name>gemini-server</server_name>
  <tool_name>gemini_generateContent</tool_name>
  <arguments>
    {
      "prompt": "Analyze the content from these trusted news sources",
      "urlContext": {
        "urls": [
          "https://reuters.com/article/tech-news",
          "https://bbc.com/news/technology"
        ],
        "fetchOptions": {
          "allowedDomains": ["reuters.com", "bbc.com"],
          "maxContentKb": 200,
          "timeoutMs": 15000,
          "userAgent": "Research-Bot/1.0"
        }
      }
    }
  </arguments>
</use_mcp_tool>

- GOOGLE_GEMINI_MODEL: Default model to use (e.g., gemini-1.5-pro-latest, gemini-1.5-flash)
- GOOGLE_GEMINI_DEFAULT_THINKING_BUDGET: Default thinking budget in tokens (0-24576) for controlling model reasoning

- GOOGLE_GEMINI_ENABLE_URL_CONTEXT: Enable URL context features (options: true, false; default: false)
- GOOGLE_GEMINI_URL_MAX_COUNT: Maximum URLs per request (default: 20)
- GOOGLE_GEMINI_URL_MAX_CONTENT_KB: Maximum content size per URL in KB (default: 100)
- GOOGLE_GEMINI_URL_FETCH_TIMEOUT_MS: Fetch timeout per URL in milliseconds (default: 10000)
- GOOGLE_GEMINI_URL_ALLOWED_DOMAINS: Comma-separated list or JSON array of allowed domains (default:
for all domains)
- GOOGLE_GEMINI_URL_BLOCKLIST: Comma-separated list or JSON array of blocked domains (default: empty)
- GOOGLE_GEMINI_URL_CONVERT_TO_MARKDOWN: Convert HTML content to markdown (options: true, false; default: true)
- GOOGLE_GEMINI_URL_INCLUDE_METADATA: Include URL metadata in context (options: true, false; default: true)
- GOOGLE_GEMINI_URL_ENABLE_CACHING: Enable URL content caching (options: true, false; default: true)
- GOOGLE_GEMINI_URL_USER_AGENT: Custom User-Agent header for URL requests (default: MCP-Gemini-Server/1.0)

- ALLOWED_OUTPUT_PATHS: A comma-separated list of absolute paths to directories where tools like mcpCallServerTool (with outputToFile parameter) and writeToFileTool are allowed to write files. Critical security feature to prevent unauthorized file writes. If not set, file output will be disabled for these tools.

- MCP_CLIENT_ID: Default client ID used when this server acts as a client to other MCP servers (defaults to "gemini-sdk-client")
- MCP_TRANSPORT: Transport to use for MCP server (options: stdio, sse, streamable, http; default: stdio)
- IMPORTANT: SSE (Server-Sent Events) is NOT deprecated and remains a critical component of the MCP protocol
- SSE is particularly valuable for bidirectional communication, enabling features like dynamic tool updates and sampling
- Each transport type has specific valid use cases within the MCP ecosystem
- MCP_LOG_LEVEL: Log level for MCP operations (options: debug, info, warn, error; default: info)
- MCP_ENABLE_STREAMING: Enable SSE streaming for HTTP transport (options: true, false; default: false)
- MCP_SESSION_TIMEOUT: Session timeout in seconds for HTTP transport (default: 3600 = 1 hour)
- SESSION_STORE_TYPE: Session storage backend (memory or sqlite; default: memory)
- SQLITE_DB_PATH: Path to SQLite database file when using sqlite store (default: ./data/sessions.db)

- MCP_TRANSPORT_TYPE: Deprecated - Use MCP_TRANSPORT instead
- MCP_WS_PORT: Deprecated - Use MCP_SERVER_PORT instead
- ENABLE_HEALTH_CHECK: Enable health check server (options: true, false; default: true)
- HEALTH_CHECK_PORT: Port for health check HTTP server (default: 3000)

You can create a .env file in the root directory with these variables:


GOOGLE_GEMINI_API_KEY=your_api_key_here

GOOGLE_GEMINI_MODEL=gemini-1.5-pro-latest
GOOGLE_GEMINI_DEFAULT_THINKING_BUDGET=4096

ALLOWED_OUTPUT_PATHS=/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs # For mcpCallServerTool and writeToFileTool

GOOGLE_GEMINI_ENABLE_URL_CONTEXT=true # Enable URL context features
GOOGLE_GEMINI_URL_MAX_COUNT=20 # Maximum URLs per request
GOOGLE_GEMINI_URL_MAX_CONTENT_KB=100 # Maximum content size per URL in KB
GOOGLE_GEMINI_URL_FETCH_TIMEOUT_MS=10000 # Fetch timeout per URL in milliseconds
GOOGLE_GEMINI_URL_ALLOWED_DOMAINS= # Allowed domains ( for all, or comma-separated list)
GOOGLE_GEMINI_URL_BLOCKLIST=malicious.com,spam.net # Blocked domains (comma-separated)
GOOGLE_GEMINI_URL_CONVERT_TO_MARKDOWN=true # Convert HTML to markdown
GOOGLE_GEMINI_URL_INCLUDE_METADATA=true # Include URL metadata in context
GOOGLE_GEMINI_URL_ENABLE_CACHING=true # Enable URL content caching
GOOGLE_GEMINI_URL_USER_AGENT=MCP-Gemini-Server/1.0 # Custom User-Agent

MCP_CLIENT_ID=gemini-sdk-client # Optional: Default client ID for MCP connections (defaults to "gemini-sdk-client")
MCP_TRANSPORT=stdio # Options: stdio, sse, streamable, http (replaced deprecated MCP_TRANSPORT_TYPE)
MCP_LOG_LEVEL=info # Optional: Log level for MCP operations (debug, info, warn, error)
MCP_ENABLE_STREAMING=true # Enable SSE streaming for HTTP transport
MCP_SESSION_TIMEOUT=3600 # Session timeout in seconds for HTTP transport
SESSION_STORE_TYPE=memory # Options: memory, sqlite
SQLITE_DB_PATH=./data/sessions.db # Path to SQLite database file when using sqlite store
ENABLE_HEALTH_CHECK=true
HEALTH_CHECK_PORT=3000

1. Connection Tokens
- MCP_CONNECTION_TOKEN provides basic authentication for clients connecting to this server
- Should be treated as a secret and use a strong, unique value in production

2. API Key Security
- GOOGLE_GEMINI_API_KEY grants access to Google Gemini API services
- Must be kept secure and never exposed in client-side code or logs
- Use environment variables or secure secret management systems to inject this value

1. File Paths
- Always use absolute paths for ALLOWED_OUTPUT_PATHS
- Use paths outside the application directory to prevent source code modification
- Restrict to specific, limited-purpose directories with appropriate permissions
- NEVER include sensitive system directories like "/", "/etc", "/usr", "/bin", or "/home"

2. Process Isolation
- Run the server with restricted user permissions
- Consider containerization (Docker) for additional isolation

3. Secrets Management
- Use a secure secrets management solution instead of .env files in production
- Rotate API keys and connection tokens regularly

4. URL Context Security
- Enable URL context only when needed: Set GOOGLE_GEMINI_ENABLE_URL_CONTEXT=false if not required
- Use restrictive domain allowlists: Avoid GOOGLE_GEMINI_URL_ALLOWED_DOMAINS=* in production
- Configure comprehensive blocklists: Add known malicious domains to GOOGLE_GEMINI_URL_BLOCKLIST
- Set conservative resource limits: Use appropriate values for GOOGLE_GEMINI_URL_MAX_CONTENT_KB and GOOGLE_GEMINI_URL_MAX_COUNT
- Monitor URL access patterns: Review logs for suspicious URL access attempts
- Consider network-level protection: Use firewalls or proxies to add additional URL filtering

Tests for the GitHub code review functionality can also use the cheaper model:

bash

npm install

For running tests that require API access, create a .env.test file in the project root with the following variables:


1. Fork and Clone the Repository
   
bash git clone https://github.com/yourusername/mcp-gemini-server.git cd mcp-gemini-server

2. Install Dependencies
   
bash npm install

3. Set Up Environment Variables
   Create a .env file in the project root with the necessary variables as described in the Environment Variables section.

4. Build and Run

bash
npm run build
npm run dev
```

gemini_generateContent

Generates non-streaming text content from a prompt with optional URL context support. Required Params: prompt (string). Optional Params: modelName (string), generationConfig (object), safetySettings (array), systemInstruction (string or object), cachedContentName (string), urlContext (object), modelPreferences (object).

gemini_generateContentStream

Generates text content via streaming using Server-Sent Events (SSE) for real-time content delivery with URL context support. Required Params: prompt (string). Optional Params: modelName (string), generationConfig (object), safetySettings (array), systemInstruction (string or object), cachedContentName (string), urlContext (object), modelPreferences (object).

gemini_functionCall

Sends a prompt and function declarations to the model, returning either a text response or a requested function call object (as a JSON string). Required Params: prompt (string), functionDeclarations (array). Optional Params: modelName (string), generationConfig (object), safetySettings (array), toolConfig (object).

gemini_startChat

Initiates a new stateful chat session and returns a unique sessionId. Optional Params: modelName (string), history (array), tools (array), generationConfig (object), safetySettings (array), systemInstruction (string or object), cachedContentName (string).

gemini_sendMessage

Sends a message within an existing chat session. Required Params: sessionId (string), message (string). Optional Params: generationConfig (object), safetySettings (array), tools (array), toolConfig (object), cachedContentName (string).

gemini_sendFunctionResult

Sends the result of a function execution back to a chat session. Required Params: sessionId (string), functionResponse (string). Optional Params: functionCall (object).

gemini_routeMessage

Routes a message to the most appropriate model from a provided list based on message content. Returns both the model's response and which model was selected. Required Params: message (string), models (array). Optional Params: routingPrompt (string), defaultModel (string), generationConfig (object), safetySettings (array), systemInstruction (string or object).

gemini_createCache

Creates cached content for compatible models. Required Params: contents (array), model (string). Optional Params: displayName (string), systemInstruction (string or object), ttl (string), tools (array), toolConfig (object).

gemini_listCaches

Lists existing cached content. Required Params: None. Optional Params: pageSize (number), pageToken (string).

gemini_getCache

Retrieves metadata for specific cached content. Required Params: cacheName (string).

gemini_updateCache

Updates metadata and contents for cached content. Required Params: cacheName (string), contents (array). Optional Params: displayName (string), systemInstruction (string or object), ttl (string), tools (array), toolConfig (object).

gemini_deleteCache

Deletes cached content. Required Params: cacheName (string).

gemini_generateImage

Generates images from text prompts using available image generation models. Required Params: prompt (string). Optional Params: modelName (string), resolution (string), numberOfImages (number), safetySettings (array), negativePrompt (string), stylePreset (string), seed (number), styleStrength (number).

gemini_url_analysis

Advanced URL analysis tool that fetches content from web pages and performs specialized analysis tasks. Required Params: urls (array), analysisType (string). Optional Params: query (string), extractionSchema (object), questions (array), compareBy (array), outputFormat (string), includeMetadata (boolean), fetchOptions (object), modelName (string).

mcpConnectToServer

Establishes a connection to an external MCP server and returns a connection ID. Required Params: serverId (string), connectionType (string), sseUrl (string, optional), stdioCommand (string, optional), stdioArgs (array of strings, optional), stdioEnv (object, optional).

mcpListServerTools

Lists available tools on a connected MCP server. Required Params: connectionId (string).

mcpCallServerTool

Calls a function on a connected MCP server. Required Params: connectionId (string), toolName (string), toolArgs (object). Optional Params: outputToFile (string).

mcpDisconnectFromServer

Disconnects from an external MCP server. Required Params: connectionId (string).

writeToFile

Writes content directly to a file. Required Params: filePath (string), content (string). Optional Params: overwrite (boolean).

This server provides the following MCP tools. Parameter schemas are defined using Zod for validation and description.

Validation and Error Handling: All parameters are validated using Zod schemas at both the MCP tool level and service layer, providing consistent validation, detailed error messages, and type safety. The server implements comprehensive error mapping to provide clear, actionable error messages.

Retry Logic: API requests automatically use exponential backoff retry for transient errors (network issues, rate limits, timeouts), improving reliability for unstable connections. The retry mechanism includes configurable parameters for maximum attempts, delay times, and jitter to prevent thundering herd effects.

Note on Optional Parameters: Many tools accept complex optional parameters (e.g., generationConfig, safetySettings, toolConfig, history, functionDeclarations, contents). These parameters are typically objects or arrays whose structure mirrors the types defined in the underlying @google/genai SDK (v0.10.0). For the exact structure and available fields within these complex parameters, please refer to:
1. The corresponding src/tools/*Params.ts file in this project.
2. The official Google AI JS SDK Documentation.

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "gemini ai": {
            "env": {
                "MCP_SERVER_HOST": "localhost",
                "MCP_SERVER_PORT": "8080",
                "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash",
                "ALLOWED_OUTPUT_PATHS": "/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs",
                "MCP_CONNECTION_TOKEN": "YOUR_GENERATED_CONNECTION_TOKEN",
                "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY"
            },
            "args": [
                "/path/to/mcp-gemini-server/dist/server.js"
            ],
            "command": "node"
        }
    }
}

Linux

{
    "env": {
        "MCP_SERVER_HOST": "localhost",
        "MCP_SERVER_PORT": "8080",
        "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash",
        "ALLOWED_OUTPUT_PATHS": "/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs",
        "MCP_CONNECTION_TOKEN": "YOUR_GENERATED_CONNECTION_TOKEN",
        "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY"
    },
    "args": [
        "/path/to/mcp-gemini-server/dist/server.js"
    ],
    "command": "node"
}

Macos

{
    "env": {
        "MCP_SERVER_HOST": "localhost",
        "MCP_SERVER_PORT": "8080",
        "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash",
        "ALLOWED_OUTPUT_PATHS": "/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs",
        "MCP_CONNECTION_TOKEN": "YOUR_GENERATED_CONNECTION_TOKEN",
        "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY"
    },
    "args": [
        "/path/to/mcp-gemini-server/dist/server.js"
    ],
    "command": "node"
}

Windows

{
    "env": {
        "MCP_SERVER_HOST": "localhost",
        "MCP_SERVER_PORT": "8080",
        "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash",
        "ALLOWED_OUTPUT_PATHS": "/var/opt/mcp-gemini-server/outputs,/tmp/mcp-gemini-outputs",
        "MCP_CONNECTION_TOKEN": "YOUR_GENERATED_CONNECTION_TOKEN",
        "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY"
    },
    "args": [
        "/c",
        "node",
        "/path/to/mcp-gemini-server/dist/server.js"
    ],
    "command": "cmd"
}

MseeP.ai Security Assessment Badge

MCP Gemini Server

Table of Contents

- Overview - File Uploads vs URL-Based Analysis - Features - Prerequisites - Installation & Setup - Configuration - Available Tools - Usage Examples - Supported Multimedia Analysis Use Cases - MCP Gemini Server and Gemini SDK's MCP Function Calling - Environment Variables - Security Considerations - Error Handling - Development and Testing - Contributing - Code Review Tools - Server Features - Known Issues

Overview

This project provides a dedicated MCP (Model Context Protocol) server that wraps the @google/genai SDK (v0.10.0). It exposes Google's Gemini model capabilities as standard MCP tools, allowing other LLMs (like Claude) or MCP-compatible systems to leverage Gemini's features as a backend workhorse.

This server aims to simplify integration with Gemini models by providing a consistent, tool-based interface managed via the MCP standard. It supports the latest Gemini models including gemini-1.5-pro-latest, gemini-1.5-flash, and gemini-2.5-pro models.

Important Note: This server does not support direct file uploads. Instead, it focuses on URL-based multimedia analysis for images and videos. For text-based content processing, use the standard content generation tools.

File Uploads vs URL-Based Analysis

❌ Not Supported: Direct File Uploads

This MCP Gemini Server does not support the following file upload operations:

- Local file uploads: Cannot upload files from your local filesystem to Gemini
- Base64 encoded files: Cannot process base64-encoded image or video data
- Binary file data: Cannot handle raw file bytes or binary data
- File references: Cannot process file IDs or references from uploaded content
- Audio file uploads: Cannot upload and transcribe audio files directly

Why File Uploads Are Not Supported:
- Simplified architecture focused on URL-based processing
- Enhanced security by avoiding file handling complexities
- Reduced storage and bandwidth requirements
- Streamlined codebase maintenance

✅ Fully Supported: URL-Based Multimedia Analysis

This server fully supports analyzing multimedia content from publicly accessible URLs:

Image Analysis from URLs:
- Public image URLs: Analyze images hosted on any publicly accessible web server
- Supported formats: PNG, JPEG, WebP, HEIC, HEIF via direct URL access
- Multiple images: Process multiple image URLs in a single request
- Security validation: Automatic URL validation and security screening

YouTube Video Analysis:
- Public YouTube videos: Full analysis of any public YouTube video content
- Video understanding: Extract insights, summaries, and detailed analysis
- Educational content: Perfect for analyzing tutorials, lectures, and educational videos
- Multiple videos: Process multiple YouTube URLs (up to 10 per request with Gemini 2.5+)

Web Content Processing:
- HTML content: Analyze and extract information from web pages
- Mixed media: Combine text content with embedded images and videos
- Contextual analysis: Process URLs alongside text prompts for comprehensive analysis

Alternatives for Local Content

If you have local files to analyze:

1. Host on a web server: Upload your files to a public web server and use the URL
2. Use cloud storage: Upload to services like Google Drive, Dropbox, or AWS S3 with public access
3. Use GitHub: Host images in a GitHub repository and use the raw file URLs
4. Use image hosting services: Upload to services like Imgur, ImageBB, or similar platforms

For audio content:
- Use external transcription services (Whisper API, Google Speech-to-Text, etc.)
- Upload audio to YouTube and analyze the resulting video URL
- Use other MCP servers that specialize in audio processing

Features

Core Generation: Standard (gemini_generateContent) and streaming (gemini_generateContentStream) text generation with support for system instructions and cached content.
Function Calling: Enables Gemini models to request the execution of client-defined functions (gemini_functionCall).
Stateful Chat: Manages conversational context across multiple turns (gemini_startChat, gemini_sendMessage, gemini_sendFunctionResult) with support for system instructions, tools, and cached content.
URL-Based Multimedia Analysis: Analyze images from public URLs and YouTube videos without file uploads. Direct file uploads are not supported.
Caching: Create, list, retrieve, update, and delete cached content to optimize prompts with support for tools and tool configurations.
Image Generation: Generate images from text prompts using Gemini 2.0 Flash Experimental (gemini_generateImage) with control over resolution, number of images, and negative prompts. Also supports the latest Imagen 3.1 model for high-quality dedicated image generation with advanced style controls. Note that Gemini 2.5 models (Flash and Pro) do not currently support image generation.
URL Context Processing: Fetch and analyze web content directly from URLs with advanced security, caching, and content processing capabilities.
gemini_generateContent: Enhanced with URL context support for including web content in prompts
gemini_generateContentStream: Streaming generation with URL context integration
gemini_url_analysis: Specialized tool for advanced URL content analysis with multiple analysis types
MCP Client: Connect to and interact with external MCP servers.
mcpConnectToServer: Establishes a connection to an external MCP server.
mcpListServerTools: Lists available tools on a connected MCP server.
mcpCallServerTool: Calls a function on a connected MCP server, with an option for file output.
mcpDisconnectFromServer: Disconnects from an external MCP server.
writeToFile: Writes content directly to files within allowed directories.

Prerequisites

Node.js (v18 or later)
An API Key from Google AI Studio (<https://aistudio.google.com/app/apikey>).
* Important: The Caching API is only compatible with Google AI Studio API keys and is not supported when using Vertex AI credentials. This server does not currently support Vertex AI authentication.

Installation & Setup

Installing Manually

1. Clone/Place Project: Ensure the mcp-gemini-server project directory is accessible on your system.
2. Install Dependencies: Navigate to the project directory in your terminal and run:

    npm install
    

3. Build Project: Compile the TypeScript source code:

    npm run build
    

This command uses the TypeScript compiler (tsc) and outputs the JavaScript files to the ./dist directory (as specified by outDir in tsconfig.json). The main server entry point will be dist/server.js.
4. Generate Connection Token: Create a strong, unique connection token for secure communication between your MCP client and the server. This is a shared secret that you generate and configure on both the server and client sides.

Generate a secure token using one of these methods:

Option A: Using Node.js crypto (Recommended)

    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.