8000 feat: enhance configuration with trust support and increased limits by FojleRabbiRabib · Pull Request #8 · eLyiN/gemini-bridge · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 32 additions & 12 deletions src/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,29 @@

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)))


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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Comment on lines +301 to +303

# Execute CLI command - simple timeout, no retries
timeout = _coerce_timeout(timeout_seconds)
Expand Down Expand Up @@ -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]

Expand Down
219 changes: 209 additions & 10 deletions tests/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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):
Expand All @@ -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


Expand All @@ -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="")
Expand Down Expand Up @@ -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="")
Expand Down Expand Up @@ -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="")
Expand All @@ -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="")

Expand All @@ -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)
Expand All @@ -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&q BD0 uot;, 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
Comment on lines +463 to +483


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"
Loading
0