diff --git a/AGENTS.md b/AGENTS.md index 2507df1..61345b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,10 +14,23 @@ Run commands from the project root to ensure relative paths resolve correctly. Follow PEP 8 with 4-space indentation and an 88-character target line length. Use descriptive, lowercase `snake_case` for functions and variables, `UPPER_SNAKE_CASE` for constants, and reserve `CamelCase` for classes. Keep functions small, add docstrings describing intent, and include type hints on public interfaces. Prefer expressive log messages over inline comments; only annotate logic that is non-obvious. ## Testing Guidelines -No automated suite ships today, so validate changes by exercising both tools: `python -m src` for the stdio server and `uvx gemini-bridge -- --help` or a sample prompt to confirm CLI wiring. When introducing automated tests, place them under `tests/`, target `pytest`, and mirror module names (e.g., `tests/test_mcp_server.py`). Cover environment-sensitive paths such as `_normalize_model_name` and `_get_timeout`, and document manual test steps in your PR. +Validate changes by exercising all three MCP tools: `consult_gemini`, `consult_gemini_with_files`, and `web_search`. Run `python -m src` for the stdio server and `uvx gemini-bridge -- --help` or a sample prompt to confirm CLI wiring. Automated tests are located under `tests/`, targeting `pytest`, and mirror module names (e.g., `tests/test_mcp_server.py`). Cover environment-sensitive paths such as `_normalize_model_name`, `_get_timeout`, and the new `web_search` function. Document manual test steps in your PR. ## Commit & Pull Request Guidelines Commit messages follow Conventional Commit prefixes (`feat:`, `fix:`, `chore:`, `docs:`) and should explain the motivation. Keep commits atomic and focused on one concern. Pull requests must include a concise summary, linked issues, and a brief testing log (commands run, expected vs. actual behavior). Request a review once CI (when available) passes and respond to feedback with follow-up commits rather than force-pushes. ## Security & Configuration Tips Authenticate the Gemini CLI (`gemini auth login`) before running tools and avoid hard-coding credentials. Use the `GEMINI_BRIDGE_TIMEOUT` environment variable for tuning, but never commit `.env` files or shell history containing secrets. Validate file paths carefully when adding features that read from disk to preserve the server’s minimal, secure surface area. + +## Model Support +The server supports multiple Gemini models through aliases: +- `flash`, `2.5-flash` → `gemini-2.5-flash` (default) +- `pro`, `2.5-pro` → `gemini-2.5-pro` +- `flash-lite`, `2.5-flash-lite`, `2.5-lite` → `gemini-2.5-flash-lite` +- `3-pro` → `gemini-3-pro-preview` +- `3-flash` → `gemini-3-flash-preview` +- `3.1-pro` → `gemini-3.1-pro-preview` +- `3.1-flash-lite` → `gemini-3.1-flash-lite-preview` +- `auto` → lets CLI choose optimal model + +Custom models prefixed with `gemini-` are passed through directly. diff --git a/CHANGELOG.md b/CHANGELOG.md index e353be2..c8269b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.3.0] - 2026-03-03 + +### Added +- **Web search tool**: New `web_search` MCP tool that leverages Gemini CLI's built-in web search capabilities for querying current information +- **Gemini 2.5 Flash Lite**: New alias `flash-lite` for the cost-effective `gemini-2.5-flash-lite` model +- **Gemini 3.1 Pro Preview**: New alias `3.1-pro` for the latest `gemini-3.1-pro-preview` model +- **Gemini 3.1 Flash Lite**: New alias `3.1-flash-lite` for the latest `gemini-3.1-flash-lite-preview` model +- **Extended model aliases**: Full list now includes flash, pro, flash-lite, 2.5-lite, 3-pro, 3-flash, 3.1-pro, 3.1-flash-lite, and auto router + +### Changed +- **Modern Python syntax**: Migrated to Python 3.10+ type hints (`str | None`, `list[str]`) throughout codebase +- **Path handling**: Replaced `os.path` with `pathlib.Path` for better cross-platform compatibility +- **Documentation updates**: README.md and CLAUDE.md updated with new tools and model options + +### Fixed +- **Model alias fixes**: Fixed `2.5-lite` to correctly map to `gemini-2.5-flash-lite` +- **Error messaging**: Improved error messages with helpful suggestions for model availability, authentication, timeout, and missing CLI +- **Documentation accuracy**: Fixed Python version requirement (3.10+ instead of 3.9+ throughout docs) +- **Web search honesty**: Updated web_search description to reflect best-effort automatic nature + +### Technical Details +- Removed old typing imports (`Optional`, `List`, `Tuple`) +- Added `from pathlib import Path` for all path operations +- Updated `_normalize_model_name()` function with new model aliases (3.1-flash-lite, 2.5-lite) +- Enhanced error handling with actionable user guidance +- All 34 tests pass including 7 new tests for models, web_search, and error handling + ## [1.2.0] - 2025-12-28 ### Added @@ -75,7 +102,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Dependencies - **Required**: `mcp>=1.0.0` - **External**: Gemini CLI (npm package `@google/gemini-cli`) -- **Python**: Compatible with Python 3.9+ +- **Python**: Compatible with Python 3.10+ #### File Structure ``` diff --git a/CLAUDE.md b/CLAUDE.md index 5ed60dd..e0f639f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,7 +100,14 @@ python -c "import src; print('Package works!')" **Model Support:** - Default: `gemini-2.5-flash` (optimal performance/cost) -- Available: `flash`, `pro` (auto-normalized to full names) +- Available aliases: + - `flash`, `2.5-flash` → `gemini-2.5-flash` + - `pro`, `2.5-pro` → `gemini-2.5-pro` + - `flash-lite`, `2.5-flash-lite` → `gemini-2.5-flash-lite` + - `3-pro` → `gemini-3-pro-preview` + - `3-flash` → `gemini-3-flash-preview` + - `3.1-pro` → `gemini-3.1-pro-preview` + - `auto` → lets CLI choose optimal model - Custom models accepted if prefixed with `gemini-` ### File Structure @@ -131,11 +138,11 @@ gemini-bridge/ - **Use Case**: General questions, code analysis without file attachments - **Example**: General programming questions, code explanations -### `consult_gemini_with_files` +### `consult_gemini_with_files` - **Purpose**: CLI bridge with file attachments for detailed analysis -- **Parameters**: +- **Parameters**: - `query` (required): The question or prompt to send to Gemini - - `directory` (required): Working directory for the query + - `directory` (required): Working directory for the query - `files` (required list): List of file paths to attach - `model` (optional): Model name (flash, pro, or custom) - `timeout_seconds` (optional): Override execution timeout for this call @@ -144,6 +151,16 @@ gemini-bridge/ - **File Handling**: Inline mode streams truncated snippets with warnings; `at_command` mode passes `@` directives for Gemini CLI to resolve - **Example**: Code reviews, debugging specific files, analyzing project structure +### `web_search` +- **Purpose**: Ask Gemini queries with web search context. Uses Gemini CLI's automatic web search when the model determines it's needed. Best-effort functionality - not guaranteed for every query. +- **Parameters**: + - `query` (required): Search query or question to look up on the web + - `directory` (required): Working directory for command execution + - `model` (optional): Model name (flash, pro, or custom) + - `timeout_seconds` (optional): Override execution timeout for this call +- **Use Case**: Getting current information, latest news, recent documentation +- **Example**: "latest Python version", "current React best practices" + ## Error Handling & Troubleshooting ### Common Error Patterns diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 10cd08a..b9c5307 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,26 +73,24 @@ Before contributing, make sure you have: ### Example code style: ```python -from typing import Optional, List import subprocess -import json def consult_gemini( - query: str, - directory: str = ".", - model: Optional[str] = None + query: str, + directory: str = ".", + model: str | None = None ) -> str: """ Send a query to Gemini CLI. - + Args: query: The question or prompt to send directory: Working directory for the query - model: Optional model name (flash, pro) - + model: Optional model name (flash, pro, flash-lite, 3-pro, etc.) + Returns: Gemini's response as a string - + Raises: RuntimeError: If CLI is not available or query fails """ @@ -209,6 +207,7 @@ Before submitting, verify: - [ ] MCP server starts without errors - [ ] `consult_gemini` tool works with basic queries - [ ] `consult_gemini_with_files` tool works with file attachments +- [ ] `web_search` tool works for web queries - [ ] Error handling works properly (try invalid queries) - [ ] Both `start_server_dev.sh` and `start_server_uvx.sh` work - [ ] Documentation is updated and accurate @@ -217,8 +216,8 @@ Before submitting, verify: If possible, test with: - Claude Code integration -- Different Python versions (3.9, 3.10, 3.11, 3.12) -- Various Gemini models (flash, pro) +- Different Python versions (3.10, 3.11, 3.12) +- Various Gemini models (flash, pro, flash-lite, 3-pro, 3-flash, 3.1-pro, auto) ## 🆘 Getting Help diff --git a/README.md b/README.md index 9de8b4b..4f11b87 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,13 @@ A lightweight MCP (Model Context Protocol) server that enables AI coding assista ## ✨ Features - **Direct Gemini CLI Integration**: Zero API costs using official Gemini CLI -- **Simple MCP Tools**: Two core functions for basic queries and file analysis +- **Three MCP Tools**: Basic queries, file analysis, and web search capabilities - **Stateless Operation**: No sessions, caching, or complex state management - **Production Ready**: Robust error handling with configurable 60-second timeouts - **Minimal Dependencies**: Only requires `mcp>=1.0.0` and Gemini CLI - **Easy Deployment**: Support for both uvx and traditional pip installation - **Universal MCP Compatibility**: Works with any MCP-compatible AI coding assistant +- **Modern Python**: Uses pathlib and modern type hints (Python 3.10+) ## 🚀 Quick Start @@ -389,8 +390,8 @@ Direct CLI bridge for simple queries. **Parameters:** - `query` (string): The question or prompt to send to Gemini -- `directory` (string): Working directory for the query (default: current directory) -- `model` (string, optional): Model to use - "flash" or "pro" (default: "flash") +- `directory` (string): Working directory for the query +- `model` (string, optional): Model to use - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", or "auto" (default: "flash") - `timeout_seconds` (int, optional): Override the execution timeout for this request **Example:** @@ -409,7 +410,7 @@ CLI bridge with file attachments for detailed analysis. - `query` (string): The question or prompt to send to Gemini - `directory` (string): Working directory for the query - `files` (list): List of file paths relative to the directory -- `model` (string, optional): Model to use - "flash" or "pro" (default: "flash") +- `model` (string, optional): Model to use - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", or "auto" (default: "flash") - `timeout_seconds` (int, optional): Override the execution timeout for this request - `mode` (string, optional): Either `"inline"` (default) to stream file contents or `"at_command"` to let Gemini CLI resolve `@path` references itself @@ -426,6 +427,23 @@ consult_gemini_with_files( **Tip:** When scanning large trees, switch to `mode="at_command"` so the Gemini CLI handles file globbing and truncation natively. +### `web_search` +Ask Gemini queries with web search context. Uses Gemini CLI's automatic web search when the model determines it's needed. Best-effort functionality - not guaranteed for every query. + +**Parameters:** +- `query` (string): Search query or question to look up on the web +- `directory` (string): Working directory for command execution +- `model` (string, optional): Model to use - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", or "auto" (default: "flash") +- `timeout_seconds` (int, optional): Override the execution timeout for this request + +**Example:** +```python +web_search( + query="latest Python version and new features", + model="flash" +) +``` + ## 📋 Usage Examples ### Basic Code Analysis @@ -459,6 +477,15 @@ consult_gemini_with_files( ) ``` +### Web Search +```python +# Get current information from the web +web_search( + query="latest Python version and new features in 3.13", + model="flash" +) +``` + ### Large File Safeguards - Inline transfers cap at ~256 KB per file and ~512 KB per request to avoid hangs. - Oversized files are truncated to head/tail snippets with a warning in the MCP response. diff --git a/SECURITY.md b/SECURITY.md index c6bd60e..d1e4ebb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -166,7 +166,7 @@ We follow responsible disclosure practices: ### System Dependencies -- **Python**: Use supported Python versions (3.9+) +- **Python**: Use supported Python versions (3.10+) - **Operating System**: Keep OS updated for subprocess security - **Network**: Secure network configuration recommended diff --git a/pyproject.toml b/pyproject.toml index 80a23d0..303fb45 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "gemini-bridge" -version = "1.2.0" +version = "1.3.0" description = "Lightweight MCP server bridging Claude Code to Google's Gemini AI via official CLI" readme = "README.md" license = "MIT" diff --git a/src/__init__.py b/src/__init__.py index c23ee26..488e4a9 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -2,5 +2,5 @@ from .mcp_server import main -__version__ = "1.2.0" +__version__ = "1.3.0" __all__ = ["main"] diff --git a/src/mcp_server.py b/src/mcp_server.py index 6a3b2b7..03b8cac 100644 --- a/src/mcp_server.py +++ b/src/mcp_server.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """ Gemini MCP Server - Simple CLI Bridge -Version 1.2.0 +Version 1.3.0 A minimal MCP server to interface with Gemini AI via the gemini CLI. Created by @shelakh/elyin """ @@ -12,7 +12,7 @@ import os import shutil import subprocess -from typing import List, Optional, Tuple +from pathlib import Path from mcp.server.fastmcp import FastMCP @@ -26,7 +26,7 @@ INLINE_CHUNK_TAIL_BYTES = int(os.getenv("GEMINI_BRIDGE_INLINE_TAIL_BYTES", str(32 * 1024))) -def _normalize_model_name(model: Optional[str]) -> str: +def _normalize_model_name(model: str | None) -> str: """ Normalize user-provided model identifiers to canonical Gemini CLI model names. Defaults to gemini-2.5-flash when not provided or unrecognized. @@ -34,8 +34,11 @@ def _normalize_model_name(model: Optional[str]) -> str: Accepted forms: - "flash", "2.5-flash", "gemini-2.5-flash" -> gemini-2.5-flash - "pro", "2.5-pro", "gemini-2.5-pro" -> gemini-2.5-pro + - "flash-lite", "2.5-flash-lite", "2.5-lite", "gemini-2.5-flash-lite", "gemini-2.5-lite" -> gemini-2.5-flash-lite - "3-pro", "gemini-3-pro", "gemini-3-pro-preview" -> gemini-3-pro-preview - "3-flash", "gemini-3-flash", "gemini-3-flash-preview" -> gemini-3-flash-preview + - "3.1-pro", "gemini-3.1-pro", "gemini-3.1-pro-preview" -> gemini-3.1-pro-preview + - "3.1-flash-lite", "gemini-3.1-flash-lite", "gemini-3.1-flash-lite-preview" -> gemini-3.1-flash-lite-preview - "auto" -> auto (model router, lets CLI choose optimal model) """ if not model: @@ -48,12 +51,22 @@ def _normalize_model_name(model: Optional[str]) -> str: if value in {"pro", "2.5-pro", "gemini-2.5-pro"}: return "gemini-2.5-pro" + # Gemini 2.5 Lite + if value in {"flash-lite", "2.5-flash-lite", "2.5-lite", "gemini-2.5-flash-lite", "gemini-2.5-lite"}: + return "gemini-2.5-flash-lite" + # Gemini 3 aliases (preview models) if value in {"3-pro", "gemini-3-pro", "gemini-3-pro-preview"}: return "gemini-3-pro-preview" if value in {"3-flash", "gemini-3-flash", "gemini-3-flash-preview"}: return "gemini-3-flash-preview" + # Gemini 3.1 series + if value in {"3.1-pro", "gemini-3.1-pro", "gemini-3.1-pro-preview"}: + return "gemini-3.1-pro-preview" + if value in {"3.1-flash-lite", "gemini-3.1-flash-lite", "gemini-3.1-flash-lite-preview"}: + return "gemini-3.1-flash-lite-preview" + # Model router (let CLI choose best model) if value == "auto": return "auto" @@ -89,7 +102,7 @@ def _get_timeout() -> int: return 60 -def _coerce_timeout(timeout_seconds: Optional[int]) -> int: +def _coerce_timeout(timeout_seconds: int | None) -> int: """Return a positive timeout, preferring explicit overrides.""" if timeout_seconds is None: return _get_timeout() @@ -113,9 +126,14 @@ def _coerce_timeout(timeout_seconds: Optional[int]) -> int: return timeout -def _resolve_path(directory: str, candidate: str) -> Tuple[str, Optional[str]]: +def _resolve_path(directory: str, candidate: str) -> tuple[str, str | None]: """Return absolute path and relative display path rooted at directory.""" - abs_path = candidate if os.path.isabs(candidate) else os.path.join(directory, candidate) + candidate_path = Path(candidate) + abs_path = ( + str(candidate_path) + if candidate_path.is_absolute() + else str(Path(directory) / candidate) + ) try: rel_path = os.path.relpath(abs_path, directory) except ValueError: @@ -125,16 +143,17 @@ def _resolve_path(directory: str, candidate: str) -> Tuple[str, Optional[str]]: return abs_path, rel_path -def _read_file_for_inline(abs_path: str) -> Tuple[str, bool, int]: +def _read_file_for_inline(abs_path: str) -> tuple[str, bool, int]: """Read file with truncation safeguards. Returns tuple of (content, truncated flag, bytes_used). """ - size = os.path.getsize(abs_path) + abs_path_obj = Path(abs_path) + size = abs_path_obj.stat().st_size truncated = False if size <= MAX_INLINE_FILE_BYTES: - with open(abs_path, "r", encoding="utf-8", errors="ignore") as handle: + with abs_path_obj.open(encoding="utf-8", errors="ignore") as handle: content = handle.read() return content, truncated, min(size, MAX_INLINE_FILE_BYTES) @@ -142,7 +161,7 @@ def _read_file_for_inline(abs_path: str) -> Tuple[str, bool, int]: head_bytes = max(INLINE_CHUNK_HEAD_BYTES, 1) tail_bytes = max(INLINE_CHUNK_TAIL_BYTES, 0) - with open(abs_path, "rb") as handle: + with abs_path_obj.open("rb") as handle: head = handle.read(head_bytes) tail = b"" if tail_bytes > 0 and size > head_bytes: @@ -160,10 +179,10 @@ def _read_file_for_inline(abs_path: str) -> Tuple[str, bool, int]: return snippet, truncated, bytes_counted -def _prepare_inline_payload(directory: str, files: List[str]) -> Tuple[str, List[str]]: +def _prepare_inline_payload(directory: str, files: list[str]) -> tuple[str, list[str]]: """Return stdin payload for inline mode and any warnings.""" - warnings: List[str] = [] - file_blocks: List[str] = [] + warnings: list[str] = [] + file_blocks: list[str] = [] total_bytes = 0 processed = 0 @@ -173,9 +192,9 @@ def _prepare_inline_payload(directory: str, files: List[str]) -> Tuple[str, List for original_path in files: abs_path, rel_path = _resolve_path(directory, original_path) - display_name = rel_path or os.path.basename(abs_path) + display_name = rel_path or Path(abs_path).name - if not os.path.exists(abs_path): + if not Path(abs_path).exists(): warnings.append(f"Skipped missing file: {display_name}") continue @@ -214,14 +233,14 @@ def _prepare_inline_payload(directory: str, files: List[str]) -> Tuple[str, List return payload, warnings -def _prepare_at_command_prompt(directory: str, files: List[str]) -> Tuple[str, List[str]]: +def _prepare_at_command_prompt(directory: str, files: list[str]) -> tuple[str, list[str]]: """Return prompt lines for @-command usage and warnings.""" - warnings: List[str] = [] - prompt_lines: List[str] = [] + warnings: list[str] = [] + prompt_lines: list[str] = [] for original_path in files: abs_path, rel_path = _resolve_path(directory, original_path) - if not os.path.exists(abs_path): + if not Path(abs_path).exists(): warnings.append(f"Skipped missing file: {original_path}") continue if rel_path is None: @@ -241,8 +260,8 @@ def _prepare_at_command_prompt(directory: str, files: List[str]) -> Tuple[str, L def execute_gemini_simple( query: str, directory: str = ".", - model: Optional[str] = None, - timeout_seconds: Optional[int] = None, + model: str | None = None, + timeout_seconds: int | None = None, ) -> str: """ Execute gemini CLI command for simple queries without file attachments. @@ -258,9 +277,9 @@ def execute_gemini_simple( # Check if gemini CLI is available if not shutil.which("gemini"): return "Error: Gemini CLI not found. Install with: npm install -g @google/gemini-cli" - + # Validate directory - if not os.path.isdir(directory): + if not Path(directory).is_dir(): return f"Error: Directory does not exist: {directory}" # Build command - use stdin for input to avoid hanging @@ -282,10 +301,19 @@ def execute_gemini_simple( if result.returncode == 0: return result.stdout.strip() if result.stdout.strip() else "No output from Gemini CLI" else: - return f"Gemini CLI Error: {result.stderr.strip()}" - + error_msg = result.stderr.strip() + # Provide helpful suggestions for common errors + if "not available" in error_msg.lower() or "unauthorized" in error_msg.lower(): + return f"Gemini CLI Error: Model '{selected_model}' may not be available for your account. Try: 'flash', 'flash-lite', or 'auto'. Details: {error_msg}" + elif "authentication" in error_msg.lower() or "auth" in error_msg.lower(): + return f"Gemini CLI Error: Authentication required. Run: gemini auth login. Details: {error_msg}" + else: + return f"Gemini CLI Error: {error_msg}" + except subprocess.TimeoutExpired: - return f"Error: Gemini CLI command timed out after {timeout} seconds" + return f"Error: Gemini CLI command timed out after {timeout} seconds. Try increasing timeout or simplifying your query." + except FileNotFoundError: + return "Error: Gemini CLI not found. Install with: npm install -g @google/gemini-cli" except Exception as e: return f"Error executing Gemini CLI: {str(e)}" @@ -293,9 +321,9 @@ def execute_gemini_simple( def execute_gemini_with_files( query: str, directory: str = ".", - files: Optional[List[str]] = None, - model: Optional[str] = None, - timeout_seconds: Optional[int] = None, + files: list[str] | None = None, + model: str | None = None, + timeout_seconds: int | None = None, mode: str = "inline", ) -> str: """ @@ -313,9 +341,9 @@ def execute_gemini_with_files( # Check if gemini CLI is available if not shutil.which("gemini"): return "Error: Gemini CLI not found. Install with: npm install -g @google/gemini-cli" - + # Validate directory - if not os.path.isdir(directory): + if not Path(directory).is_dir(): return f"Error: Directory does not exist: {directory}" # Validate files parameter @@ -327,7 +355,7 @@ def execute_gemini_with_files( cmd = ["gemini", "-m", selected_model] mode_normalized = mode.lower() - warnings: List[str] + warnings: list[str] if mode_normalized not in {"inline", "at_command"}: return f"Error: Unsupported files mode '{mode}'. Use 'inline' or 'at_command'." @@ -356,7 +384,14 @@ def execute_gemini_with_files( if result.returncode == 0: output = result.stdout.strip() if result.stdout.strip() else "No output from Gemini CLI" else: - output = f"Gemini CLI Error: {result.stderr.strip()}" + error_msg = result.stderr.strip() + # Provide helpful suggestions for common errors + if "not available" in error_msg.lower() or "unauthorized" in error_msg.lower(): + output = f"Gemini CLI Error: Model '{selected_model}' may not be available for your account. Try: 'flash', 'flash-lite', or 'auto'. Details: {error_msg}" + elif "authentication" in error_msg.lower() or "auth" in error_msg.lower(): + output = f"Gemini CLI Error: Authentication required. Run: gemini auth login. Details: {error_msg}" + else: + output = f"Gemini CLI Error: {error_msg}" if warnings: warning_block = "Warnings:\n" + "\n".join(f"- {w}" for w in warnings) @@ -364,7 +399,9 @@ def execute_gemini_with_files( return output except subprocess.TimeoutExpired: - return f"Error: Gemini CLI command timed out after {timeout} seconds" + return f"Error: Gemini CLI command timed out after {timeout} seconds. Try increasing timeout or simplifying your query." + except FileNotFoundError: + return "Error: Gemini CLI not found. Install with: npm install -g @google/gemini-cli" except Exception as e: return f"Error executing Gemini CLI: {str(e)}" @@ -418,6 +455,32 @@ def consult_gemini_with_files( return execute_gemini_with_files(query, directory, files, model, timeout_seconds, mode) +@mcp.tool() +def web_search( + query: str, + directory: str = ".", + model: str | None = None, + timeout_seconds: int | None = None, +) -> str: + """Ask Gemini queries with web search context. + + Note: This uses Gemini CLI's automatic web search capability. + The model determines when to search based on query context. + Best-effort web search - not guaranteed for every query. + + Args: + query: Search query or question to look up on the web + directory: Working directory for command execution + model: Optional model alias (flash, pro, or custom) + timeout_seconds: Optional per-call timeout override in seconds + + Returns: + Gemini's response with potential web sources + """ + search_prompt = f"Please use web search to find current information about: {query}" + return execute_gemini_simple(search_prompt, directory, model, timeout_seconds) + + def main(): """Entry point for the MCP server.""" mcp.run() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 55e08f9..acc3ec7 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -25,6 +25,35 @@ def test_normalize_model_name_pro_alias(): assert mcp_server._normalize_model_name("2.5-pro") == "gemini-2.5-pro" +def test_normalize_model_name_flash_lite(): + assert mcp_server._normalize_model_name("flash-lite") == "gemini-2.5-flash-lite" + assert mcp_server._normalize_model_name("2.5-flash-lite") == "gemini-2.5-flash-lite" + + +def test_normalize_model_name_3_series(): + assert mcp_server._normalize_model_name("3-pro") == "gemini-3-pro-preview" + assert mcp_server._normalize_model_name("3-flash") == "gemini-3-flash-preview" + + +def test_normalize_model_name_3_1_series(): + assert mcp_server._normalize_model_name("3.1-pro") == "gemini-3.1-pro-preview" + assert mcp_server._normalize_model_name("gemini-3.1-pro") == "gemini-3.1-pro-preview" + + +def test_normalize_model_name_3_1_flash_lite(): + assert mcp_server._normalize_model_name("3.1-flash-lite") == "gemini-3.1-flash-lite-preview" + assert mcp_server._normalize_model_name("gemini-3.1-flash-lite") == "gemini-3.1-flash-lite-preview" + + +def test_normalize_model_name_2_5_lite_aliases(): + assert mcp_server._normalize_model_name("2.5-lite") == "gemini-2.5-flash-lite" + assert mcp_server._normalize_model_name("gemini-2.5-lite") == "gemini-2.5-flash-lite" + + +def test_normalize_model_name_auto_router(): + assert mcp_server._normalize_model_name("auto") == "auto" + + def test_normalize_model_name_passthrough(): assert mcp_server._normalize_model_name("gemini-exp-1201") == "gemini-exp-1201" @@ -96,7 +125,31 @@ def fake_run(cmd, **kwargs): monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) response = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) - assert response == "Gemini CLI Error: boom" + assert "Gemini CLI Error: boom" in response + + +def test_execute_gemini_simple_handles_model_unavailable(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, **kwargs): + return SimpleNamespace(returncode=1, stdout="", stderr="Model not available for free tier") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + response = mcp_server.execute_gemini_simple("Hello", str(tmp_path), model="pro") + assert "not be available for your account" in response + assert "Try: 'flash', 'flash-lite', or 'auto'" in response + + +def test_execute_gemini_simple_handles_auth_error(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, **kwargs): + return SimpleNamespace(returncode=1, stdout="", stderr="Authentication required") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + response = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) + assert "Authentication required" in response + assert "gemini auth login" in response def test_execute_gemini_simple_handles_timeout(tmp_path, monkeypatch): @@ -108,6 +161,15 @@ def fake_run(cmd, **kwargs): monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) response = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) assert "command timed out" in response + assert "Try increasing timeout" in response + + +def test_execute_gemini_simple_handles_missing_cli(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: None) + + response = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) + assert "Gemini CLI not found" in response + assert "npm install -g @google/gemini-cli" in response def test_execute_gemini_with_files_requires_files(tmp_path, monkeypatch): @@ -239,3 +301,53 @@ def fake_run(cmd, **kwargs): def test_consult_gemini_with_files_requires_list(tmp_path): result = mcp_server.consult_gemini_with_files("Hello", str(tmp_path), files=None) assert "files parameter is required" in result + + +def test_web_search_prepends_search_instruction(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, **kwargs): + assert "Please use web search to find current information about" in kwargs["input"] + assert "Python version" in kwargs["input"] + return SimpleNamespace(returncode=0, stdout="Search results", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.web_search("Python version", str(tmp_path)) + assert "Search results" in result + + +def test_web_search_passes_model_and_timeout(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, cwd, capture_output, text, timeout, input): + assert cmd == ["gemini", "-m", "gemini-2.5-pro"] + assert timeout == 30 + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.web_search("test", str(tmp_path), model="pro", timeout_seconds=30) + assert result == "ok" + + +def test_web_search_with_3_1_flash_lite_model(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, cwd, capture_output, text, timeout, input): + assert cmd == ["gemini", "-m", "gemini-3.1-flash-lite-preview"] + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.web_search("test", str(tmp_path), model="3.1-flash-lite") + assert result == "ok" + + +def test_web_search_with_2_5_lite_alias(tmp_path, monkeypatch): + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, cwd, capture_output, text, timeout, input): + assert cmd == ["gemini", "-m", "gemini-2.5-flash-lite"] + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.web_search("test", str(tmp_path), model="2.5-lite") + assert result == "ok"