带有 Gemini CLI 的 MCP 服务器
¥MCP servers with the Gemini CLI
本文档提供了使用 Gemini CLI 配置和使用模型上下文协议 (MCP) 服务器的指南。
¥This document provides a guide to configuring and using Model Context Protocol (MCP) servers with the Gemini CLI.
什么是 MCP 服务器?
¥What is an MCP server?
MCP 服务器是一个应用程序,它通过模型上下文协议 (MCP) 向 Gemini CLI 公开工具和资源,使其能够与外部系统和数据源交互。MCP 服务器充当 Gemini 模型与您的本地环境或其他服务(例如 API)之间的桥梁。
¥An MCP server is an application that exposes tools and resources to the Gemini CLI through the Model Context Protocol, allowing it to interact with external systems and data sources. MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
MCP 服务器使 Gemini CLI 能够:
¥An MCP server enables the Gemini CLI to:
发现工具:通过标准化模式定义列出可用的工具、其描述和参数。
¥Discover tools: List available tools, their descriptions, and parameters through standardized schema definitions.
执行工具:使用定义的参数调用特定工具并接收结构化响应。
¥Execute tools: Call specific tools with defined arguments and receive structured responses.
访问资源:从特定资源读取数据(尽管 Gemini CLI 主要关注工具执行)。
¥Access resources: Read data from specific resources (though the Gemini CLI primarily focuses on tool execution).
使用 MCP 服务器,您可以扩展 Gemini CLI 的功能以执行超出其内置功能的操作,例如与数据库、API、自定义脚本或专门的工作流进行交互。
¥With an MCP server, you can extend the Gemini CLI's capabilities to perform actions beyond its built-in features, such as interacting with databases, APIs, custom scripts, or specialized workflows.
核心集成架构
¥Core Integration Architecture
Gemini CLI 通过核心包中内置的复杂发现和执行系统与 MCP 服务器集成(packages/core/src/tools/):
¥The Gemini CLI integrates with MCP servers through a sophisticated discovery and execution system built into the core package (packages/core/src/tools/):
发现层(mcp-client.ts)
¥Discovery Layer (mcp-client.ts)
发现过程由discoverMcpTools(), 哪个:
¥The discovery process is orchestrated by discoverMcpTools(), which:
遍历已配置的服务器从你的
settings.jsonmcpServers配置¥Iterates through configured servers from your
settings.jsonmcpServersconfiguration建立连接使用适当的传输机制(Stdio、SSE 或 Streamable HTTP)
¥Establishes connections using appropriate transport mechanisms (Stdio, SSE, or Streamable HTTP)
获取工具定义使用 MCP 协议从每个服务器
¥Fetches tool definitions from each server using the MCP protocol
消毒并验证与 Gemini API 兼容的工具模式
¥Sanitizes and validates tool schemas for compatibility with the Gemini API
注册工具在具有冲突解决功能的全局工具注册表中
¥Registers tools in the global tool registry with conflict resolution
执行层(mcp-tool.ts)
¥Execution Layer (mcp-tool.ts)
每个发现的 MCP 工具都包装在DiscoveredMCPTool例如:
¥Each discovered MCP tool is wrapped in a DiscoveredMCPTool instance that:
处理确认逻辑基于服务器信任设置和用户偏好
¥Handles confirmation logic based on server trust settings and user preferences
管理工具执行通过使用适当的参数调用 MCP 服务器
¥Manages tool execution by calling the MCP server with proper parameters
处理响应用于 LLM 上下文和用户显示
¥Processes responses for both the LLM context and user display
保持连接状态并处理超时
¥Maintains connection state and handles timeouts
运输机制
¥Transport Mechanisms
Gemini CLI 支持三种 MCP 传输类型:
¥The Gemini CLI supports three MCP transport types:
标准输入输出传输:生成子进程并通过 stdin/stdout 进行通信
¥Stdio Transport: Spawns a subprocess and communicates via stdin/stdout
上交所运输:连接到服务器发送事件端点
¥SSE Transport: Connects to Server-Sent Events endpoints
可流式传输的 HTTP 传输:使用 HTTP 流进行通信
¥Streamable HTTP Transport: Uses HTTP streaming for communication
如何设置您的 MCP 服务器
¥How to set up your MCP server
Gemini CLI 使用mcpServers您的配置settings.json文件用于定位并连接 MCP 服务器。此配置支持使用不同传输机制的多个服务器。
¥The Gemini CLI uses the mcpServers configuration in your settings.json file to locate and connect to MCP servers. This configuration supports multiple servers with different transport mechanisms.
在 settings.json 中配置 MCP 服务器
¥Configure the MCP server in settings.json
您可以在全局级别配置 MCP 服务器~/.gemini/settings.json文件或项目根目录中,创建或打开.gemini/settings.json文件。在文件中,添加mcpServers配置块。
¥You can configure MCP servers at the global level in the ~/.gemini/settings.json file or in your project's root directory, create or open the .gemini/settings.json file. Within the file, add the mcpServers configuration block.
配置结构
¥Configuration Structure
添加mcpServers反对你的settings.json文件:
¥Add an mcpServers object to your settings.json file:
{ ...file contains other config objects
"mcpServers": {
"serverName": {
"command": "path/to/server",
"args": ["--arg1", "value1"],
"env": {
"API_KEY": "$MY_API_TOKEN"
},
"cwd": "./server-directory",
"timeout": 30000,
"trust": false
}
}
}
配置属性
¥Configuration Properties
每个服务器配置支持以下属性:
¥Each server configuration supports the following properties:
必填项(以下之一)
¥Required (one of the following)
command(字符串):Stdio 传输的可执行文件的路径¥
command(string): Path to the executable for Stdio transporturl(字符串): SSE 端点 URL(例如,"http://localhost:8080/sse")¥
url(string): SSE endpoint URL (e.g.,"http://localhost:8080/sse")httpUrl(字符串):HTTP 流式传输端点 URL¥
httpUrl(string): HTTP streaming endpoint URL
选修的
¥Optional
args(string[]): Stdio 传输的命令行参数¥
args(string[]): Command-line arguments for Stdio transportheaders(object): 使用时自定义 HTTP 标头url或者httpUrl¥
headers(object): Custom HTTP headers when usingurlorhttpUrlenv(对象):服务器进程的环境变量。值可以使用以下方式引用环境变量$VAR_NAME或者${VAR_NAME}句法¥
env(object): Environment variables for the server process. Values can reference environment variables using$VAR_NAMEor${VAR_NAME}syntaxcwd(字符串): Stdio 传输的工作目录¥
cwd(string): Working directory for Stdio transporttimeout(number): 请求超时时间(以毫秒为单位)(默认值:600,000ms = 10 分钟)¥
timeout(number): Request timeout in milliseconds (default: 600,000ms = 10 minutes)trust(布尔值): 当true,绕过此服务器的所有工具调用确认(默认:false)¥
trust(boolean): Whentrue, bypasses all tool call confirmations for this server (default:false)includeTools(string[]):要从此 MCP 服务器添加的工具名称列表。指定后,只有此处列出的工具可从此服务器使用(白名单行为)。如果未指定,则默认启用此服务器的所有工具。¥
includeTools(string[]): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (whitelist behavior). If not specified, all tools from the server are enabled by default.excludeTools(string[]):要从此 MCP 服务器中排除的工具名称列表。此处列出的工具即使已由服务器公开,也不会对模型可用。笔记:excludeTools优先于includeTools- 如果某个工具同时出现在两个列表中,则它将被排除。¥
excludeTools(string[]): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. Note:excludeToolstakes precedence overincludeTools- if a tool is in both lists, it will be excluded.
远程 MCP 服务器的 OAuth 支持
¥OAuth Support for Remote MCP Servers
Gemini CLI 支持使用 SSE 或 HTTP 传输对远程 MCP 服务器进行 OAuth 2.0 身份验证。这使得能够安全地访问需要身份验证的 MCP 服务器。
¥The Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using SSE or HTTP transports. This enables secure access to MCP servers that require authentication.
自动 OAuth 发现
¥Automatic OAuth Discovery
对于支持 OAuth 发现的服务器,您可以省略 OAuth 配置并让 CLI 自动发现它:
¥For servers that support OAuth discovery, you can omit the OAuth configuration and let the CLI discover it automatically:
{
"mcpServers": {
"discoveredServer": {
"url": "https://api.example.com/sse"
}
}
}
CLI 将自动:
¥The CLI will automatically:
检测服务器何时需要 OAuth 身份验证(401 个响应)
¥Detect when a server requires OAuth authentication (401 responses)
从服务器元数据中发现 OAuth 端点
¥Discover OAuth endpoints from server metadata
如果支持,则执行动态客户端注册
¥Perform dynamic client registration if supported
处理 OAuth 流程和令牌管理
¥Handle the OAuth flow and token management
身份验证流程
¥Authentication Flow
连接到启用 OAuth 的服务器时:
¥When connecting to an OAuth-enabled server:
初始连接尝试失败,显示 401 Unauthorized
¥Initial connection attempt fails with 401 Unauthorized
OAuth 发现查找授权和令牌端点
¥OAuth discovery finds authorization and token endpoints
浏览器打开用于用户身份验证(需要本地浏览器访问)
¥Browser opens for user authentication (requires local browser access)
授权码交换访问令牌
¥Authorization code is exchanged for access tokens
代币存储安全使用
¥Tokens are stored securely for future use
连接重试成功并带有有效令牌
¥Connection retry succeeds with valid tokens
浏览器重定向要求
¥Browser Redirect Requirements
重要的:OAuth 身份验证要求您的本地计算机可以:
¥Important: OAuth authentication requires that your local machine can:
打开 Web 浏览器进行身份验证
¥Open a web browser for authentication
接收重定向
http://localhost:7777/oauth/callback¥Receive redirects on
http://localhost:7777/oauth/callback
此功能在以下情况下不起作用:
¥This feature will not work in:
无需浏览器访问的无头环境
¥Headless environments without browser access
无需 X11 转发的远程 SSH 会话
¥Remote SSH sessions without X11 forwarding
不支持浏览器的容器化环境
¥Containerized environments without browser support
管理 OAuth 身份验证
¥Managing OAuth Authentication
使用/mcp auth管理 OAuth 身份验证的命令:
¥Use the /mcp auth command to manage OAuth authentication:
# List servers requiring authentication
/mcp auth
# Authenticate with a specific server
/mcp auth serverName
# Re-authenticate if tokens expire
/mcp auth serverName
OAuth 配置属性
¥OAuth Configuration Properties
enabled(布尔值):为此服务器启用 OAuth¥
enabled(boolean): Enable OAuth for this serverclientId(字符串):OAuth 客户端标识符(动态注册时可选)¥
clientId(string): OAuth client identifier (optional with dynamic registration)clientSecret(字符串):OAuth 客户端密钥(对于公共客户端可选)¥
clientSecret(string): OAuth client secret (optional for public clients)authorizationUrl(字符串):OAuth 授权端点(如果省略则自动发现)¥
authorizationUrl(string): OAuth authorization endpoint (auto-discovered if omitted)tokenUrl(字符串):OAuth 令牌端点(如果省略则自动发现)¥
tokenUrl(string): OAuth token endpoint (auto-discovered if omitted)scopes(string[]): 必需的 OAuth 范围¥
scopes(string[]): Required OAuth scopesredirectUri(字符串):自定义重定向 URI(默认为http://localhost:7777/oauth/callback)¥
redirectUri(string): Custom redirect URI (defaults tohttp://localhost:7777/oauth/callback)tokenParamName(字符串):SSE URL 中令牌的查询参数名称¥
tokenParamName(string): Query parameter name for tokens in SSE URLsaudiences(string[]): 令牌有效的受众¥
audiences(string[]): Audiences the token is valid for
代币管理
¥Token Management
OAuth 令牌自动:
¥OAuth tokens are automatically:
安全存储在
~/.gemini/mcp-oauth-tokens.json¥Stored securely in
~/.gemini/mcp-oauth-tokens.json焕然一新过期时(如果刷新令牌可用)
¥Refreshed when expired (if refresh tokens are available)
已验证每次连接尝试之前
¥Validated before each connection attempt
已清理无效或过期时
¥Cleaned up when invalid or expired
身份验证提供程序类型
¥Authentication Provider Type
您可以使用authProviderType财产:
¥You can specify the authentication provider type using the authProviderType property:
authProviderType(string):指定身份验证提供程序。可以是以下之一:¥
authProviderType(string): Specifies the authentication provider. Can be one of the following:dynamic_discovery(默认):CLI 将自动从服务器发现 OAuth 配置。¥
dynamic_discovery(default): The CLI will automatically discover the OAuth configuration from the server.google_credentials:CLI 将使用 Google 应用程序默认凭据 (ADC) 与服务器进行身份验证。使用此提供程序时,必须指定所需的范围。¥
google_credentials: The CLI will use the Google Application Default Credentials (ADC) to authenticate with the server. When using this provider, you must specify the required scopes.
{
"mcpServers": {
"googleCloudServer": {
"httpUrl": "https://my-gcp-service.run.app/mcp",
"authProviderType": "google_credentials",
"oauth": {
"scopes": ["https://www.googleapis.com/auth/userinfo.email"]
}
}
}
}
示例配置
¥Example Configurations
Python MCP 服务器 (Stdio)
¥Python MCP Server (Stdio)
{
"mcpServers": {
"pythonTools": {
"command": "python",
"args": ["-m", "my_mcp_server", "--port", "8080"],
"cwd": "./mcp-servers/python",
"env": {
"DATABASE_URL": "$DB_CONNECTION_STRING",
"API_KEY": "${EXTERNAL_API_KEY}"
},
"timeout": 15000
}
}
}
Node.js MCP 服务器 (Stdio)
¥Node.js MCP Server (Stdio)
{
"mcpServers": {
"nodeServer": {
"command": "node",
"args": ["dist/server.js", "--verbose"],
"cwd": "./mcp-servers/node",
"trust": true
}
}
}
基于 Docker 的 MCP 服务器
¥Docker-based MCP Server
{
"mcpServers": {
"dockerizedServer": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"API_KEY",
"-v",
"${PWD}:/workspace",
"my-mcp-server:latest"
],
"env": {
"API_KEY": "$EXTERNAL_SERVICE_TOKEN"
}
}
}
}
基于HTTP的MCP服务器
¥HTTP-based MCP Server
{
"mcpServers": {
"httpServer": {
"httpUrl": "http://localhost:3000/mcp",
"timeout": 5000
}
}
}
基于 HTTP 的 MCP 服务器,带有自定义标头
¥HTTP-based MCP Server with Custom Headers
{
"mcpServers": {
"httpServerWithAuth": {
"httpUrl": "http://localhost:3000/mcp",
"headers": {
"Authorization": "Bearer your-api-token",
"X-Custom-Header": "custom-value",
"Content-Type": "application/json"
},
"timeout": 5000
}
}
}
具有工具过滤功能的 MCP 服务器
¥MCP Server with Tool Filtering
{
"mcpServers": {
"filteredServer": {
"command": "python",
"args": ["-m", "my_mcp_server"],
"includeTools": ["safe_tool", "file_reader", "data_processor"],
// "excludeTools": ["dangerous_tool", "file_deleter"],
"timeout": 30000
}
}
}
探索过程深度探究
¥Discovery Process Deep Dive
Gemini CLI 启动时,会通过以下详细流程执行 MCP 服务器发现:
¥When the Gemini CLI starts, it performs MCP server discovery through the following detailed process:
1. 服务器迭代与连接
¥1. Server Iteration and Connection
对于每个已配置的服务器mcpServers:
¥For each configured server in mcpServers:
状态跟踪开始:服务器状态设置为
CONNECTING¥Status tracking begins: Server status is set to
CONNECTING运输选择:根据配置属性:
¥Transport selection: Based on configuration properties:
httpUrl→StreamableHTTPClientTransport¥
httpUrl→StreamableHTTPClientTransporturl→SSEClientTransport¥
url→SSEClientTransportcommand→StdioClientTransport¥
command→StdioClientTransport连接建立:MCP 客户端尝试连接并配置超时
¥Connection establishment: The MCP client attempts to connect with the configured timeout
错误处理:连接失败会被记录下来,服务器状态会被设置为
DISCONNECTED¥Error handling: Connection failures are logged and the server status is set to
DISCONNECTED
2. 工具发现
¥2. Tool Discovery
连接成功后:
¥Upon successful connection:
工具清单:客户端调用 MCP 服务器的工具列表端点
¥Tool listing: The client calls the MCP server's tool listing endpoint
架构验证:每个工具的功能声明都经过验证
¥Schema validation: Each tool's function declaration is validated
工具过滤:工具的筛选依据
includeTools和excludeTools配置¥Tool filtering: Tools are filtered based on
includeToolsandexcludeToolsconfiguration名称清理:工具名称经过清理以满足 Gemini API 要求:
¥Name sanitization: Tool names are cleaned to meet Gemini API requirements:
无效字符(非字母数字、下划线、点、连字符)将替换为下划线
¥Invalid characters (non-alphanumeric, underscore, dot, hyphen) are replaced with underscores
长度超过 63 个字符的名称将被截断并进行中间替换 (
___)¥Names longer than 63 characters are truncated with middle replacement (
___)
3. 冲突解决
¥3. Conflict Resolution
当多个服务器公开同名的工具时:
¥When multiple servers expose tools with the same name:
首次注册获胜:第一个注册工具名称的服务器将获得无前缀名称
¥First registration wins: The first server to register a tool name gets the unprefixed name
自动添加前缀:后续服务器获得前缀名称:
serverName__toolName¥Automatic prefixing: Subsequent servers get prefixed names:
serverName__toolName注册表跟踪:工具注册表维护服务器名称与其工具之间的映射
¥Registry tracking: The tool registry maintains mappings between server names and their tools
4. 模式处理
¥4. Schema Processing
工具参数模式经过清理以实现 Gemini API 兼容性:
¥Tool parameter schemas undergo sanitization for Gemini API compatibility:
$schema特性被删除¥
$schemaproperties are removedadditionalProperties被剥夺¥
additionalPropertiesare strippedanyOf和default删除其默认值(Vertex AI 兼容性)¥
anyOfwithdefaulthave their default values removed (Vertex AI compatibility)递归处理适用于嵌套模式
¥Recursive processing applies to nested schemas
5.连接管理
¥5. Connection Management
发现后:
¥After discovery:
持久连接:成功注册工具的服务器维持其连接
¥Persistent connections: Servers that successfully register tools maintain their connections
清理:不提供可用工具的服务器已关闭连接
¥Cleanup: Servers that provide no usable tools have their connections closed
状态更新:最终服务器状态设置为
CONNECTED或者DISCONNECTED¥Status updates: Final server statuses are set to
CONNECTEDorDISCONNECTED
工具执行流程
¥Tool Execution Flow
当 Gemini 模型决定使用 MCP 工具时,会发生以下执行流程:
¥When the Gemini model decides to use an MCP tool, the following execution flow occurs:
1. 工具调用
¥1. Tool Invocation
该模型生成FunctionCall和:
¥The model generates a FunctionCall with:
工具名称:注册名称(可能带有前缀)
¥Tool name: The registered name (potentially prefixed)
参数:与工具参数架构匹配的 JSON 对象
¥Arguments: JSON object matching the tool's parameter schema
2. 确认流程
¥2. Confirmation Process
每个DiscoveredMCPTool实现复杂的确认逻辑:
¥Each DiscoveredMCPTool implements sophisticated confirmation logic:
基于信任的绕过
¥Trust-based Bypass
if (this.trust) {
return false; // No confirmation needed
}
动态允许列表
¥Dynamic Allow-listing
系统维护以下内部允许列表:
¥The system maintains internal allow-lists for:
服务器级别:
serverName→ 此服务器的所有工具均受信任¥Server-level:
serverName→ All tools from this server are trusted工具级别:
serverName.toolName→ 此特定工具值得信赖¥Tool-level:
serverName.toolName→ This specific tool is trusted
用户选择处理
¥User Choice Handling
当需要确认时,用户可以选择:
¥When confirmation is required, users can choose:
继续一次:仅执行本次
¥Proceed once: Execute this time only
始终允许此工具:添加到工具级允许列表
¥Always allow this tool: Add to tool-level allow-list
始终允许此服务器:添加到服务器级允许列表
¥Always allow this server: Add to server-level allow-list
取消:中止执行
¥Cancel: Abort execution
3.执行
¥3. Execution
确认后(或绕过信任):
¥Upon confirmation (or trust bypass):
参数准备:根据工具的架构验证参数
¥Parameter preparation: Arguments are validated against the tool's schema
MCP 调用:底层
CallableTool使用以下命令调用服务器:¥MCP call: The underlying
CallableToolinvokes the server with:
typescript
const functionCalls = [
{
name: this.serverToolName, // Original server tool name
args: params,
},
];
¥typescript
const functionCalls = [
{
name: this.serverToolName, // Original server tool name
args: params,
},
];
响应处理:结果格式化为 LLM 上下文和用户显示
¥Response processing: Results are formatted for both LLM context and user display
4. 响应处理
¥4. Response Handling
执行结果包含:
¥The execution result contains:
llmContent:语言模型上下文的原始响应部分¥
llmContent: Raw response parts for the language model's contextreturnDisplay:格式化输出供用户显示(通常是 markdown 代码块中的 JSON)¥
returnDisplay: Formatted output for user display (often JSON in markdown code blocks)
如何与 MCP 服务器交互
¥How to interact with your MCP server
使用/mcp命令
¥Using the /mcp Command
这/mcp命令提供有关 MCP 服务器设置的全面信息:
¥The /mcp command provides comprehensive information about your MCP server setup:
/mcp
显示如下内容:
¥This displays:
服务器列表:所有已配置的 MCP 服务器
¥Server list: All configured MCP servers
连接状态:
CONNECTED,CONNECTING, 或者DISCONNECTED¥Connection status:
CONNECTED,CONNECTING, orDISCONNECTED服务器详细信息:配置摘要(不包括敏感数据)
¥Server details: Configuration summary (excluding sensitive data)
可用工具:每个服务器的工具列表及其说明
¥Available tools: List of tools from each server with descriptions
发现状态:总体发现过程状态
¥Discovery state: Overall discovery process status
例子/mcp输出
¥Example /mcp Output
MCP Servers Status:
📡 pythonTools (CONNECTED)
Command: python -m my_mcp_server --port 8080
Working Directory: ./mcp-servers/python
Timeout: 15000ms
Tools: calculate_sum, file_analyzer, data_processor
🔌 nodeServer (DISCONNECTED)
Command: node dist/server.js --verbose
Error: Connection refused
🐳 dockerizedServer (CONNECTED)
Command: docker run -i --rm -e API_KEY my-mcp-server:latest
Tools: docker__deploy, docker__status
Discovery State: COMPLETED
工具使用
¥Tool Usage
一旦发现,MCP 工具即可像内置工具一样供 Gemini 模型使用。该模型将自动:
¥Once discovered, MCP tools are available to the Gemini model like built-in tools. The model will automatically:
选择合适的工具根据您的要求
¥Select appropriate tools based on your requests
显示确认对话框(除非服务器值得信赖)
¥Present confirmation dialogs (unless the server is trusted)
执行工具使用适当的参数
¥Execute tools with proper parameters
显示结果采用用户友好的格式
¥Display results in a user-friendly format
状态监控和故障排除
¥Status Monitoring and Troubleshooting
连接状态
¥Connection States
MCP 集成跟踪几个状态:
¥The MCP integration tracks several states:
服务器状态 (MCPServerStatus)
¥Server Status (MCPServerStatus)
DISCONNECTED:服务器未连接或出现错误¥
DISCONNECTED: Server is not connected or has errorsCONNECTING:正在尝试连接¥
CONNECTING: Connection attempt in progressCONNECTED:服务器已连接并准备就绪¥
CONNECTED: Server is connected and ready
发现州(MCPDiscoveryState)
¥Discovery State (MCPDiscoveryState)
NOT_STARTED:探索尚未开始¥
NOT_STARTED: Discovery hasn't begunIN_PROGRESS:目前正在探索服务器¥
IN_PROGRESS: Currently discovering serversCOMPLETED:发现完成(无论有无错误)¥
COMPLETED: Discovery finished (with or without errors)
常见问题和解决方案
¥Common Issues and Solutions
服务器无法连接
¥Server Won't Connect
症状:服务器显示DISCONNECTED地位
¥Symptoms: Server shows DISCONNECTED status
故障排除:
¥Troubleshooting:
检查配置:核实
command,args, 和cwd是正确的¥Check configuration: Verify
command,args, andcwdare correct手动测试:直接运行服务器命令以确保其有效
¥Test manually: Run the server command directly to ensure it works
检查依赖项:确保安装了所有必需的软件包
¥Check dependencies: Ensure all required packages are installed
审查日志:在 CLI 输出中查找错误消息
¥Review logs: Look for error messages in the CLI output
验证权限:确保 CLI 可以执行服务器命令
¥Verify permissions: Ensure the CLI can execute the server command
未发现任何工具
¥No Tools Discovered
症状:服务器已连接,但没有可用的工具
¥Symptoms: Server connects but no tools are available
故障排除:
¥Troubleshooting:
验证工具注册:确保您的服务器确实注册了工具
¥Verify tool registration: Ensure your server actually registers tools
检查 MCP 协议:确认您的服务器正确实现了 MCP 工具列表
¥Check MCP protocol: Confirm your server implements the MCP tool listing correctly
查看服务器日志:检查 stderr 输出是否存在服务器端错误
¥Review server logs: Check stderr output for server-side errors
测试工具清单:手动测试服务器的工具发现端点
¥Test tool listing: Manually test your server's tool discovery endpoint
工具未执行
¥Tools Not Executing
症状:发现了工具但在执行过程中失败
¥Symptoms: Tools are discovered but fail during execution
故障排除:
¥Troubleshooting:
参数验证:确保您的工具接受预期的参数
¥Parameter validation: Ensure your tool accepts the expected parameters
架构兼容性:验证您的输入模式是否为有效的 JSON 模式
¥Schema compatibility: Verify your input schemas are valid JSON Schema
错误处理:检查你的工具是否抛出了未处理的异常
¥Error handling: Check if your tool is throwing unhandled exceptions
超时问题:考虑增加
timeout环境¥Timeout issues: Consider increasing the
timeoutsetting
沙盒兼容性
¥Sandbox Compatibility
症状:启用沙盒时 MCP 服务器失败
¥Symptoms: MCP servers fail when sandboxing is enabled
解决方案:
¥Solutions:
基于 Docker 的服务器:使用包含所有依赖项的 Docker 容器
¥Docker-based servers: Use Docker containers that include all dependencies
路径可达性:确保服务器可执行文件在沙盒中可用
¥Path accessibility: Ensure server executables are available in the sandbox
网络访问:配置沙盒以允许必要的网络连接
¥Network access: Configure sandbox to allow necessary network connections
环境变量:验证所需的环境变量是否已传递
¥Environment variables: Verify required environment variables are passed through
调试技巧
¥Debugging Tips
启用调试模式:使用以下命令运行 CLI
--debug用于详细输出¥Enable debug mode: Run the CLI with
--debugfor verbose output检查标准错误:MCP 服务器 stderr 被捕获并记录(INFO 消息被过滤)
¥Check stderr: MCP server stderr is captured and logged (INFO messages filtered)
测试隔离:在集成之前独立测试您的 MCP 服务器
¥Test isolation: Test your MCP server independently before integrating
增量设置:在添加复杂功能之前,先从简单的工具开始
¥Incremental setup: Start with simple tools before adding complex functionality
使用
/mcp频繁地:在开发过程中监控服务器状态¥Use
/mcpfrequently: Monitor server status during development
重要说明
¥Important Notes
安全注意事项
¥Security Considerations
信任设置:这
trust选项会绕过所有确认对话框。请谨慎使用,并且仅用于您完全控制的服务器¥Trust settings: The
trustoption bypasses all confirmation dialogs. Use cautiously and only for servers you completely control访问令牌:配置包含 API 密钥或令牌的环境变量时要注意安全
¥Access tokens: Be security-aware when configuring environment variables containing API keys or tokens
沙盒兼容性:使用沙盒时,请确保 MCP 服务器在沙盒环境中可用
¥Sandbox compatibility: When using sandboxing, ensure MCP servers are available within the sandbox environment
私人数据:使用范围广泛的个人访问令牌可能会导致存储库之间的信息泄露
¥Private data: Using broadly scoped personal access tokens can lead to information leakage between repositories
绩效和资源管理
¥Performance and Resource Management
连接持久性:CLI 与成功注册工具的服务器保持持久连接
¥Connection persistence: The CLI maintains persistent connections to servers that successfully register tools
自动清理:与不提供工具的服务器的连接将自动关闭
¥Automatic cleanup: Connections to servers providing no tools are automatically closed
超时管理:根据服务器的响应特性配置适当的超时
¥Timeout management: Configure appropriate timeouts based on your server's response characteristics
资源监控:MCP 服务器作为独立进程运行并消耗系统资源
¥Resource monitoring: MCP servers run as separate processes and consume system resources
架构兼容性
¥Schema Compatibility
财产剥夺:系统会自动删除某些架构属性(
$schema,additionalProperties) 以实现 Gemini API 兼容性¥Property stripping: The system automatically removes certain schema properties (
$schema,additionalProperties) for Gemini API compatibility名称清理:工具名称会自动清理以满足 API 要求
¥Name sanitization: Tool names are automatically sanitized to meet API requirements
冲突解决:通过自动添加前缀解决服务器之间的工具名称冲突
¥Conflict resolution: Tool name conflicts between servers are resolved through automatic prefixing
这种全面的集成使 MCP 服务器成为扩展 Gemini CLI 功能的强大方式,同时保持安全性、可靠性和易用性。
¥This comprehensive integration makes MCP servers a powerful way to extend the Gemini CLI's capabilities while maintaining security, reliability, and ease of use.
从工具返回丰富的内容
¥Returning Rich Content from Tools
MCP 工具并不局限于返回简单的文本。您可以在单个工具响应中返回丰富的多部分内容,包括文本、图像、音频和其他二进制数据。这让您能够构建强大的工具,一次性向模型提供多样化的信息。
¥MCP tools are not limited to returning simple text. You can return rich, multi-part content, including text, images, audio, and other binary data in a single tool response. This allows you to build powerful tools that can provide diverse information to the model in a single turn.
该工具返回的所有数据都经过处理并发送到模型作为其下一代内容,使其能够推理或总结所提供的信息。
¥All data returned from the tool is processed and sent to the model as context for its next generation, enabling it to reason about or summarize the provided information.
工作原理
¥How It Works
要返回丰富的内容,您的工具的响应必须遵守 MCP 规范CallToolResult。 这content结果字段应该是一个数组ContentBlock对象。Gemini CLI 将正确处理此数组,将文本与二进制数据分离并将其打包以供模型使用。
¥To return rich content, your tool's response must adhere to the MCP specification for a CallToolResult. The content field of the result should be an array of ContentBlock objects. The Gemini CLI will correctly process this array, separating text from binary data and packaging it for the model.
您可以在content数组。支持的块类型包括:
¥You can mix and match different content block types in the content array. The supported block types include:
text¥
textimage¥
imageaudio¥
audioresource(嵌入内容)¥
resource(embedded content)resource_link¥
resource_link
示例:返回文本和图像
¥Example: Returning Text and an Image
以下是来自 MCP 工具的有效 JSON 响应的示例,该响应返回文本描述和图像:
¥Here is an example of a valid JSON response from an MCP tool that returns both a text description and an image:
{
"content": [
{
"type": "text",
"text": "Here is the logo you requested."
},
{
"type": "image",
"data": "BASE64_ENCODED_IMAGE_DATA_HERE",
"mimeType": "image/png"
},
{
"type": "text",
"text": "The logo was created in 2025."
}
]
}
当 Gemini CLI 收到此响应时,它将:
¥When the Gemini CLI receives this response, it will:
提取所有文本并将其合并为一个
functionResponse模型的一部分。¥Extract all the text and combine it into a single
functionResponsepart for the model.将图像数据作为单独的
inlineData部分。¥Present the image data as a separate
inlineDatapart.在 CLI 中提供清晰、用户友好的摘要,表明已收到文本和图像。
¥Provide a clean, user-friendly summary in the CLI, indicating that both text and an image were received.
这使您能够构建复杂的工具,为 Gemini 模型提供丰富的多模式上下文。
¥This enables you to build sophisticated tools that can provide rich, multi-modal context to the Gemini model.
MCP 提示符作为斜线命令
¥MCP Prompts as Slash Commands
除了工具之外,MCP 服务器还可以公开预定义的提示符,这些提示符可以在 Gemini CLI 中以斜杠命令的形式执行。这允许您为常见或复杂的查询创建快捷方式,并可通过名称轻松调用。
¥In addition to tools, MCP servers can expose predefined prompts that can be executed as slash commands within the Gemini CLI. This allows you to create shortcuts for common or complex queries that can be easily invoked by name.
在服务器上定义提示
¥Defining Prompts on the Server
下面是定义提示的 stdio MCP 服务器的一个小例子:
¥Here's a small example of a stdio MCP server that defines prompts:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
const server = new McpServer({
name: 'prompt-server',
version: '1.0.0',
});
server.registerPrompt(
'poem-writer',
{
title: 'Poem Writer',
description: 'Write a nice haiku',
argsSchema: { title: z.string(), mood: z.string().optional() },
},
({ title, mood }) => ({
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Write a haiku${mood ? ` with the mood ${mood}` : ''} called ${title}. Note that a haiku is 5 syllables followed by 7 syllables followed by 5 syllables `,
},
},
],
}),
);
const transport = new StdioServerTransport();
await server.connect(transport);
这可以包含在settings.json在下面mcpServers和:
¥This can be included in settings.json under mcpServers with:
"nodeServer": {
"command": "node",
"args": ["filename.ts"],
}
调用提示
¥Invoking Prompts
一旦发现提示符,您就可以使用其名称作为斜杠命令来调用它。CLI 将自动处理解析参数。
¥Once a prompt is discovered, you can invoke it using its name as a slash command. The CLI will automatically handle parsing arguments.
/poem-writer --title="Gemini CLI" --mood="reverent"
或者,使用位置参数:
¥or, using positional arguments:
/poem-writer "Gemini CLI" reverent
运行此命令时,Gemini CLI 会执行prompts/get使用提供的参数在 MCP 服务器上调用方法。服务器负责将参数替换到提示模板中并返回最终的提示文本。然后,CLI 将此提示发送给模型执行。这提供了一种自动化和共享常见工作流程的便捷方法。
¥When you run this command, the Gemini CLI executes the prompts/get method on the MCP server with the provided arguments. The server is responsible for substituting the arguments into the prompt template and returning the final prompt text. The CLI then sends this prompt to the model for execution. This provides a convenient way to automate and share common workflows.
使用以下方式管理 MCP 服务器gemini mcp
¥Managing MCP Servers with gemini mcp
虽然您可以随时通过手动编辑您的settings.json文件中,Gemini CLI 提供了一组便捷的命令,可让您以编程方式管理服务器配置。这些命令简化了添加、列出和删除 MCP 服务器的过程,无需直接编辑 JSON 文件。
¥While you can always configure MCP servers by manually editing your settings.json file, the Gemini CLI provides a convenient set of commands to manage your server configurations programmatically. These commands streamline the process of adding, listing, and removing MCP servers without needing to directly edit JSON files.
添加服务器 (gemini mcp add)
¥Adding a Server (gemini mcp add)
这add命令在你的settings.json. 根据范围(-s, --scope),它将被添加到用户配置中~/.gemini/settings.json或项目配置.gemini/settings.json文件。
¥The add command configures a new MCP server in your settings.json. Based on the scope (-s, --scope), it will be added to either the user config ~/.gemini/settings.json or the project config .gemini/settings.json file.
命令:
¥Command:
gemini mcp add [options] <name> <commandOrUrl> [args...]
<name>:服务器的唯一名称。¥
<name>: A unique name for the server.<commandOrUrl>:要执行的命令(例如stdio)或 URL(用于http/sse)。¥
<commandOrUrl>: The command to execute (forstdio) or the URL (forhttp/sse).[args...]:可选参数stdio命令。¥
[args...]: Optional arguments for astdiocommand.
选项(标志):
¥Options (Flags):
-s, --scope:配置范围(用户或项目)。[默认值:“项目”]¥
-s, --scope: Configuration scope (user or project). [default: "project"]-t, --transport:传输类型(stdio、sse、http)。[默认值:“stdio”]¥
-t, --transport: Transport type (stdio, sse, http). [default: "stdio"]-e, --env:设置环境变量(例如-e KEY=value)。¥
-e, --env: Set environment variables (e.g. -e KEY=value).-H, --header:为 SSE 和 HTTP 传输设置 HTTP 标头(例如 -H“X-Api-Key:abc123”-H“Authorization:Bearer abc123”)。¥
-H, --header: Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123").--timeout:设置连接超时时间(以毫秒为单位)。¥
--timeout: Set connection timeout in milliseconds.--trust:信任服务器(绕过所有工具调用确认提示)。¥
--trust: Trust the server (bypass all tool call confirmation prompts).--description:设置服务器的描述。¥
--description: Set the description for the server.--include-tools:要包含的工具的逗号分隔列表。¥
--include-tools: A comma-separated list of tools to include.--exclude-tools:要排除的工具的逗号分隔列表。¥
--exclude-tools: A comma-separated list of tools to exclude.
添加 stdio 服务器
¥Adding an stdio server
这是运行本地服务器的默认传输。
¥This is the default transport for running local servers.
# Basic syntax
gemini mcp add <name> <command> [args...]
# Example: Adding a local server
gemini mcp add my-stdio-server -e API_KEY=123 /path/to/server arg1 arg2 arg3
# Example: Adding a local python server
gemini mcp add python-server python server.py --port 8080
添加 HTTP 服务器
¥Adding an HTTP server
此传输适用于使用可流式 HTTP 传输的服务器。
¥This transport is for servers that use the streamable HTTP transport.
# Basic syntax
gemini mcp add --transport http <name> <url>
# Example: Adding an HTTP server
gemini mcp add --transport http http-server https://api.example.com/mcp/
# Example: Adding an HTTP server with an authentication header
gemini mcp add --transport http secure-http https://api.example.com/mcp/ --header "Authorization: Bearer abc123"
添加 SSE 服务器
¥Adding an SSE server
此传输适用于使用服务器发送事件 (SSE) 的服务器。
¥This transport is for servers that use Server-Sent Events (SSE).
# Basic syntax
gemini mcp add --transport sse <name> <url>
# Example: Adding an SSE server
gemini mcp add --transport sse sse-server https://api.example.com/sse/
# Example: Adding an SSE server with an authentication header
gemini mcp add --transport sse secure-sse https://api.example.com/sse/ --header "Authorization: Bearer abc123"
列出服务器(gemini mcp list)
¥Listing Servers (gemini mcp list)
要查看当前配置的所有 MCP 服务器,请使用list命令。它显示每个服务器的名称、配置详细信息和连接状态。
¥To view all MCP servers currently configured, use the list command. It displays each server's name, configuration details, and connection status.
命令:
¥Command:
gemini mcp list
示例输出:
¥Example Output:
✓ stdio-server: command: python3 server.py (stdio) - Connected
✓ http-server: https://api.example.com/mcp (http) - Connected
✗ sse-server: https://api.example.com/sse (sse) - Disconnected
删除服务器 (gemini mcp remove)
¥Removing a Server (gemini mcp remove)
要从配置中删除服务器,请使用remove带有服务器名称的命令。
¥To delete a server from your configuration, use the remove command with the server's name.
命令:
¥Command:
gemini mcp remove <name>
例子:
¥Example:
gemini mcp remove my-server
这将从中找到并删除“my-server”条目mcpServers适当的对象settings.json根据范围提交文件(-s, --scope)。
¥This will find and delete the "my-server" entry from the mcpServers object in the appropriate settings.json file based on the scope (-s, --scope).