0
# MCP Integration
1
2
The Gemini CLI integrates with the Model Context Protocol (MCP) to connect external tools and services, providing support for multiple transport types and comprehensive server management capabilities.
3
4
## Capabilities
5
6
### MCP Server Configuration
7
8
MCP servers can be configured with different transport mechanisms and connection options.
9
10
```typescript { .api }
11
interface MCPServerConfig {
12
// Stdio transport configuration
13
command?: string;
14
args?: string[];
15
env?: Record<string, string>;
16
17
// Server-Sent Events transport
18
url?: string;
19
20
// HTTP transport
21
httpUrl?: string;
22
23
// Common HTTP configuration (for SSE and HTTP)
24
headers?: Record<string, string>;
25
26
// Connection and behavior settings
27
timeout?: number;
28
trust?: boolean;
29
description?: string;
30
includeTools?: string[];
31
excludeTools?: string[];
32
33
// Extension association
34
extensionName?: string;
35
}
36
```
37
38
### Transport Types
39
40
MCP supports multiple transport mechanisms for server communication.
41
42
#### Stdio Transport
43
44
Standard input/output communication for local processes.
45
46
```typescript { .api }
47
interface StdioTransport {
48
/** Command to execute */
49
command: string;
50
51
/** Command arguments */
52
args?: string[];
53
54
/** Environment variables */
55
env?: Record<string, string>;
56
}
57
```
58
59
**Usage Examples:**
60
61
```json
62
{
63
"calculator": {
64
"command": "python",
65
"args": ["/path/to/calculator-server.py"],
66
"env": {
67
"CALC_PRECISION": "10"
68
},
69
"description": "Mathematical calculation server"
70
}
71
}
72
```
73
74
#### Server-Sent Events (SSE) Transport
75
76
HTTP-based streaming communication using Server-Sent Events.
77
78
```typescript { .api }
79
interface SSETransport {
80
/** SSE endpoint URL */
81
url: string;
82
83
/** HTTP headers */
84
headers?: Record<string, string>;
85
86
/** Connection timeout in milliseconds */
87
timeout?: number;
88
}
89
```
90
91
**Usage Examples:**
92
93
```json
94
{
95
"weather-service": {
96
"url": "http://localhost:3000/mcp/sse",
97
"headers": {
98
"Authorization": "Bearer your-api-token",
99
"Content-Type": "application/json"
100
},
101
"timeout": 10000
102
}
103
}
104
```
105
106
#### HTTP Transport
107
108
Direct HTTP request/response communication.
109
110
```typescript { .api }
111
interface HTTPTransport {
112
/** HTTP endpoint URL */
113
httpUrl: string;
114
115
/** HTTP headers */
116
headers?: Record<string, string>;
117
118
/** Request timeout in milliseconds */
119
timeout?: number;
120
}
121
```
122
123
**Usage Examples:**
124
125
```json
126
{
127
"api-gateway": {
128
"httpUrl": "https://api.example.com/mcp",
129
"headers": {
130
"Authorization": "Bearer api-key-123",
131
"X-API-Version": "1.0"
132
},
133
"timeout": 5000
134
}
135
}
136
```
137
138
## MCP Management API
139
140
### Server Configuration Loading
141
142
```typescript { .api }
143
/**
144
* Load MCP server configurations from settings and extensions
145
* @param settings - Current application settings
146
* @param extensions - Active extensions
147
* @returns Merged MCP server configurations
148
*/
149
function loadMcpServerConfigs(
150
settings: Settings,
151
extensions: Extension[]
152
): Record<string, MCPServerConfig>;
153
154
/**
155
* Validate MCP server configuration
156
* @param config - Server configuration to validate
157
* @returns Validation result
158
*/
159
function validateMcpServerConfig(
160
config: MCPServerConfig
161
): {
162
valid: boolean;
163
errors: string[];
164
warnings: string[];
165
};
166
```
167
168
### Server Lifecycle Management
169
170
```typescript { .api }
171
interface MCPServer {
172
/** Server name */
173
name: string;
174
175
/** Server configuration */
176
config: MCPServerConfig;
177
178
/** Connection status */
179
status: 'disconnected' | 'connecting' | 'connected' | 'error';
180
181
/** Available tools */
182
tools: MCPTool[];
183
184
/** Connection error if any */
185
error?: string;
186
}
187
188
/**
189
* Start MCP server connection
190
* @param name - Server name
191
* @param config - Server configuration
192
* @returns Promise resolving to server instance
193
*/
194
function startMcpServer(
195
name: string,
196
config: MCPServerConfig
197
): Promise<MCPServer>;
198
199
/**
200
* Stop MCP server connection
201
* @param name - Server name
202
*/
203
function stopMcpServer(name: string): Promise<void>;
204
205
/**
206
* Get status of all MCP servers
207
* @returns Current server status information
208
*/
209
function getMcpServerStatus(): Record<string, MCPServer>;
210
```
211
212
### Tool Discovery and Filtering
213
214
```typescript { .api }
215
interface MCPTool {
216
/** Tool name */
217
name: string;
218
219
/** Tool description */
220
description?: string;
221
222
/** Tool parameters schema */
223
inputSchema: any;
224
225
/** Server providing this tool */
226
serverName: string;
227
}
228
229
/**
230
* Discover available tools from all connected MCP servers
231
* @returns Array of available tools
232
*/
233
function discoverMcpTools(): Promise<MCPTool[]>;
234
235
/**
236
* Filter tools based on server configuration
237
* @param tools - Available tools
238
* @param config - Server configuration with include/exclude lists
239
* @returns Filtered tools array
240
*/
241
function filterMcpTools(
242
tools: MCPTool[],
243
config: MCPServerConfig
244
): MCPTool[];
245
```
246
247
## CLI Commands
248
249
### Adding MCP Servers
250
251
```bash { .api }
252
gemini mcp add <name> <commandOrUrl> [args...] [options]
253
```
254
255
#### Add Command Options
256
257
```bash { .api }
258
--scope, -s <scope> # Configuration scope: user, project
259
--transport, -t <type> # Transport type: stdio, sse, http
260
--env, -e <KEY=value> # Environment variables (repeatable)
261
--header, -H <header> # HTTP headers for SSE/HTTP (repeatable)
262
--timeout <ms> # Connection timeout in milliseconds
263
--trust # Trust server (bypass confirmations)
264
--description <desc> # Server description
265
--include-tools <tools> # Include specific tools (comma-separated)
266
--exclude-tools <tools> # Exclude specific tools (comma-separated)
267
```
268
269
**Usage Examples:**
270
271
```bash
272
# Add stdio server
273
gemini mcp add calculator python /path/to/calc-server.py
274
275
# Add HTTP server with authentication
276
gemini mcp add weather-api http://api.weather.com/mcp \
277
--transport http \
278
--header "Authorization: Bearer token123" \
279
--timeout 10000 \
280
--trust
281
282
# Add server with environment variables
283
gemini mcp add database-tool python db-server.py \
284
--env "DB_HOST=localhost" \
285
--env "DB_PORT=5432" \
286
--scope user
287
288
# Add server with tool filtering
289
gemini mcp add file-processor ./processor-server \
290
--include-tools "process_file,validate_file" \
291
--exclude-tools "delete_file"
292
```
293
294
### Managing MCP Servers
295
296
```bash { .api }
297
gemini mcp list # List configured MCP servers
298
gemini mcp remove <name> # Remove MCP server by name
299
```
300
301
### Server Status and Debugging
302
303
```bash { .api }
304
gemini mcp status # Show server connection status
305
gemini mcp test <name> # Test server connection
306
gemini mcp logs <name> # Show server logs (if available)
307
```
308
309
## Configuration Integration
310
311
### Settings Configuration
312
313
MCP servers can be configured in the settings system:
314
315
```typescript { .api }
316
interface MCPSettings {
317
/** Default server command template */
318
serverCommand?: string;
319
320
/** Globally allowed server names */
321
allowed?: string[];
322
323
/** Globally excluded server names */
324
excluded?: string[];
325
}
326
```
327
328
**Usage Examples:**
329
330
```json
331
{
332
"mcp": {
333
"allowed": ["calculator", "weather-api"],
334
"excluded": ["untrusted-server"]
335
},
336
"mcpServers": {
337
"calculator": {
338
"command": "python",
339
"args": ["~/tools/calculator-server.py"],
340
"trust": true,
341
"description": "Mathematical calculations"
342
},
343
"weather-api": {
344
"url": "http://localhost:3000/weather-mcp",
345
"timeout": 5000,
346
"headers": {
347
"API-Key": "your-key-here"
348
}
349
}
350
}
351
}
352
```
353
354
### Extension Integration
355
356
Extensions can provide MCP servers automatically:
357
358
```typescript { .api }
359
// In gemini-extension.json
360
{
361
"name": "my-extension",
362
"version": "1.0.0",
363
"mcpServers": {
364
"extension-tool": {
365
"command": "node",
366
"args": ["{{extensionPath}}/server.js"],
367
"description": "Extension-provided tools"
368
}
369
}
370
}
371
```
372
373
## Security and Trust
374
375
### Server Trust Model
376
377
```typescript { .api }
378
interface TrustLevel {
379
/** Allow server without confirmation prompts */
380
trusted: boolean;
381
382
/** Allow tool execution without individual approval */
383
autoApprove: boolean;
384
385
/** Trust level reason/source */
386
reason: 'user' | 'extension' | 'system';
387
}
388
389
/**
390
* Check if server is trusted
391
* @param serverName - Name of server to check
392
* @param config - Server configuration
393
* @returns Trust level information
394
*/
395
function checkServerTrust(
396
serverName: string,
397
config: MCPServerConfig
398
): TrustLevel;
399
```
400
401
### Security Considerations
402
403
```typescript { .api }
404
interface SecurityPolicy {
405
/** Require confirmation for new servers */
406
requireConfirmationForNewServers: boolean;
407
408
/** Maximum allowed timeout */
409
maxTimeout: number;
410
411
/** Allowed transport types */
412
allowedTransports: ('stdio' | 'sse' | 'http')[];
413
414
/** Network access restrictions */
415
networkRestrictions: {
416
allowLocalhost: boolean;
417
allowPrivateNetworks: boolean;
418
blockedDomains: string[];
419
};
420
}
421
```
422
423
## Error Handling
424
425
### Connection Errors
426
427
```typescript { .api }
428
interface MCPConnectionError {
429
/** Server name */
430
server: string;
431
432
/** Error type */
433
type: 'timeout' | 'auth' | 'network' | 'protocol';
434
435
/** Error message */
436
message: string;
437
438
/** Retry suggestions */
439
suggestions: string[];
440
441
/** Whether error is recoverable */
442
recoverable: boolean;
443
}
444
445
/**
446
* Handle MCP server connection errors
447
* @param error - Connection error details
448
* @returns Recovery action or null
449
*/
450
function handleMcpError(
451
error: MCPConnectionError
452
): Promise<'retry' | 'ignore' | 'remove' | null>;
453
```
454
455
### Tool Execution Errors
456
457
```typescript { .api }
458
interface MCPToolError {
459
/** Tool name */
460
tool: string;
461
462
/** Server name */
463
server: string;
464
465
/** Error type */
466
type: 'validation' | 'execution' | 'timeout';
467
468
/** Error details */
469
message: string;
470
471
/** Input that caused error */
472
input?: any;
473
}
474
```
475
476
## Advanced Features
477
478
### Server Health Monitoring
479
480
```typescript { .api }
481
interface ServerHealthCheck {
482
/** Server name */
483
name: string;
484
485
/** Health status */
486
status: 'healthy' | 'degraded' | 'unhealthy';
487
488
/** Response time in milliseconds */
489
responseTime: number;
490
491
/** Last check timestamp */
492
lastCheck: Date;
493
494
/** Health metrics */
495
metrics: {
496
successRate: number;
497
averageResponseTime: number;
498
errorCount: number;
499
};
500
}
501
502
/**
503
* Perform health check on MCP server
504
* @param serverName - Server to check
505
* @returns Health status
506
*/
507
function checkServerHealth(
508
serverName: string
509
): Promise<ServerHealthCheck>;
510
```
511
512
### Dynamic Server Discovery
513
514
```typescript { .api }
515
/**
516
* Discover MCP servers on the network
517
* @param options - Discovery options
518
* @returns Discovered server configurations
519
*/
520
function discoverMcpServers(options: {
521
timeout?: number;
522
protocols?: ('http' | 'sse')[];
523
portRange?: [number, number];
524
}): Promise<MCPServerConfig[]>;
525
```
526
527
### Server Capabilities
528
529
```typescript { .api }
530
interface ServerCapabilities {
531
/** Supported tools */
532
tools: string[];
533
534
/** Supported transport types */
535
transports: string[];
536
537
/** Protocol version */
538
protocolVersion: string;
539
540
/** Server metadata */
541
metadata: {
542
name: string;
543
version: string;
544
description?: string;
545
};
546
}
547
548
/**
549
* Query server capabilities
550
* @param serverName - Server to query
551
* @returns Server capabilities
552
*/
553
function getServerCapabilities(
554
serverName: string
555
): Promise<ServerCapabilities>;
556
```