From 17e82418da9f8ee05f8d838d96c33e5a1a2d51b0 Mon Sep 17 00:00:00 2001 From: "Fojle Rabbi (Rabib)" <36526962+FojleRabbiRabib@users.noreply.github.com> Date: Tue, 28 Apr 2026 23:04:01 +0600 Subject: [PATCH] feat: enhance configuration with trust support, increased limits, and improved defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Major enhancements to address user-reported issues and improve configurability. - Add automatic --skip-trust flag for headless/automated environments - New GEMINI_BRIDGE_TRUST_WORKSPACE environment variable (default: true) - Resolves "Gemini CLI is not running in a trusted directory" errors - Can be disabled for environments requiring manual trust approval - Increase default timeout: 60 seconds → 120 seconds - Better support for large file analysis and complex queries - New GEMINI_BRIDGE_DEFAULT_TIMEOUT environment variable - MAX_INLINE_FILE_COUNT: 10 → 30 files (3x improvement) - MAX_INLINE_TOTAL_BYTES: 512KB → 1MB (2x improvement) - MAX_INLINE_FILE_BYTES: 256KB → 512KB (2x improvement) - Reduces "Inline file limit reached" warnings significantly - New GEMINI_BRIDGE_DEFAULT_MODEL environment variable (default: flash) - All major options now configurable via environment variables - Better support for different usage patterns and requirements - Add 11 new tests for trust functionality and configuration - Update 4 existing tests for new command format and defaults - All 45 tests passing with comprehensive coverage - New tests cover: trust workspace, file limits, custom defaults, env var priority - GEMINI_BRIDGE_DEFAULT_TIMEOUT: Set default timeout (default: 120) - GEMINI_BRIDGE_DEFAULT_MODEL: Set default model (default: flash) - GEMINI_BRIDGE_TRUST_WORKSPACE: Auto-trust workspaces (default: true) - All existing functionality preserved - Existing environment variables continue to work - Per-call parameters override environment defaults - No breaking changes to MCP tool interfaces Resolves issues with file attachment limits and trust errors in automated environments while maintaining full backward compatibility. --- src/mcp_server.py | 44 +++++--- tests/test_mcp_server.py | 219 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 241 insertions(+), 22 deletions(-) diff --git a/src/mcp_server.py b/src/mcp_server.py index 03b8cac..fecebbc 100644 --- a/src/mcp_server.py +++ b/src/mcp_server.py @@ -18,10 +18,21 @@ mcp = FastMCP("gemini-assistant") +# ============================================================================ +# CONFIGURATION - Environment Variables with Sensible Defaults +# ============================================================================ + +# Timeout Configuration +DEFAULT_TIMEOUT = int(os.getenv("GEMINI_BRIDGE_DEFAULT_TIMEOUT", "120")) # Increased from 60 to 120 seconds +TRUST_WORKSPACE = os.getenv("GEMINI_BRIDGE_TRUST_WORKSPACE", "true") # Auto-trust workspaces for MCP usage + +# Default Model Configuration +DEFAULT_MODEL = os.getenv("GEMINI_BRIDGE_DEFAULT_MODEL", "flash") # Options: flash, pro, flash-lite, auto + # Inline attachment safeguards — tuned for quick, safe transfers. -MAX_INLINE_FILE_COUNT = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_FILE_COUNT", "10")) -MAX_INLINE_TOTAL_BYTES = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_TOTAL_BYTES", str(512 * 1024))) -MAX_INLINE_FILE_BYTES = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_FILE_BYTES", str(256 * 1024))) +MAX_INLINE_FILE_COUNT = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_FILE_COUNT", "30")) # Increased from 10 to 30 +MAX_INLINE_TOTAL_BYTES = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_TOTAL_BYTES", str(1024 * 1024))) # 1MB instead of 512KB +MAX_INLINE_FILE_BYTES = int(os.getenv("GEMINI_BRIDGE_MAX_INLINE_FILE_BYTES", str(512 * 1024))) # 512KB instead of 256KB INLINE_CHUNK_HEAD_BYTES = int(os.getenv("GEMINI_BRIDGE_INLINE_HEAD_BYTES", str(64 * 1024))) INLINE_CHUNK_TAIL_BYTES = int(os.getenv("GEMINI_BRIDGE_INLINE_TAIL_BYTES", str(32 * 1024))) @@ -29,7 +40,7 @@ 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. + Defaults to DEFAULT_MODEL environment variable or gemini-2.5-flash when not provided or unrecognized. Accepted forms: - "flash", "2.5-flash", "gemini-2.5-flash" -> gemini-2.5-flash @@ -42,7 +53,8 @@ def _normalize_model_name(model: str | None) -> str: - "auto" -> auto (model router, lets CLI choose optimal model) """ if not model: - return "gemini-2.5-flash" + model = DEFAULT_MODEL + value = model.strip().lower() # Gemini 2.5 aliases @@ -82,24 +94,24 @@ def _normalize_model_name(model: str | None) -> str: def _get_timeout() -> int: """ Get the timeout value from environment variable GEMINI_BRIDGE_TIMEOUT. - Defaults to 60 seconds if not set or invalid. - + Defaults to DEFAULT_TIMEOUT (120 seconds) if not set or invalid. + Returns: Timeout value in seconds (positive integer) """ timeout_str = os.getenv("GEMINI_BRIDGE_TIMEOUT") if not timeout_str: - return 60 + return DEFAULT_TIMEOUT try: timeout = int(timeout_str) if timeout <= 0: - logging.warning("Invalid GEMINI_BRIDGE_TIMEOUT value '%s' (must be positive). Using default 60 seconds.", timeout_str) - return 60 + logging.warning("Invalid GEMINI_BRIDGE_TIMEOUT value '%s' (must be positive). Using default %d seconds.", timeout_str, DEFAULT_TIMEOUT) + return DEFAULT_TIMEOUT return timeout except ValueError: - logging.warning("Invalid GEMINI_BRIDGE_TIMEOUT value '%s' (must be integer). Using default 60 seconds.", timeout_str) - return 60 + logging.warning("Invalid GEMINI_BRIDGE_TIMEOUT value '%s' (must be integer). Using default %d seconds.", timeout_str, DEFAULT_TIMEOUT) + return DEFAULT_TIMEOUT def _coerce_timeout(timeout_seconds: int | None) -> int: @@ -285,6 +297,10 @@ def execute_gemini_simple( # Build command - use stdin for input to avoid hanging selected_model = _normalize_model_name(model) cmd = ["gemini", "-m", selected_model] + + # Add trust flag for automated environments if enabled + if TRUST_WORKSPACE.lower() == "true": + cmd.append("--skip-trust") # Execute CLI command - simple timeout, no retries timeout = _coerce_timeout(timeout_seconds) @@ -354,6 +370,10 @@ def execute_gemini_with_files( selected_model = _normalize_model_name(model) cmd = ["gemini", "-m", selected_model] + # Add trust flag for automated environments if enabled + if TRUST_WORKSPACE.lower() == "true": + cmd.append("--skip-trust") + mode_normalized = mode.lower() warnings: list[str] diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index acc3ec7..11915ef 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -11,15 +11,33 @@ @pytest.fixture(autouse=True) -def clear_timeout_env(monkeypatch): +def clear_env_vars(monkeypatch): + """Clear all relevant environment variables before each test.""" monkeypatch.delenv("GEMINI_BRIDGE_TIMEOUT", raising=False) + monkeypatch.delenv("GEMINI_BRIDGE_DEFAULT_TIMEOUT", raising=False) + monkeypatch.delenv("GEMINI_BRIDGE_DEFAULT_MODEL", raising=False) + monkeypatch.delenv("GEMINI_BRIDGE_TRUST_WORKSPACE", raising=False) def test_normalize_model_name_defaults(): + # Test default model (respects GEMINI_BRIDGE_DEFAULT_MODEL env var) assert mcp_server._normalize_model_name(None) == "gemini-2.5-flash" assert mcp_server._normalize_model_name(" flash ") == "gemini-2.5-flash" +def test_normalize_model_name_with_custom_default(monkeypatch): + """Test that GEMINI_BRIDGE_DEFAULT_MODEL environment variable is respected.""" + import importlib + + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_MODEL", "pro") + importlib.reload(mcp_server) + assert mcp_server._normalize_model_name(None) == "gemini-2.5-pro" + + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_MODEL", "auto") + importlib.reload(mcp_server) + assert mcp_server._normalize_model_name(None) == "auto" + + def test_normalize_model_name_pro_alias(): assert mcp_server._normalize_model_name("pro") == "gemini-2.5-pro" assert mcp_server._normalize_model_name("2.5-pro") == "gemini-2.5-pro" @@ -58,8 +76,18 @@ def test_normalize_model_name_passthrough(): assert mcp_server._normalize_model_name("gemini-exp-1201") == "gemini-exp-1201" -def test_get_timeout_defaults_to_60(): - assert mcp_server._get_timeout() == 60 +def test_get_timeout_defaults_to_120(): + """Test that default timeout is now 120 seconds instead of 60.""" + assert mcp_server._get_timeout() == 120 + + +def test_get_timeout_with_custom_default(monkeypatch): + """Test that GEMINI_BRIDGE_DEFAULT_TIMEOUT environment variable is respected.""" + import importlib + + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_TIMEOUT", "180") + importlib.reload(mcp_server) + assert mcp_server._get_timeout() == 180 def test_get_timeout_returns_positive_integer(monkeypatch): @@ -68,14 +96,21 @@ def test_get_timeout_returns_positive_integer(monkeypatch): def test_get_timeout_handles_invalid_values(monkeypatch, caplog): + """Test that invalid timeout values fall back to default (120 seconds).""" + import importlib + + # Reset to default state first + monkeypatch.delenv("GEMINI_BRIDGE_DEFAULT_TIMEOUT", raising=False) + importlib.reload(mcp_server) + caplog.set_level("WARNING") monkeypatch.setenv("GEMINI_BRIDGE_TIMEOUT", "-5") - assert mcp_server._get_timeout() == 60 + assert mcp_server._get_timeout() == 120 # Updated from 60 to 120 assert "must be positive" in caplog.text caplog.clear() monkeypatch.setenv("GEMINI_BRIDGE_TIMEOUT", "abc") - assert mcp_server._get_timeout() == 60 + assert mcp_server._get_timeout() == 120 # Updated from 60 to 120 assert "must be integer" in caplog.text @@ -95,7 +130,8 @@ def test_execute_gemini_simple_success(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"] + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-2.5-flash", "--skip-trust"] assert cwd == str(tmp_path) assert input == "Hello" return SimpleNamespace(returncode=0, stdout="Answer\n", stderr="") @@ -184,7 +220,8 @@ def test_execute_gemini_with_files_reads_files(tmp_path, monkeypatch): sample_file.write_text("content", encoding="utf-8") def fake_run(cmd, **kwargs): - assert cmd == ["gemini", "-m", "gemini-2.5-flash"] + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-2.5-flash", "--skip-trust"] assert "=== example.txt ===" in kwargs["input"] assert "content" in kwargs["input"] return SimpleNamespace(returncode=0, stdout="ok", stderr="") @@ -307,6 +344,8 @@ def test_web_search_prepends_search_instruction(tmp_path, monkeypatch): monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") def fake_run(cmd, **kwargs): + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-2.5-flash", "--skip-trust"] 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="") @@ -320,7 +359,8 @@ 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"] + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-2.5-pro", "--skip-trust"] assert timeout == 30 return SimpleNamespace(returncode=0, stdout="ok", stderr="") @@ -333,7 +373,8 @@ 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"] + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-3.1-flash-lite-preview", "--skip-trust"] return SimpleNamespace(returncode=0, stdout="ok", stderr="") monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) @@ -345,9 +386,167 @@ 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"] + # Updated to expect --skip-trust flag + assert cmd == ["gemini", "-m", "gemini-2.5-flash-lite", "--skip-trust"] 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" + + +# ============================================================================ +# NEW TESTS: Enhanced Configuration and Trust Functionality +# ============================================================================ + +def test_trust_workspace_enabled_by_default(tmp_path, monkeypatch): + """Test that trust workspace is enabled by default for MCP usage.""" + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, **kwargs): + # Should include --skip-trust flag by default + assert "--skip-trust" in cmd + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) + assert result == "ok" + + +def test_trust_workspace_can_be_disabled(tmp_path, monkeypatch): + """Test that trust workspace can be disabled via environment variable.""" + import importlib + + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + monkeypatch.setenv("GEMINI_BRIDGE_TRUST_WORKSPACE", "false") + importlib.reload(mcp_server) # Reload to pick up environment variable + + def fake_run(cmd, **kwargs): + # Should NOT include --skip-trust flag when disabled + assert "--skip-trust" not in cmd + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) + assert result == "ok" + + +def test_trust_workspace_with_files(tmp_path, monkeypatch): + """Test that trust flag is added for file operations too.""" + import importlib + + # Ensure we have clean environment state + monkeypatch.delenv("GEMINI_BRIDGE_TRUST_WORKSPACE", raising=False) + importlib.reload(mcp_server) + + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + sample_file = tmp_path / "test.txt" + sample_file.write_text("content") + + # Track the actual command that was passed + actual_cmd = [] + + def fake_run(cmd, **kwargs): + # Capture the command for verification + actual_cmd.append(cmd) + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.execute_gemini_with_files("Analyze", str(tmp_path), files=["test.txt"]) + + # Verify the command includes --skip-trust + assert len(actual_cmd) > 0, "fake_run was not called" + assert "--skip-trust" in actual_cmd[0], f"Expected --skip-trust in command: {actual_cmd[0]}" + assert "ok" in result + + +def test_increased_default_file_limits(monkeypatch): + """Test that default file limits have been increased.""" + # Test new defaults + assert mcp_server.MAX_INLINE_FILE_COUNT == 30 # Increased from 10 + assert mcp_server.MAX_INLINE_TOTAL_BYTES == 1024 * 1024 # 1MB instead of 512KB + assert mcp_server.MAX_INLINE_FILE_BYTES == 512 * 1024 # 512KB instead of 256KB + + +def test_file_limits_can_be_customized(monkeypatch): + """Test that file limits can be customized via environment variables.""" + monkeypatch.setenv("GEMINI_BRIDGE_MAX_INLINE_FILE_COUNT", "50") + monkeypatch.setenv("GEMINI_BRIDGE_MAX_INLINE_TOTAL_BYTES", str(2 * 1024 * 1024)) + monkeypatch.setenv("GEMINI_BRIDGE_MAX_INLINE_FILE_BYTES", str(1024 * 1024)) + + # Need to reload the module to pick up new environment variables + import importlib + importlib.reload(mcp_server) + + assert mcp_server.MAX_INLINE_FILE_COUNT == 50 + assert mcp_server.MAX_INLINE_TOTAL_BYTES == 2 * 1024 * 1024 + assert mcp_server.MAX_INLINE_FILE_BYTES == 1024 * 1024 + + +def test_timeout_uses_per_call_override(tmp_path, monkeypatch): + """Test that per-call timeout override works correctly.""" + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + + def fake_run(cmd, cwd, capture_output, text, timeout, input): + # Per-call timeout should override default + assert timeout == 45 + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.execute_gemini_simple("Hello", str(tmp_path), timeout_seconds=45) + assert result == "ok" + + +def test_default_timeout_env_var_priority(monkeypatch): + """Test that GEMINI_BRIDGE_TIMEOUT takes priority over DEFAULT_TIMEOUT.""" + # Set default timeout to 180 + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_TIMEOUT", "180") + + # Need to reload module to pick up environment variable + import importlib + importlib.reload(mcp_server) + + # Without GEMINI_BRIDGE_TIMEOUT, should use DEFAULT_TIMEOUT (180) + assert mcp_server._get_timeout() == 180 + + # With GEMINI_BRIDGE_TIMEOUT set, it should take priority + monkeypatch.setenv("GEMINI_BRIDGE_TIMEOUT", "90") + assert mcp_server._get_timeout() == 90 + + +def test_execute_gemini_simple_with_custom_default_model(tmp_path, monkeypatch): + """Test that custom default model is used when no model is specified.""" + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_MODEL", "pro") + + # Reload to pick up environment variable + import importlib + importlib.reload(mcp_server) + + def fake_run(cmd, **kwargs): + # Should use custom default model (pro -> gemini-2.5-pro) + assert cmd == ["gemini", "-m", "gemini-2.5-pro", "--skip-trust"] + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.execute_gemini_simple("Hello", str(tmp_path)) + assert result == "ok" + + +def test_web_search_with_custom_default_model(tmp_path, monkeypatch): + """Test that web search respects custom default model.""" + monkeypatch.setattr("src.mcp_server.shutil.which", lambda _: "gemini") + monkeypatch.setenv("GEMINI_BRIDGE_DEFAULT_MODEL", "flash-lite") + + # Reload to pick up environment variable + import importlib + importlib.reload(mcp_server) + + def fake_run(cmd, **kwargs): + # Should use custom default model (flash-lite -> gemini-2.5-flash-lite) + assert cmd == ["gemini", "-m", "gemini-2.5-flash-lite", "--skip-trust"] + return SimpleNamespace(returncode=0, stdout="ok", stderr="") + + monkeypatch.setattr("src.mcp_server.subprocess.run", fake_run) + result = mcp_server.web_search("test query", str(tmp_path)) + assert result == "ok"