Gemini CLI服务端

一个允许Claude Code调用Gemini CLI作为工具的MCP服务器,利用Gemini的大上下文窗口进行研究、代码审查和分析任务。

  • by stevenc81
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 stevenc81/gemini-mcp-server

使用说明

gemini mcp服务器

允许Claude Code调用Gemini CLI作为工具的MCP服务器。利用Gemini的大型上下文窗口进行研究、代码审查和分析任务。

运作原理

Claude Code发送轻量级指令(提示、文件路径、glob模式)。服务器解析文件并在服务器端读取它们,然后将所有内容传输到 gemini -p 通过stdin。Gemini的回复以文本形式返回给Claude Code。

这意味着文件内容永远不会占用Claude的上下文窗口,只占用Gemini的上下文窗口(最多1M+令牌)。

需求

设置

  1. 安装并验证 Gemini CLI:
npm install -g @google/gemini-cli
gemini  # follow the auth prompts
  1. 克隆此仓库:
git clone https://github.com/stevenc81/gemini-mcp-server.git
  1. 验证Gemini CLI是否正常工作:
gemini -p "hello" -o json
  1. 使用克劳德代码注册服务器:
claude mcp add gemini --transport stdio --scope user -- uv run --project /path/to/gemini-mcp-server gemini-mcp-server

替换 /path/to/gemini-mcp-server 带有克隆仓库的绝对路径。

你现在应该可以让克劳德使用 gemini_query 工具。

用法

注册后,Claude Code可以调用 gemini_query 工具:

# Simple question
"Ask Gemini what the best approach for rate limiting in Go is"

# Code review with file context
"Have Gemini review src/auth.ts and src/auth.test.ts for security issues"

# Large codebase analysis
"Ask Gemini to find inconsistent error handling across src/**/*.ts"

# Recursive directory analysis
"Have Gemini review the entire lib/ directory for dead code"

# Multi-turn conversations
"Ask Gemini to review this file, then follow up with the session ID to ask about specific functions"

# Use a specific model
"Ask Gemini using gemini-2.5-flash to summarize this file"

参数

  • prompt (string,必填)——双子座的指令或问题
  • files (string[],可选)--要作为上下文包含的绝对文件路径
  • glob_patterns (string[],可选)--服务器端解析的Glob模式
  • directories (string[],可选)--递归包含的目录路径
  • model (string,可选)--覆盖模型。跳过回退链,仅使用此模型
  • timeout (int,可选)--等待的最长秒数。默认值120
  • session_id (string,可选)--通过传递之前响应中的会话ID来恢复之前的Gemini对话

模型回退

当没有指定模型时,服务器会按顺序尝试这些模型,直到成功为止:

  1. gemini-3.1-pro-preview
  2. gemini-3-flash-preview
  3. gemini-2.5-pro
  4. gemini-2.5-flash

如果你明确指定了一个模型(例如。, model="gemini-2.5-flash"),它直接使用该模型,没有回退。

多回合对话

每个响应都在元数据页脚中包含一个会话ID。把它传回去 session_id 要继续对话,请执行以下操作:

  1. 第一个查询返回: Session ID: abc-123
  2. 后续查询 session_id="abc-123" 从Gemini中断的地方继续

当发生模型回退时,会话ID会被丢弃,因为会话属于原始模型。

文件过滤

从解析文件时 directories 或 glob_patterns,服务器自动跳过二进制和垃圾文件(图像、编译的工件、档案、字体、, .DS_Store等等)。通过明确列出的文件 files 参数永远不会被过滤。

安全限制

  • 每次查询最多500个文件(可通过配置 max_files 在 resolve_files)
  • 最大10MB总上下文(可通过配置 max_bytes 在 read_files_as_context)
  • 检查文件大小 os.path.getsize() 阅读前防止OOM
  • 文件路径在发送到Gemini的上下文中显示为相对路径

鲁棒性

  • JSON解析处理CLI警告和与响应混合的非JSON输出
  • 阻塞文件I/O通过以下方式卸载到线程 asyncio.to_thread
  • 子流程用途 create_subprocess_exec (无外壳注射风险)
  • 超时可防止Gemini CLI进程挂起

发展

# Install dependencies
uv sync

# Run tests
uv run pytest -v

# Run the server locally
uv run gemini-mcp-server