0
# Tools and Extensions
1
2
Extensible tool system for file operations, shell commands, web operations, and custom tool development. The tool system provides a declarative framework for building AI agent capabilities.
3
4
## Capabilities
5
6
### DeclarativeTool Base Class
7
8
Base class for creating custom tools with validation, parameter handling, and execution framework.
9
10
```typescript { .api }
11
/**
12
* Base declarative tool class for creating custom AI agent tools
13
*/
14
abstract class DeclarativeTool<TParams = any, TResult = any> {
15
abstract readonly name: string;
16
abstract readonly description: string;
17
abstract readonly parameters: object; // JSON Schema
18
19
abstract invoke(params: TParams): Promise<ToolResult<TResult>>;
20
21
// Optional overrides
22
validate?(params: TParams): void;
23
getConfirmationDetails?(params: TParams): ToolCallConfirmationDetails;
24
}
25
26
/**
27
* Enhanced base class with built-in validation and error handling
28
*/
29
abstract class BaseDeclarativeTool<TParams = any, TResult = any> extends DeclarativeTool<TParams, TResult> {
30
constructor();
31
32
// Built-in parameter validation using JSON schema
33
protected validateParams(params: TParams): void;
34
35
// Helper methods for tool development
36
protected createResult(result: TResult, displayResult?: ToolResultDisplay): ToolResult<TResult>;
37
protected createError(message: string, details?: any): ToolResult<TResult>;
38
}
39
```
40
41
### Tool Invocation and Results
42
43
Interfaces and classes for tool execution, parameter handling, and result processing.
44
45
```typescript { .api }
46
/**
47
* Tool invocation interface
48
*/
49
interface ToolInvocation {
50
tool: AnyDeclarativeTool;
51
params: any;
52
invocationId: string;
53
}
54
55
/**
56
* Base tool invocation class
57
*/
58
abstract class BaseToolInvocation implements ToolInvocation {
59
constructor(tool: AnyDeclarativeTool, params: any, invocationId: string);
60
61
readonly tool: AnyDeclarativeTool;
62
readonly params: any;
63
readonly invocationId: string;
64
65
abstract execute(): Promise<ToolResult>;
66
}
67
68
/**
69
* Tool execution result
70
*/
71
interface ToolResult<T = any> {
72
result: T;
73
confirmationState?: ToolConfirmationOutcome;
74
displayResult?: ToolResultDisplay;
75
error?: ToolError;
76
}
77
78
/**
79
* Tool result display options
80
*/
81
type ToolResultDisplay =
82
| string
83
| { type: 'text'; content: string }
84
| { type: 'json'; content: any }
85
| { type: 'diff'; before: string; after: string }
86
| { type: 'file'; path: string; content: string };
87
```
88
89
### Tool Confirmation System
90
91
Confirmation workflow for tool execution with different approval modes.
92
93
```typescript { .api }
94
/**
95
* Tool confirmation outcomes
96
*/
97
enum ToolConfirmationOutcome {
98
ProceedOnce = 'ProceedOnce',
99
ProceedAlways = 'ProceedAlways',
100
ProceedAlwaysServer = 'ProceedAlwaysServer',
101
ProceedAlwaysTool = 'ProceedAlwaysTool',
102
ModifyWithEditor = 'ModifyWithEditor',
103
Cancel = 'Cancel'
104
}
105
106
/**
107
* Tool confirmation details for different operation types
108
*/
109
type ToolCallConfirmationDetails =
110
| ToolEditConfirmationDetails
111
| ToolExecuteConfirmationDetails
112
| ToolMcpConfirmationDetails
113
| ToolInfoConfirmationDetails;
114
115
/**
116
* Edit operation confirmation details
117
*/
118
interface ToolEditConfirmationDetails {
119
type: 'edit';
120
filePath: string;
121
originalContent: string;
122
newContent: string;
123
diff: FileDiff;
124
}
125
126
/**
127
* Execute operation confirmation details
128
*/
129
interface ToolExecuteConfirmationDetails {
130
type: 'execute';
131
command: string;
132
args: string[];
133
cwd?: string;
134
env?: Record<string, string>;
135
}
136
137
/**
138
* MCP operation confirmation details
139
*/
140
interface ToolMcpConfirmationDetails {
141
type: 'mcp';
142
serverName: string;
143
toolName: string;
144
params: any;
145
}
146
147
/**
148
* Info operation confirmation details
149
*/
150
interface ToolInfoConfirmationDetails {
151
type: 'info';
152
message: string;
153
details?: any;
154
}
155
156
/**
157
* Tool confirmation payload
158
*/
159
interface ToolConfirmationPayload {
160
invocationId: string;
161
toolName: string;
162
details: ToolCallConfirmationDetails;
163
location?: ToolLocation;
164
}
165
```
166
167
### Tool Operation Kinds
168
169
Classification system for different types of tool operations.
170
171
```typescript { .api }
172
/**
173
* Tool operation kinds for classification and approval workflows
174
*/
175
enum Kind {
176
Read = 'Read',
177
Edit = 'Edit',
178
Delete = 'Delete',
179
Move = 'Move',
180
Search = 'Search',
181
Execute = 'Execute',
182
Think = 'Think',
183
Fetch = 'Fetch',
184
Other = 'Other'
185
}
186
187
/**
188
* Tool location information
189
*/
190
interface ToolLocation {
191
filePath?: string;
192
lineNumber?: number;
193
columnNumber?: number;
194
workspaceRoot?: string;
195
}
196
```
197
198
### File Operations Tools
199
200
Built-in tools for file system operations, reading, writing, and editing files.
201
202
```typescript { .api }
203
/**
204
* Read file tool for accessing file contents
205
*/
206
class ReadFileTool extends DeclarativeTool<{path: string}, string> {
207
readonly name = 'read_file';
208
readonly description = 'Read contents of a file';
209
210
invoke(params: {path: string}): Promise<ToolResult<string>>;
211
}
212
213
/**
214
* Write file tool for creating or overwriting files
215
*/
216
class WriteFileTool extends DeclarativeTool<{path: string, content: string}, void> {
217
readonly name = 'write_file';
218
readonly description = 'Write content to a file';
219
220
invoke(params: {path: string, content: string}): Promise<ToolResult<void>>;
221
}
222
223
/**
224
* Edit file tool for making targeted changes to files
225
*/
226
class EditTool extends DeclarativeTool {
227
readonly name = 'edit';
228
readonly description = 'Edit a file with find and replace operations';
229
230
invoke(params: {
231
path: string;
232
edits: Array<{
233
oldText: string;
234
newText: string;
235
replaceAll?: boolean;
236
}>;
237
}): Promise<ToolResult>;
238
}
239
240
/**
241
* Directory listing tool
242
*/
243
class LsTool extends DeclarativeTool {
244
readonly name = 'ls';
245
readonly description = 'List directory contents';
246
247
invoke(params: {
248
path?: string;
249
all?: boolean;
250
long?: boolean;
251
}): Promise<ToolResult<string[]>>;
252
}
253
254
/**
255
* Read multiple files tool for batch file operations
256
*/
257
class ReadManyFilesTool extends DeclarativeTool {
258
readonly name = 'read_many_files';
259
readonly description = 'Read contents of multiple files';
260
261
invoke(params: {
262
paths: string[];
263
maxFiles?: number;
264
}): Promise<ToolResult<{[path: string]: string}>>;
265
}
266
```
267
268
### Search and Pattern Matching Tools
269
270
Tools for searching content within files and matching file patterns.
271
272
```typescript { .api }
273
/**
274
* Grep tool for text search within files
275
*/
276
class GrepTool extends DeclarativeTool {
277
readonly name = 'grep';
278
readonly description = 'Search for text patterns in files';
279
280
invoke(params: {
281
pattern: string;
282
paths?: string[];
283
recursive?: boolean;
284
ignoreCase?: boolean;
285
lineNumbers?: boolean;
286
}): Promise<ToolResult<string>>;
287
}
288
289
/**
290
* Ripgrep tool for fast text search
291
*/
292
class RipGrepTool extends DeclarativeTool {
293
readonly name = 'rg';
294
readonly description = 'Fast text search using ripgrep';
295
296
invoke(params: {
297
pattern: string;
298
paths?: string[];
299
type?: string;
300
ignoreCase?: boolean;
301
contextLines?: number;
302
}): Promise<ToolResult<string>>;
303
}
304
305
/**
306
* Glob tool for file pattern matching
307
*/
308
class GlobTool extends DeclarativeTool {
309
readonly name = 'glob';
310
readonly description = 'Find files matching glob patterns';
311
312
invoke(params: {
313
pattern: string;
314
cwd?: string;
315
ignore?: string[];
316
}): Promise<ToolResult<string[]>>;
317
}
318
```
319
320
### Shell and Command Execution Tools
321
322
Tools for executing shell commands and system operations.
323
324
```typescript { .api }
325
/**
326
* Shell command execution tool
327
*/
328
class ShellTool extends DeclarativeTool {
329
readonly name = 'shell';
330
readonly description = 'Execute shell commands';
331
332
invoke(params: {
333
command: string;
334
args?: string[];
335
cwd?: string;
336
env?: Record<string, string>;
337
timeout?: number;
338
}): Promise<ToolResult<{stdout: string, stderr: string, exitCode: number}>>;
339
}
340
```
341
342
### Web Operations Tools
343
344
Tools for web content fetching and web search operations.
345
346
```typescript { .api }
347
/**
348
* Web fetch tool for downloading web content
349
*/
350
class WebFetchTool extends DeclarativeTool {
351
readonly name = 'web_fetch';
352
readonly description = 'Fetch content from web URLs';
353
354
invoke(params: {
355
url: string;
356
headers?: Record<string, string>;
357
timeout?: number;
358
}): Promise<ToolResult<{content: string, contentType: string, status: number}>>;
359
}
360
361
/**
362
* Web search tool for search engine queries
363
*/
364
class WebSearchTool extends DeclarativeTool {
365
readonly name = 'web_search';
366
readonly description = 'Search the web for information';
367
368
invoke(params: {
369
query: string;
370
maxResults?: number;
371
site?: string;
372
}): Promise<ToolResult<Array<{title: string, url: string, snippet: string}>>>;
373
}
374
```
375
376
### MCP Integration Tools
377
378
Tools for Model Context Protocol server integration and communication.
379
380
```typescript { .api }
381
/**
382
* MCP client tool for server communication
383
*/
384
class McpClientTool extends DeclarativeTool {
385
readonly name = 'mcp_client';
386
readonly description = 'Communicate with MCP servers';
387
388
invoke(params: {
389
serverName: string;
390
method: string;
391
params?: any;
392
}): Promise<ToolResult<any>>;
393
}
394
395
/**
396
* MCP tool wrapper for external MCP tools
397
*/
398
class McpTool extends DeclarativeTool {
399
constructor(
400
private serverName: string,
401
private toolDefinition: any
402
);
403
404
invoke(params: any): Promise<ToolResult<any>>;
405
}
406
```
407
408
### Memory and Context Tools
409
410
Tools for managing AI memory and context information.
411
412
```typescript { .api }
413
/**
414
* Memory management tool for AI context
415
*/
416
class MemoryTool extends DeclarativeTool {
417
readonly name = 'memory';
418
readonly description = 'Manage AI memory and context';
419
420
invoke(params: {
421
action: 'read' | 'write' | 'append' | 'clear';
422
key?: string;
423
value?: any;
424
scope?: 'session' | 'global' | 'project';
425
}): Promise<ToolResult<any>>;
426
}
427
```
428
429
### Tool Utilities and Helpers
430
431
Utility functions and helpers for tool development and management.
432
433
```typescript { .api }
434
/**
435
* Type definitions
436
*/
437
type AnyToolInvocation = ToolInvocation;
438
type AnyDeclarativeTool = DeclarativeTool<any, any>;
439
440
/**
441
* File diff information
442
*/
443
interface FileDiff {
444
added: number;
445
removed: number;
446
modified: number;
447
hunks: DiffHunk[];
448
}
449
450
interface DiffHunk {
451
oldStart: number;
452
oldLines: number;
453
newStart: number;
454
newLines: number;
455
lines: string[];
456
}
457
458
/**
459
* Diff statistics
460
*/
461
interface DiffStat {
462
files: number;
463
insertions: number;
464
deletions: number;
465
}
466
467
/**
468
* Tool type guard
469
* @param obj - Object to check
470
* @returns True if object is a tool
471
*/
472
function isTool(obj: unknown): obj is AnyDeclarativeTool;
473
474
/**
475
* Detect cycles in JSON schema
476
* @param schema - Schema object to check
477
* @returns True if schema has cycles
478
*/
479
function hasCycleInSchema(schema: object): boolean;
480
```
481
482
**Usage Examples:**
483
484
```typescript
485
import {
486
DeclarativeTool,
487
BaseDeclarativeTool,
488
ToolResult,
489
Kind,
490
ReadFileTool,
491
ShellTool
492
} from '@google/gemini-cli-core';
493
494
// Custom tool development
495
class CustomAnalysisTool extends BaseDeclarativeTool<{path: string}, {summary: string}> {
496
readonly name = 'analyze_code';
497
readonly description = 'Analyze code file for complexity and patterns';
498
readonly parameters = {
499
type: 'object',
500
properties: {
501
path: { type: 'string', description: 'File path to analyze' }
502
},
503
required: ['path']
504
};
505
506
async invoke(params: {path: string}): Promise<ToolResult<{summary: string}>> {
507
try {
508
// Validate parameters automatically
509
this.validateParams(params);
510
511
// Perform analysis
512
const analysis = await this.analyzeFile(params.path);
513
514
return this.createResult({summary: analysis});
515
} catch (error) {
516
return this.createError(`Analysis failed: ${error.message}`);
517
}
518
}
519
520
private async analyzeFile(path: string): Promise<string> {
521
// Implementation details
522
return 'Analysis complete';
523
}
524
}
525
526
// Using built-in tools
527
const readTool = new ReadFileTool();
528
const result = await readTool.invoke({path: '/path/to/file.txt'});
529
530
if (result.error) {
531
console.error('Read failed:', result.error.message);
532
} else {
533
console.log('File contents:', result.result);
534
}
535
536
// Shell command execution
537
const shellTool = new ShellTool();
538
const cmdResult = await shellTool.invoke({
539
command: 'git',
540
args: ['status', '--porcelain'],
541
cwd: '/path/to/repo'
542
});
543
544
console.log('Git status:', cmdResult.result.stdout);
545
```