Skip to content
Back to search

gemini-cli-mcp-server

A production-ready Model Context Protocol (MCP) server that bridges Google's Gemini CLI with MCP-compatible clients like Claude Code and Claude Desktop. This enterprise-grade Gemini MCP server…

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/centminmod--gemini-cli-mcp-server/badge.svg)](/listings/centminmod--gemini-cli-mcp-server)

HTML

<a href="/listings/centminmod--gemini-cli-mcp-server"><img src="/api/listings/centminmod--gemini-cli-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

Prerequisites

- **Python 3.10+** - Required for MCP SDK compatibility - **Gemini CLI** - Google's command-line tool for Gemini AI - **uv** (recommended) or pip for package management

Linux Setup

# Install uv (recommended package manager)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone the repository
git clone https://github.com/centminmod/gemini-cli-mcp-server.git
cd gemini-cli-mcp-server

# Create and activate virtual environment
uv venv
source .venv/bin/activate

# Install dependencies
uv pip install -r requirements.txt

# Install and configure Gemini CLI
npm install -g @google-ai/gemini-cli
gemini config set api_key YOUR_GEMINI_API_KEY

# Verify installation
gemini --version
python mcp_server.py --help

macOS Setup

# Install uv via Homebrew (or use curl installer above)
brew install uv

# Clone the repository
git clone https://github.com/centminmod/gemini-cli-mcp-server.git
cd gemini-cli-mcp-server

# Create and activate virtual environment
uv venv
source .venv/bin/activate

# Install dependencies
uv pip install -r requirements.txt

# Install Gemini CLI (if not already installed)
npm install -g @google-ai/gemini-cli
# Or via Homebrew: brew install gemini-cli

# Configure Gemini CLI
gemini config set api_key YOUR_GEMINI_API_KEY

# Verify installation
gemini --version
python mcp_server.py --help

Alternative Installation (pip)

# Using standard Python tools
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

# Configure Gemini CLI
gemini config set api_key YOUR_GEMINI_API_KEY

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,734 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. [![GitHub stars](https://img.shields.io/github/stars/centminmod/gemini-cli-mcp-server.svg?style=flat-square)](https://github.com/centminmod/gemini-cli-mcp-server/stargazers) [![GitHub forks](https://img.shields.io/github/forks/centminmod/gemini-cli-mcp-server.svg?style=flat-square)](https://github.com/centminmod/gemini-cli-mcp-server/network) [![GitHub issues](https://img.shields.io/github/issues/centminmod/gemini-cli-mcp-server.svg?style=flat-square)](https://github.com/centminmod/gemini-cli-mcp-server/issues)
  2. # Gemini CLI MCP Server
  3. A production-ready Model Context Protocol (MCP) server that bridges Google's Gemini CLI with MCP-compatible clients like Claude Code and Claude Desktop. This enterprise-grade Gemini MCP server features OpenRouter AI API integration for access to 400+ AI models and provides 33 specialized tools for seamless multi-AI workflows between Claude, Gemini, and 400+ additional models.
  4. On Claude Desktop:
  5. ![Claude Desktop with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo3-1.png)
  6. ![Claude Desktop with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo3-2.png)
  7. **Example 1:** Claude Code calling one of the 33 MCP tools, `gemini_prompt`:
  8. ```bash
  9. @gemini_prompt("Analyse @mcp_server.py codebase and modules explaining what this code does, think deeply before responding")
  10. ```
  11. ![gemini-cli-mcp-server screenshot](/screenshots/claude-code-gemini-cli-mcp-prompt-test-020725-1.png)
  12. **Example 2:** Claude Code Custom Slash Command Prompt + Claude & Gemini CLI MCP Server Teamwork
  13. Setup Claude Code custom slash command prompt `/test-gemini-prompt-analyse-teamwork` within Git repo project at `.claude/commands/test-mcp/test-gemini-prompt-analyse-teamwork.md`. When you invoke this command, Claude Code Sonnet 4 first performs a deep analysis of the Gemini CLI MCP server code. It then delegates the same codebase to Google Gemini 2.5 Flash via the MCP tool’s `@gemini_prompt()` (note that Flash may be rate-limited on free tiers). Finally, Claude Code Sonnet 4 synthesizes both sets of insights into a single, consolidated report.
  14. Click `View Screenshots` to see example.
  15. <details>
  16. <summary>View Screenshots: Claude & Gemini Teamwork Analysis</summary>
  17. ![Claude Code using custom slash command prompt and Gemini CLI MCP server for teamwork](/screenshots/claude-code-command-shortcut-claude-gemini-mcp-teamwork-analysis2-1.png)
  18. ![Claude Code using custom slash command prompt and Gemini CLI MCP server for teamwork](/screenshots/claude-code-command-shortcut-claude-gemini-mcp-teamwork-analysis2-2.png)
  19. ![Claude Code using custom slash command prompt and Gemini CLI MCP server for teamwork](/screenshots/claude-code-command-shortcut-claude-gemini-mcp-teamwork-analysis2-3.png)
  20. ![Claude Code using custom slash command prompt and Gemini CLI MCP server for teamwork](/screenshots/claude-code-command-shortcut-claude-gemini-mcp-teamwork-analysis2-4.png)
  21. </details>
  22. **Example 3:** Claude Code Custom Slash Command Prompt + Claude & Gemini CLI MCP Server Comphrensive Review
  23. Setup Claude Code custom slash command prompt `.claude/commands/workflow-orchestrators/comprehensive-review.md` within Git repo project at `.claude/commands/workflow-orchestrators/comprehensive-review.md`. When you invoke this command, Claude Code Sonnet 4 first performs a comphrensive review of the Gemini CLI MCP server code and writes a report. It then asks Google Gemini 2.5 Flash via the MCP tool’s `@gemini_prompt()` (note that Flash may be rate-limited on free tiers) to verify and evaluate the generated report and add it's findings to the report.
  24. Click `View Screenshots` to see example.
  25. <details>
  26. <summary>View Screenshots: Comprehensive Review Workflow</summary>
  27. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-command-shortcut-comphrensive-review-1.png)
  28. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-command-shortcut-comphrensive-review-2.png)
  29. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-command-shortcut-comphrensive-review-3.png)
  30. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-command-shortcut-comphrensive-review-4.png)
  31. </details>
  32. **Example 4:** Extended: Claude Code Custom Slash Command Prompt + Claude & Gemini CLI MCP Server Comphrensive Review + Claude Response To Gemini Analysis.
  33. Setup Claude Code custom slash command prompt `.claude/commands/workflow-orchestrators/comprehensive-review.md` within Git repo project at `.claude/commands/workflow-orchestrators/comprehensive-review.md`. When you invoke this command, Claude Code Sonnet 4 first performs a comphrensive review of the Gemini CLI MCP server code and writes a report. It then asks Google Gemini 2.5 Flash via the MCP tool’s `@gemini_prompt()` (note that Flash may be rate-limited on free tiers) to verify and evaluate the generated report and add it's findings to the report. Then finally ask Claude to respond to Gemini CLI MCP server's analysis.
  34. Click `View Screenshots` to see example.
  35. <details>
  36. <summary>View Screenshots: Extended Analysis with Claude Response</summary>
  37. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-comphrensive-tasklist-thinking-slash-command-1.png)
  38. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-comphrensive-tasklist-thinking-slash-command-2.png)
  39. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-comphrensive-tasklist-thinking-slash-command-3.png)
  40. ![Claude Code using custom slash command prompt and Gemini CLI MCP server verification](/screenshots/claude-code-comphrensive-tasklist-thinking-slash-command-4.png)
  41. </details>
  42. **Example 5:** Claude Code with Gemini CLI MCP Server With OpenRouter API support
  43. Extended Gemini CLI MCP server with Openrouter API support to access 400+ LLM models. Click `View Screenshots` to see example of Claude Code chatting with Openai GP4 4.1-nano, Mistral AI devstral-small and DeepSeek R1 0528.
  44. <details>
  45. <summary>View Screenshots: Claude Code with Gemini CLI MCP Server With OpenRouter API support</summary>
  46. ![Claude Code with Gemini CLI MCP Server With OpenRouter API support](/screenshots/claude-code-gemini-cli-mcp-with-openrouter-demo-1.png)
  47. ![Claude Code with Gemini CLI MCP Server With OpenRouter API support](/screenshots/claude-code-gemini-cli-mcp-with-openrouter-demo-3.png)
  48. </details>
  49. **Example 6:** Claude Code with Gemini CLI MCP Server AI Collaboration
  50. The Gemini CLI MCP server includes OpenRouter API support for accessing 400+ LLM models. The `@gemini_ai_collaboration` MCP tool enables multiple AI models to engage in structured conversations, collaborations, or debates. This allows Gemini 2.5 models (via Gemini CLI) to collaborate with OpenRouter-based models like OpenAI GPT-4, Anthropic Claude, and others.
  51. In the example below, Gemini 2.5 Flash debates with OpenAI GPT-4.1-mini through Claude Code. Claude Code (Sonnet 4) orchestrates the debate and has full access to the conversation context, enabling sophisticated multi-AI workflows.
  52. ~~~bash
  53. @gemini_ai_collaboration(
  54. collaboration_mode="debate",
  55. content="Should we use microservices or monolith?",
  56. models="gemini-2.5-flash,openai/gpt-4.1-mini",
  57. rounds=4,
  58. debate_style="constructive"
  59. )
  60. ~~~
  61. ![Claude Code with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo-4.png)
  62. Using Gemini CLI MCP in Claude Desktop with same MCP tool:
  63. ![Claude Desktop with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo3-4.png)
  64. ![Claude Desktop with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo3-5.png)
  65. Or `validation` mode with Gemini 2.5 Flash, OpenAI GPT-4.1-mini and Anthropic Claude 3 Haiku.
  66. ~~~bash
  67. @gemini_ai_collaboration(
  68. collaboration_mode="validation",
  69. content="@mcp_server.py", # or multiple files
  70. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/cla
  71. ude-3-haiku",
  72. validation_criteria="code_quality,performance,security,mai
  73. ntainability,best_practices,documentation",
  74. confidence_threshold=0.8,
  75. consensus_method="weighted_majority",
  76. conflict_resolution="detailed_analysis",
  77. context="Code review for production deployment",
  78. budget_limit=5.00
  79. )
  80. ~~~
  81. ![Claude Code with Gemini CLI MCP Server With OpenRouter AI Collaboration](/screenshots/claude-code-gemini-mcp-openrouter-ai-collaboration-demo2-3.png)
  82. **Example 7:** Claude Code natural language prompt calling Gemini CLI MCP server's Openrouter LLM model, OpenAI GPT 4.1-nano.
  83. Claude Code natural language prompt calling Gemini CLI MCP server's Openrouter LLM model, OpenAI GPT 4.1-nano.
  84. Click `View Screenshots` to see example.
  85. <details>
  86. <summary>View Screenshots: Extended Analysis with Claude Response</summary>
  87. Seems there is a bug in that it says it gets `4o-mini` but I wanted/d`o get 4.1-nano` model as asked.
  88. ![Claude Code using Gemini CLI MCP server's OpenRouter AI integration](/screenshots/claude-code-gemini-cli-mcp-server-natural-language-call-openai-gpt-4.1-nano-opinion-1.png)
  89. ![Claude Code using Gemini CLI MCP server's OpenRouter AI integration](/screenshots/claude-code-gemini-cli-mcp-server-natural-language-call-openai-gpt-4.1-nano-opinion-2.png)
  90. OpenRouter Usage Activity for OpenAI GPT 4.1-nano
  91. ![Claude Code using Gemini CLI MCP server's OpenRouter AI integration](/screenshots/claude-code-gemini-cli-mcp-server-natural-language-call-openai-gpt-4.1-nano-opinion-3.png)
  92. Gemini CLI MCP server uses Cloudflare AI Gateway proxies for Gemini CLI itself and also for OpenRouter integration. But AI Gateway records it as 4.1-mini and not 4.1-nano.
  93. ![Claude Code using Gemini CLI MCP server's OpenRouter AI integration](/screenshots/claude-code-gemini-cli-mcp-server-natural-language-call-openai-gpt-4.1-nano-opinion-4.png)
  94. ![Claude Code using Gemini CLI MCP server's OpenRouter AI integration](/screenshots/claude-code-gemini-cli-mcp-server-natural-language-call-openai-gpt-4.1-nano-opinion-5.png)
  95. </details>
  96. ## 🚀 Key Features
  97. - **33 Specialized MCP Tools** - Complete toolset for multi-AI integration across 6 tool categories
  98. - **400+ AI Models** - Access to OpenAI, Anthropic, Meta, Google, and 20+ providers via OpenRouter integration
  99. - **Enterprise Architecture** - Refactored modular design with 83 Python files organized across multiple specialized modules
  100. - **Conversation History** - Stateful multi-turn conversations with Redis-backed storage and cross-platform support
  101. - **Dynamic Token Limits** - Tool-specific limits from 100K-800K characters with model-aware scaling
  102. - **Multi-AI Workflows** - Purpose-built tools for plan evaluation, code review, and cross-platform collaboration
  103. - **@filename Support** - Direct file reading with intelligent large file handling strategies for 32 tools
  104. - **Enterprise Security** - 22 critical security fixes with multi-layer defense and real-time protection
  105. - **Production Ready** - 2,500+ test cases, enterprise monitoring with OpenTelemetry + Prometheus
  106. - **High Concurrency** - Async architecture supporting 1,000-10,000+ concurrent requests with 10-100x improvement
  107. ## 📋 Table of Contents
  108. - [Architecture Overview](#%EF%B8%8F-architecture-overview)
  109. - [Tool Suite](#%EF%B8%8F-tool-suite)
  110. - [Core Gemini Tools](#core-gemini-tools-6)
  111. - [System Tools](#system-tools-3)
  112. - [Analysis Tools](#analysis-tools-5)
  113. - [Conversation Tools](#conversation-tools-5)
  114. - [Specialized Code Review Tools](#specialized-code-review-tools-3)
  115. - [Content Comparison Tools](#content-comparison-tools-1)
  116. - [AI Collaboration Tools](#ai-collaboration-tools-1)
  117. - [OpenRouter Tools](#openrouter-tools-6)
  118. - [Installation](#-installation)
  119. - [MCP Client Configuration](#%EF%B8%8F-mcp-client-configuration)
  120. - [Usage Examples](#-usage-examples)
  121. - [Advanced Features](#-advanced-features)
  122. - [Configuration](#%EF%B8%8F-configuration)
  123. - [Performance](#-performance)
  124. - [Testing](#-testing)
  125. - [Troubleshooting](#-troubleshooting)
  126. ## 🏗️ Architecture Overview
  127. The Gemini CLI MCP Server features a modular, enterprise-grade architecture designed for reliability, performance, and maintainability. Built on proven architectural patterns and production-ready design decisions.
  128. ```text
  129. ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
  130. │ Claude Code │ ← → │ MCP Protocol │ ← → │ Gemini CLI │
  131. │ MCP Client │ │ (JSON-RPC 2.0) │ │ Integration │
  132. └─────────────────┘ └──────────────────┘ └─────────────────┘
  133. ↑ ↑ ↑
  134. ┌─────────┐ ┌─────────────┐ ┌─────────────┐
  135. │ 33 MCP │ │ FastMCP │ │ Google │
  136. │ Tools │ │ Server │ │ Gemini AI │
  137. └─────────┘ └─────────────┘ └─────────────┘
  138. ```
  139. ### Core Components
  140. **🔧 Refactored Modular Architecture (83 Python files across multiple specialized modules)**:
  141. **Core Server Layer (6 modules):**
  142. - **`mcp_server.py`** - Streamlined main coordinator with tool registration pattern (741 lines, 83.5% reduction from 4,502 lines)
  143. - **`modules/core/mcp_core_tools.py`** - Pure MCP tool implementations for core Gemini CLI tools (487 lines)
  144. - **`modules/core/mcp_collaboration_engine.py`** - AI collaboration system with advanced workflow modes (1,103 lines)
  145. - **`modules/core/mcp_service_implementations.py`** - System and service tools coordination layer (1,228 lines)
  146. - **`modules/core/mcp_code_review_tools.py`** - Specialized code review and analysis tools (386 lines)
  147. - **`modules/core/mcp_content_comparison_tools.py`** - Multi-source content comparison capabilities (299 lines)
  148. **Configuration & Infrastructure (7 modules):**
  149. - **`modules/config/gemini_config.py`** - Main configuration interface with modular imports (1,835 lines)
  150. - **`modules/config/environment_config.py`** - Environment variable parsing and validation (NEW)
  151. - **`modules/config/model_config.py`** - Gemini model definitions and scaling configuration (NEW)
  152. - **`modules/config/feature_config.py`** - Feature flags, OpenRouter, monitoring, and conversations (NEW)
  153. - **`modules/utils/gemini_utils.py`** - Core utilities and helper functions (3,996 lines)
  154. - **`modules/services/conversation_manager.py`** - Stateful conversation management with Redis support (1,048 lines)
  155. - **`modules/services/monitoring.py`** - OpenTelemetry, Prometheus, and health check integration (1,534 lines)
  156. **Integration Modules (2 modules):**
  157. - **`modules/services/openrouter_client.py`** - OpenRouter API client for 400+ AI models (881 lines)
  158. - **`modules/services/redis_cache.py`** - Redis caching with graceful memory fallback (914 lines)
  159. **Template System (17 modules):**
  160. - **`prompts/`** - Template module with TTL caching and integrity verification
  161. - Core templates: template_loader.py, base_template.py, eval_template.py, review_template.py, verify_template.py, summarize_template.py
  162. - Collaboration templates: debate_template.py, sequential_template.py, validation_template.py
  163. - Code review templates: code_review_template.py, extract_structured_template.py, git_diff_review_template.py (NEW)
  164. - Content analysis templates: content_comparison_template.py (NEW)
  165. - Plus interface and supporting files
  166. **Security Framework (6 modules):**
  167. - **`security/`** - Enterprise security framework with 22 critical security fixes
  168. - Includes: api_key_manager.py, credential_sanitizer.py, pattern_detector.py, security_monitor.py, security_validator.py, jsonrpc_validator.py
  169. **Rate Limiting & Utility Scripts (5 modules):**
  170. - **Rate Limiting Framework** (3 modules): per_model_rate_limiter.py, rate_limit_config.py, rate_limit_integration.py
  171. - **Utility Scripts** (2 modules): rotate_openrouter_key.py, security_audit.py
  172. **📝 Template System Architecture**:
  173. ```text
  174. prompts/
  175. ├── __init__.py # Module exports and imports
  176. ├── template_loader.py # Template loading with 30-min TTL caching
  177. ├── base_template.py # Common components and utilities
  178. ├── summarize_template.py # Content summarization templates
  179. ├── review_template.py # Code review templates
  180. ├── eval_template.py # Plan evaluation templates
  181. └── verify_template.py # Solution verification templates
  182. ```
  183. **Key Template Features**:
  184. - **Template Extraction**: Large prompt templates separated from function logic for maintainability
  185. - **TTL Caching**: 30-minute cache for template loading with performance optimization
  186. - **Modular Design**: Each dual-AI workflow tool has dedicated template files
  187. - **Function Size Reduction**: ~70% average reduction in function complexity
  188. - **Performance**: Cached templates improve response times for repeated operations
  189. **⚡ Enterprise Features**:
  190. - **10-100x Concurrency Improvement**: Lock-free cache operations with atomic get-or-set patterns
  191. - **Advanced Caching System**: TTL-based caching with template integrity verification using SHA-256 hashing
  192. - **Process Pooling**: Configurable ProcessPoolExecutor reducing 100-500ms subprocess creation overhead
  193. - **Automatic Model Fallback**: gemini-2.5-pro → gemini-2.5-flash with intelligent quota management
  194. - **Enterprise Monitoring**: OpenTelemetry tracing + Prometheus metrics with graceful degradation
  195. - **90% Rate Limiting Optimization**: Deque-based O(1) algorithms with memory leak protection
  196. **🛡️ Security & Reliability**:
  197. - **22 Critical Security Fixes**: Session-based rate limiting, template integrity validation, enhanced credential sanitization, JSON-RPC validation, subprocess injection protection
  198. - **Multi-layer Defense**: 25+ attack categories with compiled regex patterns for real-time protection
  199. - **Security Pattern Detection**: Protection against command injection, path traversal, XSS, prompt injection, information disclosure
  200. - **Memory-Safe Operations**: Bounded caches with automatic cleanup and O(1) operations
  201. - **JSON-RPC Security Middleware**: Protocol-level validation with request size limits and nesting depth protection
  202. - **Structured Error Handling**: Comprehensive error taxonomy with sanitized client responses
  203. - **Enterprise Compliance**: OWASP Top 10 aligned with NIST security guidelines
  204. ### Key Architectural Decisions
  205. **🏛️ Design Philosophy**:
  206. - **FastMCP Framework**: Official MCP Python SDK with JSON-RPC 2.0 compliance
  207. - **Dual Input Support**: Both string and list command inputs for security and compatibility
  208. - **Direct Subprocess Execution**: Avoids shell injection vulnerabilities
  209. - **Structured Error Classification**: 11 error codes with machine-readable responses
  210. - **Multi-Tier TTL Caching**: Different cache durations optimized for each use case
  211. - **Full Async/Await**: High-concurrency architecture supporting 1,000-10,000+ requests
  212. - **Configurable Fallback**: Environment-driven behavior for empty command handling
  213. - **Exponential Backoff Retry**: Intelligent retry logic with jitter for transient errors
  214. - **Input Validation**: Multi-layer validation with length limits and sanitization
  215. - **Information Disclosure Prevention**: Sanitized client responses with detailed server logging
  216. ## 🛠️ Tool Suite
  217. The server provides 33 specialized MCP tools organized into six categories:
  218. ### Core Gemini Tools (6)
  219. #### `gemini_cli`
  220. Execute any Gemini CLI command directly with comprehensive error handling.
  221. ```python
  222. gemini_cli(command="--prompt 'Hello world'")
  223. gemini_cli(command="--model gemini-2.5-pro --prompt 'Explain AI'")
  224. ```
  225. #### `gemini_help`
  226. Get cached Gemini CLI help information (30-minute TTL).
  227. ```python
  228. gemini_help()
  229. ```
  230. #### `gemini_version`
  231. Get cached Gemini CLI version information (30-minute TTL).
  232. ```python
  233. gemini_version()
  234. ```
  235. #### `gemini_prompt`
  236. Send prompts with structured parameters and validation (100,000 char limit).
  237. ```python
  238. gemini_prompt(
  239. prompt="Explain quantum computing",
  240. model="gemini-2.5-flash",
  241. sandbox=False,
  242. debug=False
  243. )
  244. ```
  245. #### `gemini_models`
  246. List all available Gemini AI models.
  247. ```python
  248. gemini_models()
  249. ```
  250. #### `gemini_metrics`
  251. Get comprehensive server performance metrics and statistics.
  252. ```python
  253. gemini_metrics()
  254. ```
  255. ### System Tools (3)
  256. #### `gemini_sandbox`
  257. Execute prompts in sandbox mode for code execution (200,000 char limit).
  258. ```python
  259. gemini_sandbox(
  260. prompt="Write and run a Python script to analyze data",
  261. model="gemini-2.5-pro",
  262. sandbox_image="python:3.11-slim" # optional
  263. )
  264. ```
  265. #### `gemini_cache_stats`
  266. Get cache statistics for all cache backends.
  267. ```python
  268. gemini_cache_stats()
  269. ```
  270. #### `gemini_rate_limiting_stats`
  271. Get comprehensive rate limiting and quota statistics.
  272. ```python
  273. gemini_rate_limiting_stats()
  274. ```
  275. ### Analysis Tools (5)
  276. #### `gemini_summarize`
  277. Summarize content with focus-specific analysis (400,000 char limit).
  278. ```python
  279. gemini_summarize(
  280. content="Your code or text content here",
  281. focus="architecture and design patterns",
  282. model="gemini-2.5-pro"
  283. )
  284. ```
  285. #### `gemini_summarize_files`
  286. File-based summarization optimized for @filename syntax (800,000 char limit).
  287. **Key Advantages over `gemini_summarize`**:
  288. - **2x Higher Limit**: 800K vs 400K characters for large codebases
  289. - **@filename Optimized**: Purpose-built for direct file reading
  290. - **Token Efficiency**: 50-70% improvement with lightweight prompts
  291. - **Enterprise Scale**: Handles massive multi-directory projects
  292. ```python
  293. gemini_summarize_files(
  294. files="@src/ @docs/ @tests/", # @filename syntax
  295. focus="complete system analysis", # optional
  296. model="gemini-2.5-pro" # optional
  297. )
  298. ```
  299. #### `gemini_eval_plan`
  300. Evaluate Claude Code implementation plans (500,000 char limit).
  301. ```python
  302. gemini_eval_plan(
  303. plan="Implementation plan from Claude Code",
  304. context="Node.js REST API with MongoDB",
  305. requirements="Must support 10,000 concurrent users",
  306. model="gemini-2.5-pro"
  307. )
  308. ```
  309. #### `gemini_review_code`
  310. Review specific code suggestions with detailed analysis (300,000 char limit).
  311. ```python
  312. gemini_review_code(
  313. code="Code snippet or @filename to review",
  314. purpose="Security review of authentication",
  315. context="Express.js REST API",
  316. language="javascript",
  317. model="gemini-2.5-pro"
  318. )
  319. ```
  320. #### `gemini_verify_solution`
  321. Comprehensive verification of complete solutions (800,000 char limit).
  322. ```python
  323. gemini_verify_solution(
  324. solution="Complete implementation including code, tests, docs",
  325. requirements="Original requirements specification",
  326. test_criteria="Performance and security criteria",
  327. context="Production deployment environment",
  328. model="gemini-2.5-pro"
  329. )
  330. ```
  331. ### Conversation Tools (5)
  332. #### `gemini_start_conversation`
  333. Start a new conversation with ID for stateful interactions.
  334. ```python
  335. gemini_start_conversation(
  336. title="Python Development Help",
  337. description="Ongoing assistance with Python project",
  338. tags="python,development",
  339. expiration_hours=24
  340. )
  341. ```
  342. #### `gemini_continue_conversation`
  343. Continue an existing conversation with context history.
  344. ```python
  345. gemini_continue_conversation(
  346. conversation_id="conv_12345",
  347. prompt="How do I optimize this function?",
  348. model="gemini-2.5-flash"
  349. )
  350. ```
  351. #### `gemini_list_conversations`
  352. List active conversations with metadata.
  353. ```python
  354. gemini_list_conversations(
  355. limit=20,
  356. status_filter="active"
  357. )
  358. ```
  359. #### `gemini_clear_conversation`
  360. Clear/delete a specific conversation.
  361. ```python
  362. gemini_clear_conversation(conversation_id="conv_12345")
  363. ```
  364. #### `gemini_conversation_stats`
  365. Get conversation system statistics and health.
  366. ```python
  367. gemini_conversation_stats()
  368. ```
  369. ### Specialized Code Review Tools (3)
  370. #### `gemini_code_review`
  371. Comprehensive code analysis with structured output (NEW).
  372. ```python
  373. gemini_code_review(
  374. code="Your code to review",
  375. language="python", # optional, auto-detected
  376. focus_areas="security,performance,quality,best_practices", # optional
  377. severity_threshold="info", # optional: info, warning, error, critical
  378. output_format="structured" # optional: structured, markdown, json
  379. )
  380. ```
  381. #### `gemini_extract_structured`
  382. Extract structured data using JSON schemas (NEW).
  383. ```python
  384. # Define a schema for code analysis
  385. schema = {
  386. "type": "object",
  387. "properties": {
  388. "functions": {"type": "array"},
  389. "classes": {"type": "array"},
  390. "issues": {"type": "array"}
  391. }
  392. }
  393. gemini_extract_structured(
  394. content="Code or text to analyze",
  395. schema=json.dumps(schema),
  396. examples="Optional examples of expected output", # optional
  397. strict_mode=True, # optional
  398. model="gemini-2.5-flash" # optional
  399. )
  400. ```
  401. #### `gemini_git_diff_review`
  402. Analyze git diffs with contextual feedback (NEW).
  403. ```python
  404. gemini_git_diff_review(
  405. diff="Git diff content or patch",
  406. context_lines=3, # optional
  407. review_type="comprehensive", # optional: comprehensive, security_only, performance_only, quick
  408. base_branch="main", # optional
  409. commit_message="Fix authentication bug" # optional
  410. )
  411. ```
  412. ### Content Comparison Tools (1)
  413. #### `gemini_content_comparison`
  414. Advanced multi-source content comparison and analysis (NEW).
  415. ```python
  416. # Compare documentation versions
  417. gemini_content_comparison(
  418. sources='["@README.md", "@docs/README.md", "https://github.com/user/repo/README.md"]',
  419. comparison_type="semantic", # semantic, textual, structural, factual, code
  420. output_format="structured", # structured, matrix, summary, detailed, json
  421. include_metrics=True, # optional, include similarity scores
  422. focus_areas="completeness,accuracy,structure" # optional, what to focus on
  423. )
  424. # Code version analysis
  425. gemini_content_comparison(
  426. sources='["@src/auth_v1.py", "@src/auth_v2.py"]',
  427. comparison_type="code",
  428. output_format="detailed",
  429. focus_areas="differences,security,performance"
  430. )
  431. ```
  432. ### AI Collaboration Tools (1)
  433. #### `gemini_ai_collaboration`
  434. Enhanced multi-platform AI collaboration with cross-platform capabilities.
  435. ```python
  436. # Sequential analysis pipeline
  437. gemini_ai_collaboration(
  438. collaboration_mode="sequential",
  439. content="Your task or code to analyze",
  440. models="gemini-2.5-flash,openai/gpt-4.1-nano,anthropic/claude-3-haiku",
  441. pipeline_stages="analysis,security_review,optimization,final_validation"
  442. )
  443. # Multi-round AI debate
  444. gemini_ai_collaboration(
  445. collaboration_mode="debate",
  446. content="Should we use microservices or monolith?",
  447. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku",
  448. rounds=4,
  449. debate_style="constructive"
  450. )
  451. ```
  452. #### Complete Parameter Reference for `gemini_ai_collaboration`
  453. **Available Collaboration Modes:**
  454. - **`sequential`** - Progressive refinement through ordered analysis pipeline
  455. - **`debate`** - Multi-round discussions with consensus building
  456. - **`validation`** - Cross-platform validation with conflict resolution
  457. **Available Debate Styles (for debate mode):**
  458. - **`constructive`** (default) - Focus on building understanding rather than winning arguments
  459. - **`adversarial`** - Challenge assumptions and arguments rigorously
  460. - **`collaborative`** - Work together to explore topics comprehensively
  461. - **`socratic`** - Use questioning to explore underlying assumptions
  462. - **`devil_advocate`** - Deliberately argue for challenging positions
  463. **Universal Parameters:**
  464. - **`collaboration_mode`** (required): `sequential` | `debate` | `validation`
  465. - **`content`** (required): Content to be analyzed/processed
  466. - **`models`** (optional): Comma-separated list of AI models (auto-selected if not provided)
  467. - **`context`** (optional): Additional context for collaboration
  468. - **`conversation_id`** (optional): For stateful conversation history
  469. - **`budget_limit`** (optional): USD cost limit for OpenRouter models
  470. **Sequential Mode Parameters:**
  471. - **`pipeline_stages`** (optional): Comma-separated stages (auto-generated if not provided)
  472. - **`handoff_criteria`** (optional): `completion_of_stage` | `quality_threshold` | `consensus_reached` | `time_based`
  473. - **`quality_gates`** (optional): `none` | `basic` | `standard` | `strict` | `comprehensive`
  474. - **`focus`** (optional): Focus area (default: "progressive refinement")
  475. **Debate Mode Parameters:**
  476. - **`rounds`** (optional): Number of debate rounds (1-10, default: 3)
  477. - **`debate_style`** (optional): See debate styles above (default: "constructive")
  478. - **`convergence_criteria`** (optional): `substantial_agreement` | `consensus` | `majority_view` | `all_viewpoints`
  479. - **`focus`** (optional): Focus area (default: "comprehensive analysis")
  480. **Validation Mode Parameters:**
  481. - **`validation_criteria`** (optional): Comma-separated criteria (auto-generated if not provided)
  482. - **`confidence_threshold`** (optional): 0.0-1.0 (default: 0.7)
  483. - **`consensus_method`** (optional): `simple_majority` | `weighted_majority` | `unanimous` | `supermajority` | `expert_panel`
  484. - **`conflict_resolution`** (optional): `ignore` | `flag_only` | `detailed_analysis` | `additional_validation` | `expert_arbitration`
  485. #### Advanced Usage Examples
  486. **Different Debate Styles:**
  487. ```python
  488. # Adversarial debate for critical analysis
  489. gemini_ai_collaboration(
  490. collaboration_mode="debate",
  491. content="Should our startup use microservices architecture?",
  492. models="gemini-2.5-flash,openai/gpt-4.1-mini",
  493. rounds=3,
  494. debate_style="adversarial",
  495. convergence_criteria="majority_view"
  496. )
  497. # Socratic questioning for deep exploration
  498. gemini_ai_collaboration(
  499. collaboration_mode="debate",
  500. content="What makes code maintainable?",
  501. models="gemini-2.5-flash,anthropic/claude-3-haiku",
  502. rounds=4,
  503. debate_style="socratic",
  504. focus="fundamental principles"
  505. )
  506. # Devil's advocate for stress testing ideas
  507. gemini_ai_collaboration(
  508. collaboration_mode="debate",
  509. content="Our new feature implementation plan",
  510. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku",
  511. rounds=2,
  512. debate_style="devil_advocate",
  513. focus="identifying potential failures"
  514. )
  515. ```
  516. **Sequential Pipeline Examples:**
  517. ```python
  518. # Quality-gated sequential analysis
  519. gemini_ai_collaboration(
  520. collaboration_mode="sequential",
  521. content="@src/authentication.py",
  522. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku",
  523. pipeline_stages="code_review,security_analysis,performance_optimization,documentation",
  524. quality_gates="strict",
  525. handoff_criteria="quality_threshold"
  526. )
  527. # Time-based handoffs for rapid iteration
  528. gemini_ai_collaboration(
  529. collaboration_mode="sequential",
  530. content="Product requirements analysis",
  531. models="gemini-2.5-flash,openai/gpt-4.1-nano",
  532. pipeline_stages="initial_analysis,stakeholder_review,final_recommendations",
  533. handoff_criteria="time_based",
  534. focus="user experience"
  535. )
  536. ```
  537. **Validation Examples:**
  538. ```python
  539. # High-confidence consensus validation
  540. gemini_ai_collaboration(
  541. collaboration_mode="validation",
  542. content="Critical system design decisions",
  543. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku",
  544. validation_criteria="scalability,security,maintainability,cost_efficiency",
  545. confidence_threshold=0.9,
  546. consensus_method="unanimous",
  547. conflict_resolution="expert_arbitration"
  548. )
  549. # Supermajority validation with detailed conflict analysis
  550. gemini_ai_collaboration(
  551. collaboration_mode="validation",
  552. content="API design specification",
  553. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku",
  554. validation_criteria="usability,performance,consistency,documentation",
  555. consensus_method="supermajority",
  556. conflict_resolution="detailed_analysis"
  557. )
  558. ```
  559. **Auto-Selection Behavior:**
  560. When `models` parameter is not provided, the function automatically selects appropriate models:
  561. - **Sequential**: `"gemini-2.5-flash,openai/gpt-4.1-nano,anthropic/claude-3-haiku"`
  562. - **Debate**: `"gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku"`
  563. - **Validation**: `"gemini-2.5-flash,openai/gpt-4.1-nano,anthropic/claude-3-haiku"`
  564. ### OpenRouter Tools (6)
  565. #### `gemini_test_openrouter`
  566. Test OpenRouter connectivity and client functionality.
  567. ```python
  568. gemini_test_openrouter()
  569. ```
  570. #### `gemini_openrouter_opinion`
  571. Get responses from any of 400+ AI models via OpenRouter with @filename support.
  572. ```python
  573. gemini_openrouter_opinion(
  574. prompt="Analyze @config.yaml for security issues",
  575. model="anthropic/claude-3-haiku",
  576. temperature=0.7,
  577. max_tokens=2000,
  578. file_handling_strategy="auto"
  579. )
  580. ```
  581. #### `gemini_openrouter_models`
  582. List all available OpenRouter models (400+) with advanced filtering and output options.
  583. ```python
  584. gemini_openrouter_models(
  585. category="programming",
  586. provider_filter="openai",
  587. sort_by="usage",
  588. include_pricing=True
  589. )
  590. ```
  591. #### `gemini_cross_model_comparison`
  592. Compare responses across Gemini CLI and OpenRouter models with @filename support.
  593. ```python
  594. gemini_cross_model_comparison(
  595. prompt="Design a REST API for user authentication",
  596. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku"
  597. )
  598. ```
  599. #### `gemini_openrouter_usage_stats`
  600. Get OpenRouter usage statistics and costs for the current session.
  601. ```python
  602. gemini_openrouter_usage_stats()
  603. ```
  604. #### `gemini_cross_model_comparison`
  605. Compare responses across Gemini CLI and OpenRouter models with @filename support.
  606. ```python
  607. gemini_cross_model_comparison(
  608. prompt="Design a REST API for user authentication",
  609. models="gemini-2.5-flash,openai/gpt-4.1-mini,anthropic/claude-3-haiku"
  610. )
  611. ```
  612. ## 📦 Installation
  613. ### Prerequisites
  614. - **Python 3.10+** - Required for MCP SDK compatibility
  615. - **Gemini CLI** - Google's command-line tool for Gemini AI
  616. - **uv** (recommended) or pip for package management
  617. ### Linux Setup
  618. ```bash
  619. # Install uv (recommended package manager)
  620. curl -LsSf https://astral.sh/uv/install.sh | sh
  621. # Clone the repository
  622. git clone https://github.com/centminmod/gemini-cli-mcp-server.git
  623. cd gemini-cli-mcp-server
  624. # Create and activate virtual environment
  625. uv venv
  626. source .venv/bin/activate
  627. # Install dependencies
  628. uv pip install -r requirements.txt
  629. # Install and configure Gemini CLI
  630. npm install -g @google-ai/gemini-cli
  631. gemini config set api_key YOUR_GEMINI_API_KEY
  632. # Verify installation
  633. gemini --version
  634. python mcp_server.py --help
  635. ```
  636. ### macOS Setup
  637. ```bash
  638. # Install uv via Homebrew (or use curl installer above)
  639. brew install uv
  640. # Clone the repository
  641. git clone https://github.com/centminmod/gemini-cli-mcp-server.git
  642. cd gemini-cli-mcp-server
  643. # Create and activate virtual environment
  644. uv venv
  645. source .venv/bin/activate
  646. # Install dependencies
  647. uv pip install -r requirements.txt
  648. # Install Gemini CLI (if not already installed)
  649. npm install -g @google-ai/gemini-cli
  650. # Or via Homebrew: brew install gemini-cli
  651. # Configure Gemini CLI
  652. gemini config set api_key YOUR_GEMINI_API_KEY
  653. # Verify installation
  654. gemini --version
  655. python mcp_server.py --help
  656. ```
  657. ### Alternative Installation (pip)
  658. ```bash
  659. # Using standard Python tools
  660. python -m venv venv
  661. source venv/bin/activate # On Windows: venv\Scripts\activate
  662. pip install -r requirements.txt
  663. # Configure Gemini CLI
  664. gemini config set api_key YOUR_GEMINI_API_KEY
  665. ```
  666. ## ⚙️ MCP Client Configuration
  667. ### Claude Code
  668. Add the server using the Claude Code MCP command for `user` scope:
  669. ```bash
  670. claude mcp add gemini-cli /absolute/path/to/.venv/bin/python /absolute/path/to/mcp_server.py -s user -e GEMINI_API_KEY='YOUR_GEMINI_API_KEY'
  671. ```
  672. Use the `-s` or `--scope` flag to specify where the configuration is stored:
  673. * `local` (default): Available only to you in the current project (was called `project` in older versions)
  674. * `project`: Shared with everyone in the project via `.mcp.json` file
  675. * `user`: Available to you across all projects (was called `global` in older versions)
  676. ### Claude Desktop
  677. Add the following to your Claude Desktop settings file:
  678. **Location**:
  679. - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  680. - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
  681. - Linux: `~/.config/claude/claude_desktop_config.json`
  682. **Configuration**:
  683. ```json
  684. {
  685. "mcpServers": {
  686. "gemini-cli": {
  687. "command": "/absolute/path/to/.venv/bin/python",
  688. "args": ["/absolute/path/to/mcp_server.py"]
  689. }
  690. }
  691. }
  692. ```
  693. **Important**: Use absolute paths for both the Python executable and the `mcp_server.py` script.
  694. ### Other MCP Clients
  695. For other MCP-compatible clients, use the stdio transport with:
  696. - **Command**: Path to Python executable in virtual environment
  697. - **Arguments**: Path to `mcp_server.py`
  698. - **Transport**: stdio (standard input/output)
  699. ## 🎯 Usage Examples
  700. ### Basic Operations
  701. **Simple Q&A**:
  702. ```python
  703. # Quick question with fast model
  704. gemini_prompt(
  705. prompt="What is machine learning?",
  706. model="gemini-2.5-flash"
  707. )
  708. # Complex analysis with advanced model
  709. gemini_prompt(
  710. prompt="Analyze the trade-offs between REST and GraphQL APIs",
  711. model="gemini-2.5-pro"
  712. )
  713. ```
  714. **File Analysis**:
  715. ```python
  716. # Review code file directly
  717. gemini_review_code(
  718. code="@src/auth.py",
  719. purpose="Security vulnerability assessment",
  720. language="python"
  721. )
  722. # Summarize multiple files (standard approach)
  723. gemini_summarize(
  724. content="@src/ @tests/ @docs/",
  725. focus="architecture and design patterns"
  726. )
  727. # Large-scale file analysis (optimized approach)
  728. gemini_summarize_files(
  729. files="@src/ @lib/ @components/ @tests/ @docs/",
  730. focus="complete system architecture and dependencies"
  731. )
  732. ```
  733. **Code Execution**:
  734. ```python
  735. # Interactive development
  736. gemini_sandbox(
  737. prompt="Create a data visualization of sales trends",
  738. model="gemini-2.5-pro"
  739. )
  740. # Custom environment
  741. gemini_sandbox(
  742. prompt="Test this Node.js API endpoint",
  743. sandbox_image="node:18-alpine"
  744. )
  745. ```
  746. ### Dual-AI Workflow Examples
  747. The dual-AI workflow enables powerful collaboration between Claude Code and Gemini AI:
  748. #### 1. Plan Evaluation
  749. ```python
  750. # Claude Code generates an implementation plan
  751. plan = """
  752. 1. Create JWT authentication middleware
  753. 2. Implement rate limiting with Redis
  754. 3. Add input validation with Joi
  755. 4. Set up comprehensive error handling
  756. 5. Create user registration/login endpoints
  757. """
  758. # Gemini AI evaluates the plan
  759. gemini_eval_plan(
  760. plan=plan,
  761. context="Express.js REST API for e-commerce platform",
  762. requirements="Must support 50,000 concurrent users, GDPR compliant",
  763. model="gemini-2.5-pro"
  764. )
  765. ```
  766. #### 2. Code Review During Development
  767. ```python
  768. # Claude Code suggests implementation
  769. code = """
  770. const jwt = require('jsonwebtoken');
  771. const authMiddleware = (req, res, next) => {
  772. const token = req.header('Authorization')?.replace('Bearer ', '');
  773. if (!token) {
  774. return res.status(401).json({ error: 'Access denied' });
  775. }
  776. try {
  777. const decoded = jwt.verify(token, process.env.JWT_SECRET);
  778. req.user = decoded;
  779. next();
  780. } catch (error) {
  781. res.status(401).json({ error: 'Invalid token' });
  782. }
  783. };
  784. """
  785. # Gemini AI reviews the code
  786. gemini_review_code(
  787. code=code,
  788. purpose="JWT authentication middleware for Express.js",
  789. context="E-commerce API with high security requirements",
  790. language="javascript",
  791. model="gemini-2.5-pro"
  792. )
  793. ```
  794. #### 3. Complete Solution Verification
  795. ```python
  796. # Complete implementation ready for deployment
  797. solution = """
  798. [Complete implementation including:]
  799. - Authentication system with JWT and refresh tokens
  800. - Rate limiting middleware with Redis
  801. - Input validation with comprehensive schemas
  802. - Error handling with structured responses
  803. - User management endpoints
  804. - Security headers and CORS configuration
  805. - Comprehensive test suite
  806. - API documentation
  807. - Deployment configuration
  808. """
  809. # Final verification before deployment
  810. gemini_verify_solution(
  811. solution=solution,
  812. requirements="Secure authentication system with rate limiting",
  813. test_criteria="Handle 50k concurrent users, 99.9% uptime, sub-200ms response",
  814. context="Production deployment on AWS ECS with Redis ElastiCache",
  815. model="gemini-2.5-pro"
  816. )
  817. ```
  818. ### Advanced Usage Patterns
  819. **Large Codebase Analysis**:
  820. ```python
  821. # Enterprise-scale project analysis (recommended)
  822. gemini_summarize_files(
  823. files="@src/ @lib/ @components/ @utils/ @tests/ @docs/",
  824. focus="architectural patterns and dependencies",
  825. model="gemini-2.5-pro"
  826. )
  827. # Alternative for smaller projects
  828. gemini_summarize(
  829. content="@src/ @lib/ @components/ @utils/ @tests/",
  830. focus="architectural patterns and dependencies",
  831. model="gemini-2.5-pro"
  832. )
  833. ```
  834. **Performance Analysis**:
  835. ```python
  836. # Review code for performance issues
  837. gemini_review_code(
  838. code="@src/api/handlers/ @src/database/",
  839. purpose="Performance optimization and bottleneck identification",
  840. context="High-traffic API serving 1M requests/day",
  841. model="gemini-2.5-pro"
  842. )
  843. ```
  844. **Security Assessment**:
  845. ```python
  846. # Comprehensive security review
  847. gemini_review_code(
  848. code="@auth/ @middleware/ @validators/",
  849. purpose="Security vulnerability assessment",
  850. context="Financial services application with PCI compliance requirements",
  851. model="gemini-2.5-pro"
  852. )
  853. ```
  854. ### Specialized Code Review Examples (NEW)
  855. **Structured Code Analysis**:
  856. ```python
  857. # Comprehensive code review with structured output
  858. gemini_code_review(
  859. code="@src/api/handlers/",
  860. language="python",
  861. focus_areas="security,performance,maintainability",
  862. severity_threshold="warning",
  863. output_format="structured"
  864. )
  865. ```
  866. **Schema-Based Data Extraction**:
  867. ```python
  868. # Extract API endpoints from codebase
  869. schema = {
  870. "type": "object",
  871. "properties": {
  872. "endpoints": {
  873. "type": "array",
  874. "items": {
  875. "type": "object",
  876. "properties": {
  877. "path": {"type": "string"},
  878. "method": {"type": "string"},
  879. "authentication": {"type": "boolean"}
  880. }
  881. }
  882. }
  883. }
  884. }
  885. gemini_extract_structured(
  886. content="@src/routes/",
  887. schema=json.dumps(schema),
  888. strict_mode=True
  889. )
  890. ```
  891. **Git Diff Analysis**:
  892. ```python
  893. # Review pull request changes
  894. gemini_git_diff_review(
  895. diff="@pull_request.diff",
  896. review_type="comprehensive",
  897. base_branch="main",
  898. commit_message="Add user authentication feature"
  899. )
  900. ```
  901. **Multi-Source Content Comparison**:
  902. ```python
  903. # Compare API documentation versions
  904. gemini_content_comparison(
  905. sources='["@docs/api_v1.md", "@docs/api_v2.md", "https://api.example.com/docs"]',
  906. comparison_type="semantic",
  907. output_format="matrix",
  908. focus_areas="breaking_changes,new_features,deprecations"
  909. )
  910. ```
  911. ## ⚡ Advanced Features
  912. ### Dynamic Token Limits
  913. Each tool has optimized character limits based on typical use cases:
  914. | Tool | Limit | Use Case |
  915. |------|-------|----------|
  916. | `gemini_prompt` | 100K chars | General purpose interactions |
  917. | `gemini_sandbox` | 200K chars | Code execution & development |
  918. | `gemini_eval_plan` | 500K chars | Architecture evaluation |
  919. | `gemini_review_code` | 300K chars | Code review & analysis |
  920. | `gemini_verify_solution` | 800K chars | Complete solution verification |
  921. | `gemini_summarize` | 400K chars | Large content summarization |
  922. | `gemini_summarize_files` | 800K chars | File-based analysis with @filename syntax |
  923. | `gemini_ai_collaboration` | 500K chars | Multi-AI workflow collaboration |
  924. | `gemini_openrouter_opinion` | 150K chars | OpenRouter model interactions |
  925. | `gemini_code_review` | 300K chars | Structured code analysis (NEW) |
  926. | `gemini_extract_structured` | 200K chars | Schema-based data extraction (NEW) |
  927. | `gemini_git_diff_review` | 150K chars | Git diff analysis (NEW) |
  928. | `gemini_content_comparison` | 400K chars | Multi-source content comparison (NEW) |
  929. | **Conversation Tools** | Variable | Context-aware with token management |
  930. ### Model-Aware Scaling
  931. Limits automatically scale based on the selected model's capabilities:
  932. - **gemini-2.5-pro**: 100% of limits (best quality)
  933. - **gemini-2.5-flash**: 100% of limits (speed optimized)
  934. - **gemini-1.5-pro**: 80% of limits (stable performance)
  935. - **gemini-1.5-flash**: 60% of limits (speed focused)
  936. - **gemini-1.0-pro**: 40% of limits (legacy compatibility)
  937. ### Automatic Model Fallback
  938. When quota limits are exceeded, the server automatically falls back from premium to standard models:
  939. ```
  940. gemini-2.5-pro (quota exceeded) → gemini-2.5-flash (automatic retry)
  941. ```
  942. This ensures continuous operation during high-usage periods without user intervention.
  943. ### OpenRouter Multi-Model Integration
  944. Access to 400+ AI models from 20+ providers including OpenAI, Anthropic, Meta, Google, and more:
  945. **Key Benefits:**
  946. - **Model Variants**: Optimization options (:free, :nitro, :floor, :online) for cost, speed, and capabilities
  947. - **Cost Management**: Built-in usage tracking with daily limits and warnings
  948. - **Cross-Platform Comparison**: Compare responses between Gemini CLI and OpenRouter models
  949. - **Enhanced @filename Support**: Intelligent large file handling for 200K+ token support
  950. **Popular Models Available:**
  951. - **OpenAI**: gpt-4.1-nano, gpt-4.1-mini, gpt-4.1,gpt-4o, gpt-4o-mini, gpt-3.5-turbo
  952. - **Anthropic**: claude-sonnet-4, claude-3-haiku, claude-opus-4
  953. - **Meta**: llama-3.2-11b-vision-instruct, llama-3.1-405b-instruct
  954. - **Google**: gemini-2.5-pro, gemini-2.5-flash (via OpenRouter)
  955. - **Free Options**: Multiple free model variants available
  956. ### Conversation History Management
  957. Stateful multi-turn conversations with persistent context:
  958. **Key Features:**
  959. - **Redis-Backed Storage**: Scalable conversation storage with graceful memory fallback
  960. - **Cross-Platform Support**: Works seamlessly with both Gemini CLI and OpenRouter models
  961. - **Automatic Context Building**: Intelligent context assembly respecting token limits
  962. - **Conversation Pruning**: Automatic message and token limit management
  963. - **Configurable Expiration**: Automatic cleanup with customizable retention periods
  964. ### Advanced Caching
  965. **TTL-Based Caching**:
  966. - Help/version commands: 30 minutes
  967. - Prompt results: 5 minutes
  968. - Template loading: 30 minutes
  969. **Cache Features**:
  970. - Atomic operations prevent race conditions
  971. - Memory limits prevent unbounded growth
  972. - Automatic cleanup and expiration
  973. - Cache hit/miss metrics tracking
  974. ### @filename Syntax Support
  975. 32 of the 33 tools support Gemini CLI's native @filename syntax for optimal token efficiency. OpenRouter tools include enhanced large file handling:
  976. ```python
  977. # Single file
  978. gemini_prompt(prompt="Analyze @config.py")
  979. # Multiple files
  980. gemini_review_code(code="@src/auth.py @src/middleware.py")
  981. # Directories and wildcards
  982. gemini_summarize(content="@src/ @tests/ @**/*.js")
  983. # OpenRouter with intelligent file processing
  984. gemini_openrouter_opinion(
  985. prompt="Review @large_codebase/ for security",
  986. model="anthropic/claude-3-haiku",
  987. file_handling_strategy="auto" # auto, full, chunk, summarize
  988. )
  989. # Mixed content
  990. gemini_eval_plan(plan="Based on @requirements.md, implement @design.py")
  991. ```
  992. **Benefits**:
  993. - 50-70% token efficiency improvement for Gemini CLI tools
  994. - Direct file reading by Gemini CLI
  995. - Intelligent large file handling for OpenRouter (200K+ token support)
  996. - Multiple processing strategies: full, chunk, summarize, auto
  997. - No intermediate processing overhead
  998. - Preserves full context window utilization
  999. ### Template System Benefits
  1000. The modular template system provides significant advantages for enterprise deployments:
  1001. **📈 Maintainability**:
  1002. - **Function Size Reduction**: ~70% average reduction in function complexity
  1003. - **Separation of Concerns**: Template content isolated from business logic
  1004. - **Single Responsibility**: Each template serves a specific AI workflow purpose
  1005. - **Version Control**: Template changes tracked independently
  1006. **⚡ Performance**:
  1007. - **TTL Caching**: 30-minute cache for template loading reduces I/O overhead
  1008. - **Memory Efficiency**: Templates loaded once and reused across requests
  1009. - **Response Time**: Faster tool execution with cached template access
  1010. - **Resource Optimization**: Reduced filesystem access for repeated operations
  1011. **🔧 Development Experience**:
  1012. - **Modular Architecture**: Each dual-AI workflow tool has dedicated templates
  1013. - **Easy Customization**: Templates can be modified without touching core logic
  1014. - **Testing**: Templates can be unit tested independently
  1015. - **Documentation**: Self-documenting template structure with clear organization
  1016. ## ⚙️ Configuration
  1017. ### Environment Variables
  1018. The server supports extensive configuration through environment variables:
  1019. #### Core Configuration
  1020. ```bash
  1021. export GEMINI_TIMEOUT=300 # Command timeout (10-3600 seconds)
  1022. export GEMINI_LOG_LEVEL=INFO # Logging level (DEBUG, INFO, WARNING, ERROR)
  1023. export GEMINI_COMMAND_PATH=gemini # Path to Gemini CLI executable
  1024. export GEMINI_OUTPUT_FORMAT=json # Response format (json, text)
  1025. ```
  1026. #### Retry Configuration
  1027. ```bash
  1028. export RETRY_MAX_ATTEMPTS=3 # Maximum retry attempts (1-10)
  1029. export RETRY_BASE_DELAY=1.0 # Base delay for exponential backoff (0.1-10.0)
  1030. export RETRY_MAX_DELAY=30.0 # Maximum delay between retries (5.0-300.0)
  1031. ```
  1032. #### Tool-Specific Limits
  1033. ```bash
  1034. export GEMINI_PROMPT_LIMIT=100000 # gemini_prompt character limit
  1035. export GEMINI_SANDBOX_LIMIT=200000 # gemini_sandbox character limit
  1036. export GEMINI_EVAL_LIMIT=500000 # gemini_eval_plan character limit
  1037. export GEMINI_REVIEW_LIMIT=300000 # gemini_review_code character limit
  1038. export GEMINI_VERIFY_LIMIT=800000 # gemini_verify_solution character limit
  1039. export GEMINI_SUMMARIZE_LIMIT=400000 # gemini_summarize character limit
  1040. export GEMINI_SUMMARIZE_FILES_LIMIT=800000 # gemini_summarize_files character limit
  1041. ```
  1042. #### Model Fallback
  1043. ```bash
  1044. export GEMINI_ENABLE_FALLBACK=true # Enable automatic model fallback
  1045. ```
  1046. #### Rate Limiting
  1047. ```bash
  1048. export GEMINI_RATE_LIMIT_REQUESTS=100 # Requests per time window
  1049. export GEMINI_RATE_LIMIT_WINDOW=60 # Time window in seconds
  1050. ```
  1051. #### OpenRouter Configuration
  1052. ```bash
  1053. export OPENROUTER_API_KEY="sk-or-v1-your-api-key" # OpenRouter API key for 400+ models
  1054. export OPENROUTER_DEFAULT_MODEL="openai/gpt-4.1-nano" # Default OpenRouter model
  1055. export OPENROUTER_COST_LIMIT_PER_DAY="10.0" # Daily cost limit in USD
  1056. export OPENROUTER_ENABLE_STREAMING="true" # Enable streaming responses
  1057. export OPENROUTER_MAX_FILE_TOKENS="50000" # Per-file token limit for @filename
  1058. export OPENROUTER_MAX_TOTAL_TOKENS="150000" # Total prompt token limit
  1059. ```
  1060. #### Conversation Management
  1061. ```bash
  1062. export GEMINI_CONVERSATION_ENABLED="true" # Enable conversation history
  1063. export GEMINI_CONVERSATION_STORAGE="redis" # Storage backend (redis, memory, auto)
  1064. export GEMINI_CONVERSATION_EXPIRATION_HOURS="24" # Auto-cleanup time
  1065. export GEMINI_CONVERSATION_MAX_MESSAGES="10" # Message history limit
  1066. export GEMINI_CONVERSATION_MAX_TOKENS="20000" # Token history limit
  1067. export GEMINI_REDIS_HOST="localhost" # Redis host for conversation storage
  1068. export GEMINI_REDIS_PORT="6479" # Redis port (custom to avoid conflicts)
  1069. ```
  1070. #### Cloudflare AI Gateway Integration (Optional)
  1071. ```bash
  1072. # Route OpenRouter requests through Cloudflare AI Gateway for enhanced performance
  1073. export CLOUDFLARE_AI_GATEWAY_ENABLED="true" # Enable Cloudflare AI Gateway
  1074. export CLOUDFLARE_ACCOUNT_ID="your-account-id" # Cloudflare Account ID
  1075. export CLOUDFLARE_GATEWAY_ID="your-gateway-id" # Cloudflare Gateway ID
  1076. export CLOUDFLARE_AI_GATEWAY_TIMEOUT="300" # Gateway timeout in seconds
  1077. export CLOUDFLARE_AI_GATEWAY_MAX_RETRIES="3" # Maximum retry attempts
  1078. ```
  1079. #### Enterprise Monitoring (Optional)
  1080. ```bash
  1081. export ENABLE_MONITORING=true # Master control for all monitoring features
  1082. export ENABLE_OPENTELEMETRY=true # Enable OpenTelemetry distributed tracing
  1083. export ENABLE_PROMETHEUS=true # Enable Prometheus metrics collection
  1084. export ENABLE_HEALTH_CHECKS=true # Enable health check system
  1085. export PROMETHEUS_PORT=8000 # Prometheus metrics endpoint port
  1086. export OPENTELEMETRY_ENDPOINT="https://otel-collector:4317" # OpenTelemetry endpoint
  1087. export OPENTELEMETRY_SERVICE_NAME="gemini-cli-mcp-server" # Service name for tracing
  1088. ```
  1089. #### Security Configuration (Advanced)
  1090. ```bash
  1091. export JSONRPC_MAX_REQUEST_SIZE=1048576 # Max JSON-RPC request size (1MB default)
  1092. export JSONRPC_MAX_NESTING_DEPTH=10 # Max object/array nesting depth
  1093. export JSONRPC_STRICT_MODE=true # Enable strict JSON-RPC validation
  1094. export GEMINI_SUBPROCESS_MAX_CPU_TIME=300 # Subprocess CPU time limit (seconds)
  1095. export GEMINI_SUBPROCESS_MAX_MEMORY_MB=512 # Subprocess memory limit (MB)
  1096. ```
  1097. ### Configuration Examples
  1098. **Standard Development**:
  1099. ```bash
  1100. # Use defaults - no configuration needed
  1101. ```
  1102. **With OpenRouter (400+ Models)**:
  1103. ```bash
  1104. export OPENROUTER_API_KEY="sk-or-v1-your-api-key"
  1105. export OPENROUTER_COST_LIMIT_PER_DAY="10.0"
  1106. export OPENROUTER_DEFAULT_MODEL="anthropic/claude-3-haiku"
  1107. ```
  1108. **Full Enterprise Setup**:
  1109. ```bash
  1110. # Core configuration
  1111. export GEMINI_TIMEOUT=600
  1112. export GEMINI_EVAL_LIMIT=750000
  1113. export GEMINI_REVIEW_LIMIT=600000
  1114. export GEMINI_VERIFY_LIMIT=1200000
  1115. export RETRY_MAX_ATTEMPTS=5
  1116. # OpenRouter integration
  1117. export OPENROUTER_API_KEY="sk-or-v1-your-api-key"
  1118. export OPENROUTER_COST_LIMIT_PER_DAY="25.0"
  1119. export OPENROUTER_DEFAULT_MODEL="openai/gpt-4.1-mini"
  1120. # Cloudflare AI Gateway (optional)
  1121. export CLOUDFLARE_AI_GATEWAY_ENABLED="true"
  1122. export CLOUDFLARE_ACCOUNT_ID="your-account-id"
  1123. export CLOUDFLARE_GATEWAY_ID="your-gateway-id"
  1124. # Conversation history with Redis
  1125. export GEMINI_CONVERSATION_ENABLED="true"
  1126. export GEMINI_CONVERSATION_STORAGE="redis"
  1127. export GEMINI_REDIS_PORT="6479"
  1128. # Enterprise monitoring
  1129. export ENABLE_MONITORING="true"
  1130. export ENABLE_PROMETHEUS="true"
  1131. export PROMETHEUS_PORT="8000"
  1132. ```
  1133. **High-Performance Setup**:
  1134. ```bash
  1135. export GEMINI_LOG_LEVEL=WARNING
  1136. export RETRY_BASE_DELAY=0.5
  1137. export RETRY_MAX_DELAY=10.0
  1138. export GEMINI_RATE_LIMIT_REQUESTS=500
  1139. export OPENROUTER_ENABLE_STREAMING="true"
  1140. ```
  1141. **Debug Configuration**:
  1142. ```bash
  1143. export GEMINI_LOG_LEVEL=DEBUG
  1144. export GEMINI_OUTPUT_FORMAT=json
  1145. export GEMINI_TIMEOUT=120
  1146. export ENABLE_STDIN_DEBUG="1"
  1147. ```
  1148. ### Response Formats
  1149. #### JSON Format (Default)
  1150. ```json
  1151. {
  1152. "status": "success",
  1153. "return_code": 0,
  1154. "stdout": "Response from Gemini AI",
  1155. "stderr": ""
  1156. }
  1157. ```
  1158. #### Text Format
  1159. ```
  1160. Response from Gemini AI
  1161. ```
  1162. ## 🚀 Performance
  1163. ### Performance Characteristics
  1164. **Operation Times**:
  1165. - Fast operations (help, version, metrics): < 2 seconds
  1166. - Medium operations (simple prompts): 2-10 seconds
  1167. - Complex operations (file analysis, code review): 10-60 seconds
  1168. - Large analysis (enterprise codebases): 1-5 minutes
  1169. - OpenRouter requests: 2-15 seconds (varies by model)
  1170. - Conversation context loading: < 1 second (with Redis)
  1171. **Concurrency**:
  1172. - Async architecture supports 1,000-10,000+ concurrent requests
  1173. - 10-100x concurrency improvement with lock-free cache operations
  1174. - Memory-efficient single-threaded design
  1175. - Non-blocking I/O operations across all 33 tools
  1176. **Memory Usage**:
  1177. - Base server: 15-30MB (optimized for enterprise features)
  1178. - Per operation: 2-8MB average (varies by tool complexity)
  1179. - Bounded caches prevent memory leaks with automatic cleanup
  1180. - O(1) rate limiting algorithms with memory leak protection
  1181. - Redis-backed conversation storage scales independently
  1182. **Total Lines of Code**: ~15,000+ lines across 83 modules
  1183. **Cache Effectiveness**:
  1184. - Help/version commands: 95-99% hit rate
  1185. - Prompt results: 60-80% hit rate for repeated operations
  1186. - Template loading: 90-95% hit rate (30-minute TTL)
  1187. - OpenRouter model discovery: 98% hit rate
  1188. - Conversation context: 85-95% hit rate with Redis
  1189. ### Performance Optimization
  1190. **For High-Throughput Scenarios**:
  1191. ```bash
  1192. export GEMINI_LOG_LEVEL=WARNING # Reduce logging overhead
  1193. export RETRY_BASE_DELAY=0.5 # Faster retry cycles
  1194. export GEMINI_RATE_LIMIT_REQUESTS=1000 # Higher rate limits
  1195. ```
  1196. **For Large Content Processing**:
  1197. ```bash
  1198. export GEMINI_TIMEOUT=1800 # Extended timeout (30 minutes)
  1199. export GEMINI_EVAL_LIMIT=1500000 # Maximum evaluation capacity
  1200. export GEMINI_VERIFY_LIMIT=2000000 # Maximum verification capacity
  1201. ```
  1202. **For Development Speed**:
  1203. ```bash
  1204. export GEMINI_OUTPUT_FORMAT=text # Faster response parsing
  1205. export RETRY_MAX_ATTEMPTS=1 # Fail fast for debugging
  1206. ```
  1207. ### Monitoring
  1208. Use the `gemini_metrics` tool to monitor server performance:
  1209. ```python
  1210. gemini_metrics()
  1211. ```
  1212. **Key Metrics**:
  1213. - Commands executed and success rate across all 33 tools
  1214. - Average latency and throughput per tool category
  1215. - Cache hit rates and effectiveness (4 cache types)
  1216. - Error rates and types with detailed classification
  1217. - Model usage and fallback statistics (Gemini + OpenRouter)
  1218. - Memory usage and resource utilization
  1219. - OpenRouter cost tracking and usage statistics
  1220. - Conversation system performance and storage metrics
  1221. - Security pattern detection and rate limiting effectiveness
  1222. ## 🧪 Testing
  1223. ### Quick Validation
  1224. **Test Server Import**:
  1225. ```bash
  1226. python -c "from mcp_server import mcp; print('✅ Server imports successfully')"
  1227. ```
  1228. **Test Gemini CLI Integration**:
  1229. ```bash
  1230. python -c "
  1231. import asyncio
  1232. from gemini_utils import validate_gemini_setup
  1233. print('✅ Gemini CLI setup valid' if validate_gemini_setup() else '❌ Gemini CLI setup invalid')
  1234. "
  1235. ```
  1236. ### MCP Inspector Testing
  1237. Test the server with the official MCP development tools:
  1238. ```bash
  1239. # Install MCP development tools
  1240. uv pip install "mcp[dev]"
  1241. # Test server with MCP inspector
  1242. mcp dev mcp_server.py
  1243. ```
  1244. This opens an interactive interface to test all MCP tools directly.
  1245. ### Manual Testing
  1246. **Test Basic Functionality**:
  1247. ```python
  1248. # In Python REPL or script
  1249. import asyncio
  1250. from mcp_server import gemini_help, gemini_version, gemini_models
  1251. async def test_basic():
  1252. print("Testing basic functionality...")
  1253. # Test cached operations
  1254. help_result = await gemini_help()
  1255. print(f"Help: {len(help_result)} characters")
  1256. version_result = await gemini_version()
  1257. print(f"Version: {version_result[:50]}...")
  1258. models_result = await gemini_models()
  1259. print(f"Models: {models_result[:100]}...")
  1260. print("✅ Basic tests passed")
  1261. asyncio.run(test_basic())
  1262. ```
  1263. **Test Prompt Functionality**:
  1264. ```python
  1265. import asyncio
  1266. from mcp_server import gemini_prompt
  1267. async def test_prompts():
  1268. print("Testing prompt functionality...")
  1269. result = await gemini_prompt(
  1270. prompt="Say hello and confirm you're working",
  1271. model="gemini-2.5-flash"
  1272. )
  1273. print(f"Prompt result: {result[:200]}...")
  1274. print("✅ Prompt tests passed")
  1275. asyncio.run(test_prompts())
  1276. ```
  1277. ### Production Readiness
  1278. The server has been comprehensively tested with:
  1279. - **2,500+ test cases** across 6 specialized test files with descriptive naming
  1280. - **Complete security validation** covering all 22 critical security fixes with attack simulation
  1281. - **Performance benchmarking** with concurrency stress testing and memory leak detection
  1282. - **Monitoring integration testing** with graceful degradation validation
  1283. - **@filename syntax validation** with real files across 32 of 33 tools
  1284. - **OpenRouter integration testing** with 400+ model compatibility validation
  1285. - **AI Collaboration testing** with 92.9% success rate and production enhancements
  1286. - **Conversation system testing** with Redis storage and context management
  1287. - **Specialized code review testing** for new analysis tools
  1288. - **Error handling and edge cases** for enterprise deployment scenarios
  1289. ## 🔧 Troubleshooting
  1290. ### Common Issues
  1291. #### "Tool 'gemini_cli' not found"
  1292. **Cause**: MCP client can't connect to server or server isn't running.
  1293. **Solutions**:
  1294. 1. Verify absolute paths in MCP client configuration
  1295. 2. Check that virtual environment is activated
  1296. 3. Test server manually: `python mcp_server.py`
  1297. 4. Check client logs for connection errors
  1298. #### "Gemini CLI not found"
  1299. **Cause**: Gemini CLI not installed or not in PATH.
  1300. **Solutions**:
  1301. 1. Install Gemini CLI: `npm install -g @google-ai/gemini-cli`
  1302. 2. Verify installation: `gemini --version`
  1303. 3. Set custom path: `export GEMINI_COMMAND_PATH=/path/to/gemini`
  1304. #### Authentication Errors
  1305. **Cause**: Gemini API key not configured or invalid.
  1306. **Solutions**:
  1307. 1. Configure API key: `gemini config set api_key YOUR_API_KEY`
  1308. 2. Verify key validity: `gemini --version`
  1309. 3. Check API quota and billing status
  1310. #### Rate Limit Exceeded
  1311. **Cause**: Too many requests in short time period.
  1312. **Solutions**:
  1313. 1. Wait for rate limit window to reset
  1314. 2. Increase limits: `export GEMINI_RATE_LIMIT_REQUESTS=500`
  1315. 3. Use faster model: Switch to `gemini-2.5-flash`
  1316. #### Large Content Failures
  1317. **Cause**: Content exceeds tool-specific character limits.
  1318. **Solutions**:
  1319. 1. Check content size: `wc -c your_file.txt`
  1320. 2. Increase limits: `export GEMINI_EVAL_LIMIT=1000000`
  1321. 3. Use chunking strategy for very large content
  1322. 4. Use `gemini_summarize_files` for file-based analysis
  1323. #### Server Won't Start
  1324. **Diagnostic Steps**:
  1325. 1. Check Python version: `python --version` (must be 3.10+)
  1326. 2. Verify dependencies: `pip list | grep mcp`
  1327. 3. Test imports: `python -c "import mcp"`
  1328. 4. Check logs: `GEMINI_LOG_LEVEL=DEBUG python mcp_server.py`
  1329. #### Performance Issues
  1330. **Optimization Steps**:
  1331. 1. Monitor metrics: Use `gemini_metrics()` tool
  1332. 2. Check cache hit rates (should be >80% for repeated operations)
  1333. 3. Reduce logging: `export GEMINI_LOG_LEVEL=WARNING`
  1334. 4. Optimize timeouts: `export GEMINI_TIMEOUT=120`
  1335. ### Debug Mode
  1336. Enable comprehensive debugging:
  1337. ```bash
  1338. export GEMINI_LOG_LEVEL=DEBUG
  1339. export GEMINI_OUTPUT_FORMAT=json
  1340. python mcp_server.py
  1341. ```
  1342. This provides detailed information about:
  1343. - Command execution and arguments
  1344. - Cache operations and hit rates
  1345. - Error details and stack traces
  1346. - Performance metrics and timing
  1347. - Model fallback behavior
  1348. ### Getting Help
  1349. If you encounter issues not covered here:
  1350. 1. **Check server logs** for detailed error messages
  1351. 2. **Verify Gemini CLI** works independently: `gemini --help`
  1352. 3. **Test with simple commands** first: `gemini_version()`
  1353. 4. **Monitor metrics** for performance insights: `gemini_metrics()`
  1354. 5. **Check environment variables** for correct configuration
  1355. ## 📄 Requirements
  1356. ### System Requirements
  1357. - **Python**: 3.10 or higher
  1358. - **Operating System**: Linux, macOS, or Windows
  1359. - **Memory**: 512MB minimum, 2GB recommended
  1360. - **Disk Space**: 100MB for installation
  1361. - **Network**: Internet connection for Gemini API access
  1362. ### Python Dependencies
  1363. ```
  1364. mcp>=0.3.0
  1365. httpx>=0.24.0
  1366. cachetools>=5.3.0
  1367. ```
  1368. ### Optional Dependencies
  1369. ```
  1370. pytest>=7.0.0 # For development and testing
  1371. pytest-mock>=3.10.0 # For mocking in tests
  1372. uvicorn[standard]>=0.20.0 # For alternative server deployment
  1373. ```
  1374. ### External Dependencies
  1375. - **Gemini CLI**: Google's command-line interface for Gemini AI
  1376. - **Node.js**: Required for Gemini CLI installation (if using npm)
  1377. ## Star History
  1378. [![Star History Chart](https://api.star-history.com/svg?repos=centminmod/gemini-cli-mcp-server&type=Date)](https://www.star-history.com/#centminmod/gemini-cli-mcp-server&Date)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.