@iqai/adk 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { Part, Content as Content$1, Blob, SpeechConfig, AudioTranscriptionConfig, RealtimeInputConfig, ProactivityConfig, GenerateContentConfig, LiveConnectConfig, GroundingMetadata, GenerateContentResponseUsageMetadata, GoogleGenAI, FunctionCall } from '@google/genai';
2
- export { Blob, Content } from '@google/genai';
1
+ import { Part, Content, Blob, SpeechConfig, AudioTranscriptionConfig, RealtimeInputConfig, ProactivityConfig, FunctionDeclaration, GroundingMetadata, GenerateContentResponseUsageMetadata, GenerateContentConfig, Schema, LiveConnectConfig, GoogleGenAI, FunctionCall } from '@google/genai';
2
+ export { Blob, Content, FunctionDeclaration, Schema as JSONSchema } from '@google/genai';
3
3
  import { LanguageModel } from 'ai';
4
4
  import * as z from 'zod/v4';
5
5
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
@@ -32,41 +32,6 @@ declare class Logger {
32
32
  debugArray(title: string, items: Array<Record<string, any>>): void;
33
33
  }
34
34
 
35
- /**
36
- * JSON Schema type for function parameters
37
- */
38
- interface JSONSchema {
39
- type: string;
40
- properties?: Record<string, JSONSchema>;
41
- items?: JSONSchema;
42
- required?: string[];
43
- enum?: string[];
44
- description?: string;
45
- format?: string;
46
- pattern?: string;
47
- minimum?: number;
48
- maximum?: number;
49
- default?: any;
50
- [key: string]: any;
51
- }
52
- /**
53
- * Represents a function declaration for the LLM
54
- */
55
- interface FunctionDeclaration {
56
- /**
57
- * Name of the function
58
- */
59
- name: string;
60
- /**
61
- * Description of what the function does
62
- */
63
- description: string;
64
- /**
65
- * Parameters schema in JSON Schema format
66
- */
67
- parameters: JSONSchema;
68
- }
69
-
70
35
  /**
71
36
  * Represents the actions attached to an event.
72
37
  */
@@ -206,7 +171,7 @@ interface MemoryEntry {
206
171
  /**
207
172
  * The main content of the memory
208
173
  */
209
- content: Content$1;
174
+ content: Content;
210
175
  /**
211
176
  * The author of the memory
212
177
  */
@@ -366,7 +331,7 @@ declare class LiveRequest {
366
331
  /**
367
332
  * If set, send the content to the model in turn-by-turn mode.
368
333
  */
369
- content?: Content$1;
334
+ content?: Content;
370
335
  /**
371
336
  * If set, send the blob to the model in realtime mode.
372
337
  */
@@ -376,7 +341,7 @@ declare class LiveRequest {
376
341
  */
377
342
  close: boolean;
378
343
  constructor(options?: {
379
- content?: Content$1;
344
+ content?: Content;
380
345
  blob?: Blob;
381
346
  close?: boolean;
382
347
  });
@@ -395,7 +360,7 @@ declare class LiveRequestQueue {
395
360
  /**
396
361
  * Send content to the queue.
397
362
  */
398
- sendContent(content: Content$1): void;
363
+ sendContent(content: Content): void;
399
364
  /**
400
365
  * Send realtime blob to the queue.
401
366
  */
@@ -514,10 +479,10 @@ declare class TranscriptionEntry {
514
479
  /**
515
480
  * The data that can be used for transcription
516
481
  */
517
- data: Blob | Content$1;
482
+ data: Blob | Content;
518
483
  constructor(options: {
519
484
  role?: string;
520
- data: Blob | Content$1;
485
+ data: Blob | Content;
521
486
  });
522
487
  }
523
488
 
@@ -596,7 +561,7 @@ declare class InvocationContext {
596
561
  /**
597
562
  * The user content that started this invocation. Readonly.
598
563
  */
599
- readonly userContent?: Content$1;
564
+ readonly userContent?: Content;
600
565
  /**
601
566
  * The current session of this invocation context. Readonly.
602
567
  */
@@ -638,7 +603,7 @@ declare class InvocationContext {
638
603
  invocationId?: string;
639
604
  branch?: string;
640
605
  agent: BaseAgent;
641
- userContent?: Content$1;
606
+ userContent?: Content;
642
607
  session: Session;
643
608
  endInvocation?: boolean;
644
609
  liveRequestQueue?: LiveRequestQueue;
@@ -675,7 +640,7 @@ declare class ReadonlyContext {
675
640
  /**
676
641
  * The user content that started this invocation. READONLY field.
677
642
  */
678
- get userContent(): Content$1 | undefined;
643
+ get userContent(): Content | undefined;
679
644
  /**
680
645
  * The current invocation id.
681
646
  */
@@ -793,17 +758,6 @@ interface ToolConfig {
793
758
  */
794
759
  maxRetryAttempts?: number;
795
760
  }
796
- /**
797
- * LLM request interface for processing outgoing requests
798
- */
799
- interface LlmRequest$1 {
800
- toolsDict: Record<string, BaseTool>;
801
- config?: {
802
- tools?: Array<{
803
- functionDeclarations?: FunctionDeclaration[];
804
- }>;
805
- };
806
- }
807
761
  /**
808
762
  * API variant types
809
763
  */
@@ -886,7 +840,7 @@ declare abstract class BaseTool {
886
840
  * @param toolContext The context of the tool
887
841
  * @param llmRequest The outgoing LLM request, mutable by this method
888
842
  */
889
- processLlmRequest(_toolContext: ToolContext, llmRequest: LlmRequest$1): Promise<void>;
843
+ processLlmRequest(_toolContext: ToolContext, llmRequest: LlmRequest): Promise<void>;
890
844
  /**
891
845
  * Gets the API variant for this tool
892
846
  */
@@ -1009,2617 +963,2687 @@ interface CreateToolConfigWithoutSchema {
1009
963
  declare function createTool<T extends Record<string, any>>(config: CreateToolConfigWithSchema<T>): BaseTool;
1010
964
  declare function createTool(config: CreateToolConfigWithoutSchema): BaseTool;
1011
965
 
1012
- /**
1013
- * A tool that wraps a user-defined TypeScript function.
1014
- *
1015
- * This tool automatically generates a function declaration from the function's
1016
- * signature and documentation, making it easy to expose functions to agents.
1017
- */
1018
- declare class FunctionTool<T extends Record<string, any>> extends BaseTool {
1019
- private func;
1020
- private mandatoryArgs;
1021
- private parameterTypes;
966
+ interface File {
967
+ /** The name of the file with file extension (e.g., "file.csv") */
968
+ name: string;
969
+ /** The base64-encoded bytes of the file content */
970
+ content: string;
971
+ /** The mime type of the file (e.g., "image/png") */
972
+ mimeType: string;
973
+ }
974
+ interface CodeExecutionInput {
975
+ /** The code to execute */
976
+ code: string;
977
+ /** The input files available to the code */
978
+ inputFiles: File[];
979
+ /** The execution ID for the stateful code execution */
980
+ executionId?: string;
981
+ }
982
+ interface CodeExecutionResult {
983
+ /** The standard output of the code execution */
984
+ stdout: string;
985
+ /** The standard error of the code execution */
986
+ stderr: string;
987
+ /** The output files from the code execution */
988
+ outputFiles: File[];
989
+ }
990
+ declare class CodeExecutionUtils {
1022
991
  /**
1023
- * Creates a new FunctionTool wrapping the provided function.
1024
- *
1025
- * @param func The function to wrap
1026
- * @param options Optional configuration for the tool
992
+ * Gets the file content as a base64-encoded string
1027
993
  */
1028
- constructor(func: (...args: any[]) => any, options?: {
1029
- name?: string;
1030
- description?: string;
1031
- isLongRunning?: boolean;
1032
- shouldRetryOnFailure?: boolean;
1033
- maxRetryAttempts?: number;
1034
- parameterTypes?: Record<string, string>;
1035
- });
994
+ static getEncodedFileContent(data: string | ArrayBuffer): string;
995
+ private static isBase64Encoded;
1036
996
  /**
1037
- * Executes the wrapped function with the provided arguments.
997
+ * Extracts the first code block from the content and truncates everything after it
1038
998
  */
1039
- runAsync(args: T, context: ToolContext): Promise<any>;
999
+ static extractCodeAndTruncateContent(content: Content, codeBlockDelimiters: Array<[string, string]>): string | null;
1000
+ private static escapeRegex;
1040
1001
  /**
1041
- * Returns the function declaration for this tool.
1002
+ * Builds an executable code part with code string
1042
1003
  */
1043
- getDeclaration(): FunctionDeclaration;
1004
+ static buildExecutableCodePart(code: string): Part;
1044
1005
  /**
1045
- * Checks if the wrapped function accepts a toolContext parameter.
1006
+ * Builds the code execution result part from the code execution result
1046
1007
  */
1047
- private functionAcceptsToolContext;
1008
+ static buildCodeExecutionResultPart(codeExecutionResult: CodeExecutionResult): Part;
1048
1009
  /**
1049
- * Checks if the wrapped function is async.
1010
+ * Converts the code execution parts to text parts in a Content
1050
1011
  */
1051
- private isAsyncFunction;
1012
+ static convertCodeExecutionParts(content: Content, codeBlockDelimiter: [string, string], executionResultDelimiters: [string, string]): void;
1013
+ }
1014
+
1015
+ interface BaseCodeExecutorConfig {
1052
1016
  /**
1053
- * Extracts the mandatory arguments from a function.
1054
- * In TypeScript, we can't easily inspect parameter defaults at runtime,
1055
- * so this is a best-effort approach.
1017
+ * If true, extract and process data files from the model request
1018
+ * and attach them to the code executor.
1019
+ * Supported data file MimeTypes are [text/csv].
1020
+ * Default to false.
1056
1021
  */
1057
- private getMandatoryArgs;
1022
+ optimizeDataFile?: boolean;
1058
1023
  /**
1059
- * Checks which mandatory arguments are missing from the provided args.
1024
+ * Whether the code executor is stateful. Default to false.
1060
1025
  */
1061
- private getMissingMandatoryArgs;
1026
+ stateful?: boolean;
1062
1027
  /**
1063
- * Extracts the function parameters from the function's signature.
1028
+ * The number of attempts to retry on consecutive code execution errors.
1029
+ * Default to 2.
1064
1030
  */
1065
- private getFunctionParameters;
1031
+ errorRetryAttempts?: number;
1066
1032
  /**
1067
- * Converts an argument to the proper type based on the function signature.
1033
+ * The list of the enclosing delimiters to identify the code blocks.
1034
+ * For example, the delimiter ['```python\n', '\n```'] can be
1035
+ * used to identify code blocks with the following format:
1036
+ *
1037
+ * ```python
1038
+ * print("hello")
1039
+ * ```
1068
1040
  */
1069
- private convertArgumentType;
1041
+ codeBlockDelimiters?: Array<[string, string]>;
1070
1042
  /**
1071
- * Extracts the type of a specific parameter from the function signature.
1043
+ * The delimiters to format the code execution result.
1072
1044
  */
1073
- private getParameterType;
1045
+ executionResultDelimiters?: [string, string];
1046
+ }
1047
+ declare abstract class BaseCodeExecutor {
1048
+ protected readonly config: Required<BaseCodeExecutorConfig>;
1049
+ constructor(config?: BaseCodeExecutorConfig);
1050
+ /**
1051
+ * Executes code and returns the code execution result.
1052
+ */
1053
+ abstract executeCode(invocationContext: InvocationContext, codeExecutionInput: CodeExecutionInput): Promise<CodeExecutionResult>;
1054
+ get optimizeDataFile(): boolean;
1055
+ get stateful(): boolean;
1056
+ get errorRetryAttempts(): number;
1057
+ get codeBlockDelimiters(): Array<[string, string]>;
1058
+ get executionResultDelimiters(): [string, string];
1074
1059
  }
1075
1060
 
1076
1061
  /**
1077
- * Options for building a function declaration
1062
+ * Candidate response from the model.
1078
1063
  */
1079
- interface BuildFunctionDeclarationOptions {
1080
- name?: string;
1081
- description?: string;
1082
- ignoreParams?: string[];
1064
+ interface Candidate {
1065
+ content?: Content;
1066
+ groundingMetadata?: GroundingMetadata;
1067
+ finishReason?: string;
1068
+ finishMessage?: string;
1083
1069
  }
1084
1070
  /**
1085
- * Builds a function declaration from a TypeScript function.
1086
- *
1087
- * This utility analyzes the function signature and JSDoc comments to create
1088
- * a FunctionDeclaration object that can be used with LLMs.
1089
- *
1090
- * @param func The function to analyze
1091
- * @param options Options for customizing the declaration
1092
- * @returns A FunctionDeclaration representing the function
1071
+ * Prompt feedback in case of blocked or failed prompt.
1093
1072
  */
1094
- declare function buildFunctionDeclaration(func: (...args: any[]) => any, options?: BuildFunctionDeclarationOptions): FunctionDeclaration;
1095
-
1073
+ interface PromptFeedback {
1074
+ blockReason?: string;
1075
+ blockReasonMessage?: string;
1076
+ }
1096
1077
  /**
1097
- * Creates a new FunctionTool that wraps a function.
1098
- * This is a convenience function for creating a new FunctionTool.
1099
- *
1100
- * @param func The function to wrap
1101
- * @param options Optional configuration for the tool
1102
- * @returns A new FunctionTool wrapping the function
1078
+ * The response from the model generation API.
1103
1079
  */
1104
- declare function createFunctionTool(func: (...args: any[]) => any, options?: {
1105
- name?: string;
1106
- description?: string;
1107
- isLongRunning?: boolean;
1108
- shouldRetryOnFailure?: boolean;
1109
- maxRetryAttempts?: number;
1110
- }): any;
1111
-
1080
+ interface GenerateContentResponse {
1081
+ candidates?: Candidate[];
1082
+ usageMetadata?: GenerateContentResponseUsageMetadata;
1083
+ promptFeedback?: PromptFeedback;
1084
+ }
1112
1085
  /**
1113
- * Simple GoogleSearch tool implementation
1086
+ * Response from a language model.
1114
1087
  */
1115
- declare class GoogleSearch extends BaseTool {
1116
- protected logger: Logger;
1088
+ declare class LlmResponse {
1117
1089
  /**
1118
- * Constructor for GoogleSearch
1090
+ * Unique identifier for the response.
1119
1091
  */
1120
- constructor();
1092
+ id?: string;
1121
1093
  /**
1122
- * Get the function declaration for the tool
1094
+ * The content generated by the model.
1123
1095
  */
1124
- getDeclaration(): FunctionDeclaration;
1096
+ content?: Content;
1125
1097
  /**
1126
- * Execute the search
1127
- * This is a simplified implementation that doesn't actually search, just returns mock results
1098
+ * The grounding metadata of the response.
1128
1099
  */
1129
- runAsync(args: {
1130
- query: string;
1131
- num_results?: number;
1132
- }, _context: ToolContext): Promise<any>;
1133
- }
1134
-
1135
- interface HttpRequestResult {
1136
- statusCode: number;
1137
- headers: Record<string, string>;
1138
- body: string;
1139
- error?: string;
1140
- }
1141
- /**
1142
- * Tool for making HTTP requests to external APIs and web services
1143
- */
1144
- declare class HttpRequestTool extends BaseTool {
1145
- constructor();
1100
+ groundingMetadata?: GroundingMetadata;
1146
1101
  /**
1147
- * Get the function declaration for the tool
1102
+ * Indicates whether the text content is part of an unfinished text stream.
1148
1103
  */
1149
- getDeclaration(): FunctionDeclaration;
1104
+ partial?: boolean;
1150
1105
  /**
1151
- * Execute the HTTP request
1106
+ * Indicates whether the response from the model is complete.
1152
1107
  */
1153
- runAsync(args: {
1154
- url: string;
1155
- method?: string;
1156
- headers?: Record<string, string>;
1157
- body?: string;
1158
- params?: Record<string, string>;
1159
- timeout?: number;
1160
- }, _context: ToolContext): Promise<HttpRequestResult>;
1108
+ turnComplete?: boolean;
1161
1109
  /**
1162
- * Check if a string is valid JSON
1110
+ * Error code if the response is an error.
1163
1111
  */
1164
- private isValidJson;
1165
- }
1166
-
1167
- interface FileOperationResult {
1168
- success: boolean;
1169
- data?: any;
1170
- error?: string;
1171
- }
1172
- /**
1173
- * Tool for performing file system operations
1174
- */
1175
- declare class FileOperationsTool extends BaseTool {
1176
- private basePath;
1177
- constructor(options?: {
1178
- basePath?: string;
1179
- });
1112
+ errorCode?: string;
1180
1113
  /**
1181
- * Get the function declaration for the tool
1114
+ * Error message if the response is an error.
1182
1115
  */
1183
- getDeclaration(): FunctionDeclaration;
1116
+ errorMessage?: string;
1184
1117
  /**
1185
- * Execute the file operation
1118
+ * Flag indicating that LLM was interrupted when generating the content.
1186
1119
  */
1187
- runAsync(args: {
1188
- operation: "read" | "write" | "append" | "delete" | "exists" | "list" | "mkdir";
1189
- filepath: string;
1190
- content?: string;
1191
- encoding?: BufferEncoding;
1192
- }, _context: ToolContext): Promise<FileOperationResult>;
1193
- /**
1194
- * Resolve a file path relative to the base path
1195
- */
1196
- private resolvePath;
1120
+ interrupted?: boolean;
1197
1121
  /**
1198
- * Validate that a path is within the base path for security
1122
+ * The custom metadata of the LlmResponse.
1199
1123
  */
1200
- private validatePath;
1124
+ customMetadata?: Record<string, any>;
1201
1125
  /**
1202
- * Read a file
1126
+ * The usage metadata of the LlmResponse.
1203
1127
  */
1204
- private readFile;
1128
+ usageMetadata?: GenerateContentResponseUsageMetadata;
1205
1129
  /**
1206
- * Write to a file
1130
+ * Index of the candidate response.
1207
1131
  */
1208
- private writeFile;
1132
+ candidateIndex?: number;
1209
1133
  /**
1210
- * Append to a file
1134
+ * Reason why the model finished generating.
1211
1135
  */
1212
- private appendFile;
1136
+ finishReason?: string;
1213
1137
  /**
1214
- * Delete a file
1138
+ * Error object if the response is an error.
1215
1139
  */
1216
- private deleteFile;
1140
+ error?: Error;
1217
1141
  /**
1218
- * Check if a file exists
1142
+ * Creates a new LlmResponse.
1219
1143
  */
1220
- private fileExists;
1144
+ constructor(data?: Partial<LlmResponse>);
1221
1145
  /**
1222
- * List directory contents
1146
+ * Creates an LlmResponse from a GenerateContentResponse.
1147
+ *
1148
+ * @param generateContentResponse The GenerateContentResponse to create the LlmResponse from.
1149
+ * @returns The LlmResponse.
1223
1150
  */
1224
- private listDirectory;
1151
+ static create(generateContentResponse: GenerateContentResponse): LlmResponse;
1225
1152
  /**
1226
- * Create a directory
1153
+ * Creates an LlmResponse from an error.
1154
+ *
1155
+ * @param error The error object or message.
1156
+ * @param options Additional options for the error response.
1157
+ * @param options.errorCode A specific error code for the response.
1158
+ * @param options.model The model that was being used when the error occurred.
1159
+ * @returns The LlmResponse.
1227
1160
  */
1228
- private makeDirectory;
1161
+ static fromError(error: unknown, options?: {
1162
+ errorCode?: string;
1163
+ model?: string;
1164
+ }): LlmResponse;
1229
1165
  }
1230
1166
 
1231
- interface UserInteractionResult {
1232
- success: boolean;
1233
- userInput?: string;
1234
- error?: string;
1235
- }
1236
1167
  /**
1237
- * Tool for prompting the user for input
1168
+ * The base class for a live model connection.
1238
1169
  */
1239
- declare class UserInteractionTool extends BaseTool {
1240
- constructor();
1170
+ declare abstract class BaseLLMConnection {
1241
1171
  /**
1242
- * Get the function declaration for the tool
1172
+ * Sends the conversation history to the model.
1173
+ *
1174
+ * You call this method right after setting up the model connection.
1175
+ * The model will respond if the last content is from user, otherwise it will
1176
+ * wait for new user input before responding.
1177
+ *
1178
+ * @param history The conversation history to send to the model.
1243
1179
  */
1244
- getDeclaration(): FunctionDeclaration;
1180
+ abstract sendHistory(history: Content[]): Promise<void>;
1245
1181
  /**
1246
- * Execute the user interaction
1182
+ * Sends a user content to the model.
1183
+ *
1184
+ * The model will respond immediately upon receiving the content.
1185
+ * If you send function responses, all parts in the content should be function
1186
+ * responses.
1187
+ *
1188
+ * @param content The content to send to the model.
1247
1189
  */
1248
- runAsync(args: {
1249
- prompt: string;
1250
- options?: string[];
1251
- defaultValue?: string;
1252
- }, context: ToolContext): Promise<UserInteractionResult>;
1253
- }
1254
-
1255
- /**
1256
- * Tool that allows an agent to exit the current execution loop
1257
- */
1258
- declare class ExitLoopTool extends BaseTool {
1259
- protected logger: Logger;
1190
+ abstract sendContent(content: Content): Promise<void>;
1260
1191
  /**
1261
- * Constructor for ExitLoopTool
1192
+ * Sends a chunk of audio or a frame of video to the model in realtime.
1193
+ *
1194
+ * The model may not respond immediately upon receiving the blob. It will do
1195
+ * voice activity detection and decide when to respond.
1196
+ *
1197
+ * @param blob The blob to send to the model.
1262
1198
  */
1263
- constructor();
1199
+ abstract sendRealtime(blob: Blob): Promise<void>;
1264
1200
  /**
1265
- * Execute the exit loop action
1201
+ * Receives the model response using the llm server connection.
1202
+ *
1203
+ * @returns LlmResponse: The model response.
1266
1204
  */
1267
- runAsync(_args: Record<string, any>, context: ToolContext): Promise<any>;
1205
+ abstract receive(): AsyncGenerator<LlmResponse, void, unknown>;
1206
+ /**
1207
+ * Closes the llm server connection.
1208
+ */
1209
+ abstract close(): Promise<void>;
1268
1210
  }
1269
1211
 
1270
1212
  /**
1271
- * Tool that allows an agent to get a choice from the user
1213
+ * The BaseLlm class.
1272
1214
  */
1273
- declare class GetUserChoiceTool extends BaseTool {
1215
+ declare abstract class BaseLlm {
1216
+ /**
1217
+ * The name of the LLM, e.g. gemini-1.5-flash or gemini-1.5-flash-001.
1218
+ */
1219
+ model: string;
1274
1220
  protected logger: Logger;
1275
1221
  /**
1276
- * Constructor for GetUserChoiceTool
1222
+ * Constructor for BaseLlm
1277
1223
  */
1278
- constructor();
1224
+ constructor(model: string);
1279
1225
  /**
1280
- * Get the function declaration for the tool
1226
+ * Returns a list of supported models in regex for LLMRegistry
1281
1227
  */
1282
- getDeclaration(): FunctionDeclaration;
1228
+ static supportedModels(): string[];
1283
1229
  /**
1284
- * Execute the user choice action
1285
- * This is a long running operation that will return null initially
1286
- * and the actual choice will be provided asynchronously
1230
+ * Generates one content from the given contents and tools.
1231
+ *
1232
+ * @param llmRequest LlmRequest, the request to send to the LLM.
1233
+ * @param stream bool = false, whether to do streaming call.
1234
+ * @returns a generator of LlmResponse.
1235
+ *
1236
+ * For non-streaming call, it will only yield one LlmResponse.
1237
+ *
1238
+ * For streaming call, it may yield more than one response, but all yielded
1239
+ * responses should be treated as one response by merging the
1240
+ * parts list.
1287
1241
  */
1288
- runAsync(args: {
1289
- options: string[];
1290
- question?: string;
1291
- }, context: ToolContext): Promise<any>;
1292
- }
1293
-
1294
- /**
1295
- * Tool that allows an agent to transfer control to another agent
1296
- */
1297
- declare class TransferToAgentTool extends BaseTool {
1298
- protected logger: Logger;
1242
+ generateContentAsync(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
1299
1243
  /**
1300
- * Constructor for TransferToAgentTool
1244
+ * Implementation method to be overridden by subclasses.
1245
+ * This replaces the abstract generateContentAsync method.
1301
1246
  */
1302
- constructor();
1247
+ protected abstract generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
1303
1248
  /**
1304
- * Execute the transfer to agent action
1249
+ * Appends a user content, so that model can continue to output.
1250
+ *
1251
+ * @param llmRequest LlmRequest, the request to send to the LLM.
1305
1252
  */
1306
- runAsync(args: {
1307
- agent_name: string;
1308
- }, context: ToolContext): Promise<any>;
1253
+ protected maybeAppendUserContent(llmRequest: LlmRequest): void;
1254
+ /**
1255
+ * Creates a live connection to the LLM.
1256
+ *
1257
+ * @param llmRequest LlmRequest, the request to send to the LLM.
1258
+ * @returns BaseLLMConnection, the connection to the LLM.
1259
+ */
1260
+ connect(llmRequest: LlmRequest): BaseLLMConnection;
1309
1261
  }
1310
1262
 
1311
1263
  /**
1312
- * Tool that allows an agent to load memories relevant to a query
1264
+ * Abstract base class for all planners.
1265
+ *
1266
+ * The planner allows the agent to generate plans for the queries to guide its action.
1313
1267
  */
1314
- declare class LoadMemoryTool extends BaseTool {
1315
- protected logger: Logger;
1316
- /**
1317
- * Constructor for LoadMemoryTool
1318
- */
1319
- constructor();
1268
+ declare abstract class BasePlanner {
1320
1269
  /**
1321
- * Get the function declaration for the tool
1270
+ * Builds the system instruction to be appended to the LLM request for planning.
1271
+ *
1272
+ * @param readonlyContext The readonly context of the invocation
1273
+ * @param llmRequest The LLM request. Readonly.
1274
+ * @returns The planning system instruction, or undefined if no instruction is needed
1322
1275
  */
1323
- getDeclaration(): FunctionDeclaration;
1276
+ abstract buildPlanningInstruction(readonlyContext: ReadonlyContext, llmRequest: LlmRequest): string | undefined;
1324
1277
  /**
1325
- * Execute the memory loading action
1278
+ * Processes the LLM response for planning.
1279
+ *
1280
+ * @param callbackContext The callback context of the invocation
1281
+ * @param responseParts The LLM response parts. Readonly.
1282
+ * @returns The processed response parts, or undefined if no processing is needed
1326
1283
  */
1327
- runAsync(args: {
1328
- query: string;
1329
- }, context: ToolContext): Promise<any>;
1284
+ abstract processPlanningResponse(callbackContext: CallbackContext, responseParts: Part[]): Part[] | undefined;
1330
1285
  }
1331
1286
 
1332
1287
  /**
1333
- * Content interface for LLM requests
1288
+ * Type for instruction providers that can be functions
1334
1289
  */
1335
- interface Content {
1336
- role: string;
1337
- parts: Part[];
1338
- }
1290
+ type InstructionProvider = (ctx: ReadonlyContext) => string | Promise<string>;
1339
1291
  /**
1340
- * Extended LLM request interface with content support
1292
+ * Union type for tools (supporting functions, tools, and toolsets)
1341
1293
  */
1342
- interface ExtendedLlmRequest extends LlmRequest$1 {
1343
- contents?: Content[];
1344
- appendInstructions?: (instructions: string[]) => void;
1345
- }
1294
+ type ToolUnion = BaseTool | ((...args: any[]) => any);
1346
1295
  /**
1347
- * A tool that loads the artifacts and adds them to the session.
1296
+ * Configuration for LlmAgent
1348
1297
  */
1349
- declare class LoadArtifactsTool extends BaseTool {
1350
- constructor();
1298
+ interface LlmAgentConfig<T extends BaseLlm = BaseLlm> {
1351
1299
  /**
1352
- * Get the function declaration for the tool
1300
+ * Name of the agent
1353
1301
  */
1354
- getDeclaration(): FunctionDeclaration;
1302
+ name: string;
1355
1303
  /**
1356
- * Execute the load artifacts operation
1304
+ * Description of the agent
1357
1305
  */
1358
- runAsync(args: {
1359
- artifact_names?: string[];
1360
- }, context: ToolContext): Promise<{
1361
- artifact_names: string[];
1362
- }>;
1306
+ description: string;
1363
1307
  /**
1364
- * Processes the outgoing LLM request for this tool.
1308
+ * The LLM model to use
1309
+ * When not set, the agent will inherit the model from its ancestor
1365
1310
  */
1366
- processLlmRequest(toolContext: ToolContext, llmRequest: ExtendedLlmRequest): Promise<void>;
1311
+ model?: string | T | LanguageModel;
1367
1312
  /**
1368
- * Appends artifacts information to the LLM request
1313
+ * Instructions for the LLM model, guiding the agent's behavior
1369
1314
  */
1370
- private appendArtifactsToLlmRequest;
1315
+ instruction?: string | InstructionProvider;
1371
1316
  /**
1372
- * Extracts function response from a part if it exists
1317
+ * Instructions for all the agents in the entire agent tree
1318
+ * ONLY the global_instruction in root agent will take effect
1373
1319
  */
1374
- private extractFunctionResponse;
1375
- }
1376
-
1377
- type McpConfig = {
1378
- name: string;
1379
- description: string;
1380
- transport: McpTransportType;
1381
- timeout?: number;
1382
- retryOptions?: {
1383
- maxRetries?: number;
1384
- initialDelay?: number;
1385
- maxDelay?: number;
1386
- };
1387
- headers?: Record<string, string>;
1388
- cacheConfig?: {
1389
- enabled?: boolean;
1390
- maxAge?: number;
1391
- maxSize?: number;
1392
- };
1393
- debug?: boolean;
1320
+ globalInstruction?: string | InstructionProvider;
1394
1321
  /**
1395
- * Sampling handler for processing MCP sampling requests.
1396
- * This allows MCP servers to request LLM completions through your ADK agent.
1322
+ * Tools available to this agent
1397
1323
  */
1398
- samplingHandler?: SamplingHandler;
1399
- };
1400
- type McpTransportType = {
1401
- mode: "stdio";
1402
- command: string;
1403
- args: string[];
1404
- env?: Record<string, string>;
1405
- } | {
1406
- mode: "sse";
1407
- serverUrl: string;
1408
- headers?: HeadersInit;
1409
- };
1410
- /**
1411
- * Error types specific to the MCP client
1412
- */
1413
- declare enum McpErrorType {
1414
- CONNECTION_ERROR = "connection_error",
1415
- TOOL_EXECUTION_ERROR = "tool_execution_error",
1416
- RESOURCE_CLOSED_ERROR = "resource_closed_error",
1417
- TIMEOUT_ERROR = "timeout_error",
1418
- INVALID_SCHEMA_ERROR = "invalid_schema_error",
1419
- SAMPLING_ERROR = "SAMPLING_ERROR",
1420
- INVALID_REQUEST_ERROR = "INVALID_REQUEST_ERROR"
1421
- }
1422
- /**
1423
- * Custom error class for MCP-related errors
1424
- */
1425
- declare class McpError extends Error {
1426
- type: McpErrorType;
1427
- originalError?: Error;
1428
- constructor(message: string, type: McpErrorType, originalError?: Error);
1429
- }
1430
- type McpSamplingRequest = z$1.infer<typeof CreateMessageRequestSchema>;
1431
- type McpSamplingResponse = z$1.infer<typeof CreateMessageResultSchema>;
1432
- type SamplingHandler = (request: LlmRequest) => Promise<string | LlmResponse>;
1433
-
1434
- declare class McpClientService {
1435
- private config;
1436
- private client;
1437
- private transport;
1438
- private isClosing;
1439
- private mcpSamplingHandler;
1440
- protected logger: Logger;
1441
- constructor(config: McpConfig);
1324
+ tools?: ToolUnion[];
1442
1325
  /**
1443
- * Initializes and returns an MCP client based on configuration.
1444
- * Will create a new client if one doesn't exist yet.
1326
+ * Code executor for this agent
1445
1327
  */
1446
- initialize(): Promise<Client>;
1328
+ codeExecutor?: BaseCodeExecutor;
1447
1329
  /**
1448
- * Creates a transport based on the configuration.
1330
+ * Disallows LLM-controlled transferring to the parent agent
1449
1331
  */
1450
- private createTransport;
1332
+ disallowTransferToParent?: boolean;
1451
1333
  /**
1452
- * Re-initializes the MCP client when a session is closed.
1453
- * Used by the retry mechanism.
1334
+ * Disallows LLM-controlled transferring to the peer agents
1454
1335
  */
1455
- reinitialize(): Promise<void>;
1336
+ disallowTransferToPeers?: boolean;
1456
1337
  /**
1457
- * Cleans up resources associated with this client service.
1458
- * Similar to Python's AsyncExitStack.aclose() functionality.
1338
+ * Whether to include contents in the model request
1459
1339
  */
1460
- private cleanupResources;
1340
+ includeContents?: "default" | "none";
1461
1341
  /**
1462
- * Call an MCP tool with retry capability if the session is closed.
1342
+ * The output key in session state to store the output of the agent
1463
1343
  */
1464
- callTool(name: string, args: Record<string, any>): Promise<any>;
1344
+ outputKey?: string;
1465
1345
  /**
1466
- * Closes and cleans up all resources.
1467
- * Should be called when the service is no longer needed.
1468
- * Similar to Python's close() method.
1346
+ * Instructs the agent to make a plan and execute it step by step
1469
1347
  */
1470
- close(): Promise<void>;
1348
+ planner?: BasePlanner;
1471
1349
  /**
1472
- * Checks if the client is currently connected
1350
+ * Memory service for long-term storage and retrieval
1473
1351
  */
1474
- isConnected(): boolean;
1475
- private setupSamplingHandler;
1352
+ memoryService?: BaseMemoryService;
1476
1353
  /**
1477
- * Set a new ADK sampling handler
1354
+ * Session service for managing conversations
1478
1355
  */
1479
- setSamplingHandler(handler: SamplingHandler): void;
1356
+ sessionService?: BaseSessionService;
1480
1357
  /**
1481
- * Remove the sampling handler
1358
+ * Artifact service for file storage and management
1482
1359
  */
1483
- removeSamplingHandler(): void;
1360
+ artifactService?: BaseArtifactService;
1361
+ /**
1362
+ * User ID for the session
1363
+ */
1364
+ userId?: string;
1365
+ /**
1366
+ * Application name
1367
+ */
1368
+ appName?: string;
1369
+ /**
1370
+ * Additional content generation configurations
1371
+ * NOTE: not all fields are usable, e.g. tools must be configured via `tools`,
1372
+ * thinking_config must be configured via `planner` in LlmAgent.
1373
+ */
1374
+ generateContentConfig?: GenerateContentConfig;
1375
+ /**
1376
+ * The input schema when agent is used as a tool
1377
+ */
1378
+ inputSchema?: any;
1379
+ /**
1380
+ * The output schema when agent replies
1381
+ * NOTE: when this is set, agent can ONLY reply and CANNOT use any tools
1382
+ */
1383
+ outputSchema?: any;
1484
1384
  }
1485
-
1486
- /**
1487
- * Converts an ADK-style BaseTool to an MCP tool format
1488
- * Similar to Python's adk_to_mcp_tool_type function
1489
- */
1490
- declare function adkToMcpToolType(tool: BaseTool): Tool;
1491
- /**
1492
- * Converts MCP JSONSchema to ADK's FunctionDeclaration format
1493
- * Similar to handling in McpToolAdapter's getDeclaration
1494
- */
1495
- declare function jsonSchemaToDeclaration(name: string, description: string, schema: Record<string, any> | undefined): FunctionDeclaration;
1496
- /**
1497
- * Normalizes a JSON Schema to ensure it's properly formatted
1498
- * Handles edge cases and ensures consistency
1499
- */
1500
- declare function normalizeJsonSchema(schema: Record<string, any>): JSONSchema;
1501
- /**
1502
- * Converts MCP tool inputSchema to parameters format expected by BaseTool
1503
- */
1504
- declare function mcpSchemaToParameters(mcpTool: Tool): JSONSchema;
1505
-
1506
1385
  /**
1507
- * MCP Sampling Handler class that handles message format conversion
1508
- * between MCP format and ADK format
1386
+ * LLM-based Agent
1509
1387
  */
1510
- declare class McpSamplingHandler {
1388
+ declare class LlmAgent<T extends BaseLlm = BaseLlm> extends BaseAgent {
1389
+ /**
1390
+ * The model to use for the agent
1391
+ * When not set, the agent will inherit the model from its ancestor
1392
+ */
1393
+ model: string | T | LanguageModel;
1394
+ /**
1395
+ * Instructions for the LLM model, guiding the agent's behavior
1396
+ */
1397
+ instruction: string | InstructionProvider;
1398
+ /**
1399
+ * Instructions for all the agents in the entire agent tree
1400
+ * ONLY the global_instruction in root agent will take effect
1401
+ */
1402
+ globalInstruction: string | InstructionProvider;
1403
+ /**
1404
+ * Tools available to this agent
1405
+ */
1406
+ tools: ToolUnion[];
1407
+ /**
1408
+ * Code executor for this agent
1409
+ */
1410
+ codeExecutor?: BaseCodeExecutor;
1411
+ /**
1412
+ * Disallows LLM-controlled transferring to the parent agent
1413
+ */
1414
+ disallowTransferToParent: boolean;
1415
+ /**
1416
+ * Disallows LLM-controlled transferring to the peer agents
1417
+ */
1418
+ disallowTransferToPeers: boolean;
1419
+ /**
1420
+ * Whether to include contents in the model request
1421
+ */
1422
+ includeContents: "default" | "none";
1423
+ /**
1424
+ * The output key in session state to store the output of the agent
1425
+ */
1426
+ outputKey?: string;
1427
+ /**
1428
+ * Instructs the agent to make a plan and execute it step by step
1429
+ */
1430
+ planner?: BasePlanner;
1431
+ /**
1432
+ * Memory service for long-term storage and retrieval
1433
+ */
1434
+ private memoryService?;
1435
+ /**
1436
+ * Session service for managing conversations
1437
+ */
1438
+ private sessionService?;
1439
+ /**
1440
+ * Artifact service for file storage and management
1441
+ */
1442
+ private artifactService?;
1443
+ /**
1444
+ * User ID for the session
1445
+ */
1446
+ private userId?;
1447
+ /**
1448
+ * Application name
1449
+ */
1450
+ private appName?;
1451
+ /**
1452
+ * Additional content generation configurations
1453
+ */
1454
+ generateContentConfig?: GenerateContentConfig;
1455
+ /**
1456
+ * The input schema when agent is used as a tool
1457
+ */
1458
+ inputSchema?: any;
1459
+ /**
1460
+ * The output schema when agent replies
1461
+ */
1462
+ outputSchema?: any;
1511
1463
  protected logger: Logger;
1512
- private samplingHandler;
1513
- constructor(samplingHandler: SamplingHandler);
1514
1464
  /**
1515
- * Handle MCP sampling request and convert between formats
1465
+ * Constructor for LlmAgent
1516
1466
  */
1517
- handleSamplingRequest(request: McpSamplingRequest): Promise<McpSamplingResponse>;
1467
+ constructor(config: LlmAgentConfig<T>);
1518
1468
  /**
1519
- * Convert MCP messages to ADK Content format
1469
+ * The resolved model field as BaseLLM
1470
+ * This method is only for use by Agent Development Kit
1520
1471
  */
1521
- private convertMcpMessagesToADK;
1472
+ get canonicalModel(): BaseLlm;
1522
1473
  /**
1523
- * Convert a single MCP message to ADK Content format
1474
+ * The resolved instruction field to construct instruction for this agent
1475
+ * This method is only for use by Agent Development Kit
1524
1476
  */
1525
- private convertSingleMcpMessageToADK;
1477
+ canonicalInstruction(ctx: ReadonlyContext): Promise<[string, boolean]>;
1526
1478
  /**
1527
- * Convert MCP message content to ADK parts format
1479
+ * The resolved global_instruction field to construct global instruction
1480
+ * This method is only for use by Agent Development Kit
1528
1481
  */
1529
- private convertMcpContentToADKParts;
1482
+ canonicalGlobalInstruction(ctx: ReadonlyContext): Promise<[string, boolean]>;
1530
1483
  /**
1531
- * Convert ADK response to MCP response format
1484
+ * The resolved tools field as a list of BaseTool based on the context
1485
+ * This method is only for use by Agent Development Kit
1532
1486
  */
1533
- private convertADKResponseToMcp;
1487
+ canonicalTools(ctx?: ReadonlyContext): Promise<BaseTool[]>;
1534
1488
  /**
1535
- * Update the ADK handler
1489
+ * Gets the appropriate LLM flow for this agent
1490
+ * This matches the Python implementation's _llm_flow property
1536
1491
  */
1537
- updateHandler(handler: SamplingHandler): void;
1492
+ private get llmFlow();
1493
+ /**
1494
+ * Saves the model output to state if needed
1495
+ * This matches the Python implementation's __maybe_save_output_to_state
1496
+ */
1497
+ private maybeSaveOutputToState;
1498
+ /**
1499
+ * Core logic to run this agent via text-based conversation
1500
+ * This matches the Python implementation's _run_async_impl
1501
+ */
1502
+ protected runAsyncImpl(context: InvocationContext): AsyncGenerator<Event, void, unknown>;
1538
1503
  }
1504
+
1539
1505
  /**
1540
- * Helper function to create a sampling handler with proper TypeScript types.
1541
- *
1542
- * @param handler - Function that handles sampling requests
1543
- * @returns Properly typed ADK sampling handler
1544
- *
1545
- * @example
1546
- * ```typescript
1547
- * import { createSamplingHandler, Gemini } from "@iqai/adk";
1548
- *
1549
- * const llm = new Gemini("gemini-2.0-flash-exp");
1550
- *
1551
- * // Example 1: Return full LlmResponse
1552
- * const samplingHandler1 = createSamplingHandler(async (request) => {
1553
- * const responses = [];
1554
- * for await (const response of llm.generateContentAsync(request)) {
1555
- * responses.push(response);
1556
- * }
1557
- * return responses[responses.length - 1];
1558
- * });
1559
- *
1560
- * // Example 2: Return simple string
1561
- * const samplingHandler2 = createSamplingHandler(async (request) => {
1562
- * const lastMessage = request.contents[request.contents.length - 1].parts[0].text;
1563
- * return await runner.ask(lastMessage);
1564
- * });
1565
- *
1566
- * // Example 3: Direct function reference
1567
- * const samplingHandler3 = createSamplingHandler(runner.ask);
1568
- * ```
1569
- */
1570
- declare function createSamplingHandler(handler: SamplingHandler): SamplingHandler;
1571
-
1572
- /**
1573
- * Simplified MCP Server Wrappers
1574
- *
1575
- * This module provides simplified wrapper functions for IQAI MCP servers and popular third-party MCP servers.
1576
- * Instead of manually configuring McpToolset with verbose configuration objects, you can use these
1577
- * convenience functions with flexible configuration objects.
1578
- *
1579
- * @example
1580
- * ```typescript
1581
- * // Old verbose way:
1582
- * const toolset = new McpToolset({
1583
- * name: "Near Intents Swaps MCP Client",
1584
- * description: "Client for Near Intents Swaps",
1585
- * debug: env.DEBUG,
1586
- * retryOptions: { maxRetries: 2, initialDelay: 200 },
1587
- * transport: {
1588
- * mode: "stdio",
1589
- * command: "npx",
1590
- * args: ["-y", "@iqai/mcp-near"],
1591
- * env: {
1592
- * ACCOUNT_ID: env.ACCOUNT_ID,
1593
- * ACCOUNT_KEY: env.ACCOUNT_KEY,
1594
- * NEAR_NETWORK_ID: "testnet",
1595
- * PATH: env.PATH
1596
- * },
1597
- * },
1598
- * });
1599
- *
1600
- * // New simplified way:
1601
- * const toolset = McpNearAgent({
1602
- * env: {
1603
- * ACCOUNT_ID: env.ACCOUNT_ID,
1604
- * ACCOUNT_KEY: env.ACCOUNT_KEY,
1605
- * NEAR_NETWORK_ID: "testnet",
1606
- * PATH: env.PATH
1607
- * }
1608
- * });
1609
- *
1610
- * // Usage with LLM Agent:
1611
- * const nearTools = await toolset.getTools();
1612
- * const agent = new LlmAgent({
1613
- * name: "near_assistant",
1614
- * model: "gemini-2.5-flash",
1615
- * tools: nearTools,
1616
- * });
1617
- * ```
1618
- *
1619
- * @example
1620
- * ```typescript
1621
- * // Multiple MCP servers:
1622
- * const atpTools = await McpAtp({
1623
- * env: {
1624
- * ATP_WALLET_PRIVATE_KEY: env.WALLET_PRIVATE_KEY,
1625
- * ATP_API_KEY: env.ATP_API_KEY
1626
- * }
1627
- * }).getTools();
1628
- *
1629
- * const fraxlendTools = await McpFraxlend({
1630
- * env: {
1631
- * WALLET_PRIVATE_KEY: env.WALLET_PRIVATE_KEY
1632
- * }
1633
- * }).getTools();
1634
- *
1635
- * const agent = new LlmAgent({
1636
- * name: "defi_assistant",
1637
- * model: "gemini-2.5-flash",
1638
- * tools: [...atpTools, ...fraxlendTools],
1639
- * });
1640
- * ```
1641
- *
1642
- * @example
1643
- * ```typescript
1644
- * // Using MCP servers with sampling handlers:
1645
- * import { createSamplingHandler, LlmResponse } from "@iqai/adk";
1646
- *
1647
- * const samplingHandler = createSamplingHandler(async (request) => {
1648
- * // Handle MCP sampling requests
1649
- * return new LlmResponse({
1650
- * content: {
1651
- * role: "model",
1652
- * parts: [{ text: "Response from sampling handler" }],
1653
- * },
1654
- * });
1655
- * });
1656
- *
1657
- * const nearTools = await McpNearAgent({
1658
- * env: {
1659
- * ACCOUNT_ID: env.ACCOUNT_ID,
1660
- * ACCOUNT_KEY: env.ACCOUNT_KEY,
1661
- * NEAR_NETWORK_ID: "testnet",
1662
- * PATH: env.PATH
1663
- * },
1664
- * samplingHandler
1665
- * }).getTools();
1666
- *
1667
- * const agent = new LlmAgent({
1668
- * name: "near_assistant",
1669
- * model: "gemini-2.5-flash",
1670
- * tools: nearTools,
1671
- * });
1672
- * ```
1506
+ * Type for agents that can be used as tools
1673
1507
  */
1508
+ type BaseAgentType = LlmAgent;
1674
1509
  /**
1675
- * Base configuration interface for MCP servers
1510
+ * Configuration for AgentTool
1676
1511
  */
1677
- interface McpServerConfig {
1678
- /** Environment variables to pass to the MCP server */
1679
- env?: Record<string, any>;
1680
- /** Enable debug logging */
1681
- debug?: boolean;
1682
- /** Custom description for the MCP server */
1512
+ interface AgentToolConfig {
1513
+ /**
1514
+ * Name of the tool
1515
+ */
1516
+ name: string;
1517
+ /**
1518
+ * Description of the tool
1519
+ */
1683
1520
  description?: string;
1684
- /** Retry configuration */
1685
- retryOptions?: {
1686
- maxRetries?: number;
1687
- initialDelay?: number;
1688
- };
1689
- /** Sampling handler for processing MCP sampling requests */
1690
- samplingHandler?: SamplingHandler;
1521
+ /**
1522
+ * The agent that will be used as a tool
1523
+ */
1524
+ agent: BaseAgentType;
1525
+ /**
1526
+ * Optional function declaration schema override
1527
+ */
1528
+ functionDeclaration?: FunctionDeclaration;
1529
+ /**
1530
+ * Optional key to store the tool output in the state
1531
+ */
1532
+ outputKey?: string;
1533
+ /**
1534
+ * Optional flag to skip summarization of the agent's response
1535
+ */
1536
+ skipSummarization?: boolean;
1537
+ /**
1538
+ * Whether the tool is a long running operation
1539
+ */
1540
+ isLongRunning?: boolean;
1541
+ /**
1542
+ * Whether the tool execution should be retried on failure
1543
+ */
1544
+ shouldRetryOnFailure?: boolean;
1545
+ /**
1546
+ * Maximum retry attempts
1547
+ */
1548
+ maxRetryAttempts?: number;
1691
1549
  }
1692
1550
  /**
1693
- * MCP ABI - Smart contract ABI interactions for Ethereum-compatible blockchains
1694
- *
1695
- * Required env vars: CONTRACT_ABI, CONTRACT_ADDRESS
1696
- * Optional env vars: CONTRACT_NAME, CHAIN_ID, RPC_URL, WALLET_PRIVATE_KEY
1697
- */
1698
- declare function McpAbi(config?: McpServerConfig): McpToolset;
1699
- /**
1700
- * MCP ATP - Interact with the IQ AI Agent Tokenization Platform
1551
+ * A tool that uses an agent to perform a task.
1701
1552
  *
1702
- * Required env vars: ATP_WALLET_PRIVATE_KEY, ATP_API_KEY
1553
+ * This tool allows specialized agents to be used as reusable tools
1554
+ * within other agents, enabling modular agent composition and
1555
+ * domain-specific expertise as services.
1703
1556
  */
1704
- declare function McpAtp(config?: McpServerConfig): McpToolset;
1705
- /**
1706
- * MCP BAMM - Borrow Automated Market Maker operations on Fraxtal
1707
- *
1708
- * Required env vars: WALLET_PRIVATE_KEY
1709
- */
1710
- declare function McpBamm(config?: McpServerConfig): McpToolset;
1711
- /**
1712
- * MCP FRAXLEND - Interact with the Fraxlend lending platform
1713
- *
1714
- * Required env vars: WALLET_PRIVATE_KEY
1715
- */
1716
- declare function McpFraxlend(config?: McpServerConfig): McpToolset;
1717
- /**
1718
- * MCP IQWiki - Access and manage IQ.wiki data and user activities
1719
- *
1720
- * No required env vars
1721
- */
1722
- declare function McpIqWiki(config?: McpServerConfig): McpToolset;
1723
- /**
1724
- * MCP NEAR Agent - NEAR Protocol blockchain integration with AI-driven event processing
1725
- *
1726
- * Required env vars: ACCOUNT_ID, ACCOUNT_KEY
1727
- * Optional env vars: NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
1728
- */
1729
- declare function McpNearAgent(config?: McpServerConfig): McpToolset;
1730
- /**
1731
- * MCP Near Intents Swaps - NEAR Protocol intent swaps functionality
1732
- *
1733
- * Required env vars: ACCOUNT_ID, ACCOUNT_KEY
1734
- * Optional env vars: NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
1735
- */
1736
- declare function McpNearIntentSwaps(config?: McpServerConfig): McpToolset;
1737
- /**
1738
- * MCP ODOS - Interact with decentralized exchanges through ODOS aggregation
1739
- *
1740
- * Required env vars: WALLET_PRIVATE_KEY
1741
- */
1742
- declare function McpOdos(config?: McpServerConfig): McpToolset;
1743
- /**
1744
- * MCP Telegram - Interact with Telegram bots and channels
1745
- *
1746
- * Required env vars: TELEGRAM_BOT_TOKEN
1747
- */
1748
- declare function McpTelegram(config?: McpServerConfig): McpToolset;
1557
+ declare class AgentTool extends BaseTool {
1558
+ /**
1559
+ * The agent used by this tool
1560
+ */
1561
+ private agent;
1562
+ /**
1563
+ * The function declaration schema
1564
+ */
1565
+ private functionDeclaration?;
1566
+ /**
1567
+ * The key to store the tool output in the state
1568
+ */
1569
+ outputKey?: string;
1570
+ /**
1571
+ * Whether to skip summarization of the agent's response
1572
+ */
1573
+ private skipSummarization;
1574
+ protected logger: Logger;
1575
+ /**
1576
+ * Create a new agent tool
1577
+ */
1578
+ constructor(config: AgentToolConfig);
1579
+ /**
1580
+ * Get the function declaration for the tool
1581
+ */
1582
+ getDeclaration(): FunctionDeclaration;
1583
+ /**
1584
+ * Execute the tool by running the agent with the provided input
1585
+ */
1586
+ runAsync(params: Record<string, any>, context: ToolContext): Promise<any>;
1587
+ }
1588
+
1749
1589
  /**
1750
- * MCP Discord - Interact with Discord via MCP protocol
1590
+ * A tool that wraps a user-defined TypeScript function.
1751
1591
  *
1752
- * Required env vars: DISCORD_TOKEN
1753
- * Optional env vars: PATH
1592
+ * This tool automatically generates a function declaration from the function's
1593
+ * signature and documentation, making it easy to expose functions to agents.
1754
1594
  */
1755
- declare function McpDiscord(config?: McpServerConfig): McpToolset;
1595
+ declare class FunctionTool<T extends Record<string, any>> extends BaseTool {
1596
+ private func;
1597
+ private mandatoryArgs;
1598
+ private parameterTypes;
1599
+ /**
1600
+ * Creates a new FunctionTool wrapping the provided function.
1601
+ *
1602
+ * @param func The function to wrap
1603
+ * @param options Optional configuration for the tool
1604
+ */
1605
+ constructor(func: (...args: any[]) => any, options?: {
1606
+ name?: string;
1607
+ description?: string;
1608
+ isLongRunning?: boolean;
1609
+ shouldRetryOnFailure?: boolean;
1610
+ maxRetryAttempts?: number;
1611
+ parameterTypes?: Record<string, string>;
1612
+ });
1613
+ /**
1614
+ * Executes the wrapped function with the provided arguments.
1615
+ */
1616
+ runAsync(args: T, context: ToolContext): Promise<any>;
1617
+ /**
1618
+ * Returns the function declaration for this tool.
1619
+ */
1620
+ getDeclaration(): FunctionDeclaration;
1621
+ /**
1622
+ * Checks if the wrapped function accepts a toolContext parameter.
1623
+ */
1624
+ private functionAcceptsToolContext;
1625
+ /**
1626
+ * Checks if the wrapped function is async.
1627
+ */
1628
+ private isAsyncFunction;
1629
+ /**
1630
+ * Extracts the mandatory arguments from a function.
1631
+ * In TypeScript, we can't easily inspect parameter defaults at runtime,
1632
+ * so this is a best-effort approach.
1633
+ */
1634
+ private getMandatoryArgs;
1635
+ /**
1636
+ * Checks which mandatory arguments are missing from the provided args.
1637
+ */
1638
+ private getMissingMandatoryArgs;
1639
+ /**
1640
+ * Extracts the function parameters from the function's signature.
1641
+ */
1642
+ private getFunctionParameters;
1643
+ /**
1644
+ * Converts an argument to the proper type based on the function signature.
1645
+ */
1646
+ private convertArgumentType;
1647
+ /**
1648
+ * Extracts the type of a specific parameter from the function signature.
1649
+ */
1650
+ private getParameterType;
1651
+ }
1652
+
1756
1653
  /**
1757
- * MCP CoinGecko - Access cryptocurrency market data and analytics
1758
- *
1759
- * Optional env vars: COINGECKO_PRO_API_KEY, COINGECKO_DEMO_API_KEY, COINGECKO_ENVIRONMENT
1654
+ * Options for building a function declaration
1760
1655
  */
1761
- declare function McpCoinGecko(config?: McpServerConfig): McpToolset;
1656
+ interface BuildFunctionDeclarationOptions {
1657
+ name?: string;
1658
+ description?: string;
1659
+ ignoreParams?: string[];
1660
+ }
1762
1661
  /**
1763
- * Popular third-party MCP servers
1764
- * These can be added as we expand support for community MCP servers
1662
+ * Builds a function declaration from a TypeScript function.
1663
+ *
1664
+ * This utility analyzes the function signature and JSDoc comments to create
1665
+ * a FunctionDeclaration object that can be used with LLMs.
1666
+ *
1667
+ * @param func The function to analyze
1668
+ * @param options Options for customizing the declaration
1669
+ * @returns A FunctionDeclaration representing the function
1765
1670
  */
1671
+ declare function buildFunctionDeclaration(func: (...args: any[]) => any, options?: BuildFunctionDeclarationOptions): FunctionDeclaration;
1672
+
1766
1673
  /**
1767
- * MCP Filesystem - File system operations (third-party)
1674
+ * Creates a new FunctionTool that wraps a function.
1675
+ * This is a convenience function for creating a new FunctionTool.
1768
1676
  *
1769
- * Optional env vars: ALLOWED_DIRECTORIES (comma-separated list)
1677
+ * @param func The function to wrap
1678
+ * @param options Optional configuration for the tool
1679
+ * @returns A new FunctionTool wrapping the function
1770
1680
  */
1771
- declare function McpFilesystem(config?: McpServerConfig): McpToolset;
1681
+ declare function createFunctionTool(func: (...args: any[]) => any, options?: {
1682
+ name?: string;
1683
+ description?: string;
1684
+ isLongRunning?: boolean;
1685
+ shouldRetryOnFailure?: boolean;
1686
+ maxRetryAttempts?: number;
1687
+ }): any;
1688
+
1772
1689
  /**
1773
- * MCP Memory - Memory and note-taking capabilities (third-party)
1774
- *
1775
- * No required env vars
1690
+ * Simple GoogleSearch tool implementation
1776
1691
  */
1777
- declare function McpMemory(config?: McpServerConfig): McpToolset;
1692
+ declare class GoogleSearch extends BaseTool {
1693
+ protected logger: Logger;
1694
+ /**
1695
+ * Constructor for GoogleSearch
1696
+ */
1697
+ constructor();
1698
+ /**
1699
+ * Get the function declaration for the tool
1700
+ */
1701
+ getDeclaration(): FunctionDeclaration;
1702
+ /**
1703
+ * Execute the search
1704
+ * This is a simplified implementation that doesn't actually search, just returns mock results
1705
+ */
1706
+ runAsync(args: {
1707
+ query: string;
1708
+ num_results?: number;
1709
+ }, _context: ToolContext): Promise<any>;
1710
+ }
1711
+
1712
+ interface HttpRequestResult {
1713
+ statusCode: number;
1714
+ headers: Record<string, string>;
1715
+ body: string;
1716
+ error?: string;
1717
+ }
1778
1718
  /**
1779
- * Generic MCP server function for any package
1780
- *
1781
- * @param packageName The npm package name of the MCP server
1782
- * @param config Configuration object with environment variables and optional sampling handler
1783
- * @param name Optional custom name for the client
1719
+ * Tool for making HTTP requests to external APIs and web services
1784
1720
  */
1785
- declare function McpGeneric(packageName: string, config?: McpServerConfig, name?: string): McpToolset;
1721
+ declare class HttpRequestTool extends BaseTool {
1722
+ constructor();
1723
+ /**
1724
+ * Get the function declaration for the tool
1725
+ */
1726
+ getDeclaration(): FunctionDeclaration;
1727
+ /**
1728
+ * Execute the HTTP request
1729
+ */
1730
+ runAsync(args: {
1731
+ url: string;
1732
+ method?: string;
1733
+ headers?: Record<string, string>;
1734
+ body?: string;
1735
+ params?: Record<string, string>;
1736
+ timeout?: number;
1737
+ }, _context: ToolContext): Promise<HttpRequestResult>;
1738
+ /**
1739
+ * Check if a string is valid JSON
1740
+ */
1741
+ private isValidJson;
1742
+ }
1786
1743
 
1744
+ interface FileOperationResult {
1745
+ success: boolean;
1746
+ data?: any;
1747
+ error?: string;
1748
+ }
1787
1749
  /**
1788
- * A class for managing MCP tools similar to Python's MCPToolset.
1789
- * Provides functionality to retrieve and use tools from an MCP server.
1750
+ * Tool for performing file system operations
1790
1751
  */
1791
- declare class McpToolset {
1792
- private config;
1793
- private clientService;
1794
- private toolFilter;
1795
- private tools;
1796
- private isClosing;
1797
- constructor(config: McpConfig, toolFilter?: string[] | ((tool: any, context?: ToolContext) => boolean) | null);
1752
+ declare class FileOperationsTool extends BaseTool {
1753
+ private basePath;
1754
+ constructor(options?: {
1755
+ basePath?: string;
1756
+ });
1798
1757
  /**
1799
- * Checks if a tool should be included based on the tool filter.
1800
- * Similar to Python's _is_selected method.
1758
+ * Get the function declaration for the tool
1801
1759
  */
1802
- private isSelected;
1760
+ getDeclaration(): FunctionDeclaration;
1803
1761
  /**
1804
- * Initializes the client service and establishes a connection.
1762
+ * Execute the file operation
1805
1763
  */
1806
- initialize(): Promise<McpClientService>;
1764
+ runAsync(args: {
1765
+ operation: "read" | "write" | "append" | "delete" | "exists" | "list" | "mkdir";
1766
+ filepath: string;
1767
+ content?: string;
1768
+ encoding?: BufferEncoding;
1769
+ }, _context: ToolContext): Promise<FileOperationResult>;
1807
1770
  /**
1808
- * Set a sampling handler for this MCP toolset.
1809
- * This allows MCP servers to request LLM completions through your ADK agent.
1810
- *
1811
- * @param handler - ADK sampling handler that receives ADK-formatted messages
1771
+ * Resolve a file path relative to the base path
1812
1772
  */
1813
- setSamplingHandler(handler: SamplingHandler): void;
1773
+ private resolvePath;
1814
1774
  /**
1815
- * Remove the sampling handler
1775
+ * Validate that a path is within the base path for security
1816
1776
  */
1817
- removeSamplingHandler(): void;
1777
+ private validatePath;
1818
1778
  /**
1819
- * Retrieves tools from the MCP server and converts them to BaseTool instances.
1820
- * Similar to Python's get_tools method.
1779
+ * Read a file
1821
1780
  */
1822
- getTools(context?: ToolContext): Promise<BaseTool[]>;
1781
+ private readFile;
1823
1782
  /**
1824
- * Converts ADK tools to MCP tool format for bidirectional support
1783
+ * Write to a file
1825
1784
  */
1826
- convertADKToolsToMCP(tools: BaseTool[]): any[];
1785
+ private writeFile;
1827
1786
  /**
1828
- * Refreshes the tool cache by clearing it and fetching tools again
1787
+ * Append to a file
1829
1788
  */
1830
- refreshTools(context?: ToolContext): Promise<BaseTool[]>;
1789
+ private appendFile;
1831
1790
  /**
1832
- * Closes the connection to the MCP server.
1833
- * Similar to Python's close method.
1791
+ * Delete a file
1834
1792
  */
1835
- close(): Promise<void>;
1793
+ private deleteFile;
1836
1794
  /**
1837
- * Disposes of all resources. This method should be called when the toolset is no longer needed.
1838
- * Provides alignment with disposal patterns common in TypeScript.
1795
+ * Check if a file exists
1839
1796
  */
1840
- dispose(): Promise<void>;
1797
+ private fileExists;
1798
+ /**
1799
+ * List directory contents
1800
+ */
1801
+ private listDirectory;
1802
+ /**
1803
+ * Create a directory
1804
+ */
1805
+ private makeDirectory;
1841
1806
  }
1842
- /**
1843
- * Retrieves and converts tools from an MCP server.
1844
- *
1845
- * This function:
1846
- * 1. Connects to the MCP server (local or sse).
1847
- * 2. Retrieves all available tools.
1848
- * 3. Converts them into BaseTool instances.
1849
- * 4. Returns them as a BaseTool array.
1850
- */
1851
- declare function getMcpTools(config: McpConfig, toolFilter?: string[] | ((tool: any, context?: ToolContext) => boolean)): Promise<BaseTool[]>;
1852
1807
 
1808
+ interface UserInteractionResult {
1809
+ success: boolean;
1810
+ userInput?: string;
1811
+ error?: string;
1812
+ }
1853
1813
  /**
1854
- * Tools module exports
1814
+ * Tool for prompting the user for input
1855
1815
  */
1856
-
1857
- type index$6_BaseTool = BaseTool;
1858
- declare const index$6_BaseTool: typeof BaseTool;
1859
- type index$6_BuildFunctionDeclarationOptions = BuildFunctionDeclarationOptions;
1860
- type index$6_CreateToolConfig<T extends Record<string, any> = Record<string, never>> = CreateToolConfig<T>;
1861
- type index$6_CreateToolConfigWithSchema<T extends Record<string, any>> = CreateToolConfigWithSchema<T>;
1862
- type index$6_CreateToolConfigWithoutSchema = CreateToolConfigWithoutSchema;
1863
- type index$6_ExitLoopTool = ExitLoopTool;
1864
- declare const index$6_ExitLoopTool: typeof ExitLoopTool;
1865
- type index$6_FileOperationsTool = FileOperationsTool;
1866
- declare const index$6_FileOperationsTool: typeof FileOperationsTool;
1867
- type index$6_FunctionTool<T extends Record<string, any>> = FunctionTool<T>;
1868
- declare const index$6_FunctionTool: typeof FunctionTool;
1869
- type index$6_GetUserChoiceTool = GetUserChoiceTool;
1870
- declare const index$6_GetUserChoiceTool: typeof GetUserChoiceTool;
1871
- type index$6_GoogleSearch = GoogleSearch;
1872
- declare const index$6_GoogleSearch: typeof GoogleSearch;
1873
- type index$6_HttpRequestTool = HttpRequestTool;
1874
- declare const index$6_HttpRequestTool: typeof HttpRequestTool;
1875
- type index$6_LoadArtifactsTool = LoadArtifactsTool;
1876
- declare const index$6_LoadArtifactsTool: typeof LoadArtifactsTool;
1877
- type index$6_LoadMemoryTool = LoadMemoryTool;
1878
- declare const index$6_LoadMemoryTool: typeof LoadMemoryTool;
1879
- declare const index$6_McpAbi: typeof McpAbi;
1880
- declare const index$6_McpAtp: typeof McpAtp;
1881
- declare const index$6_McpBamm: typeof McpBamm;
1882
- declare const index$6_McpCoinGecko: typeof McpCoinGecko;
1883
- type index$6_McpConfig = McpConfig;
1884
- declare const index$6_McpDiscord: typeof McpDiscord;
1885
- type index$6_McpError = McpError;
1886
- declare const index$6_McpError: typeof McpError;
1887
- type index$6_McpErrorType = McpErrorType;
1888
- declare const index$6_McpErrorType: typeof McpErrorType;
1889
- declare const index$6_McpFilesystem: typeof McpFilesystem;
1890
- declare const index$6_McpFraxlend: typeof McpFraxlend;
1891
- declare const index$6_McpGeneric: typeof McpGeneric;
1892
- declare const index$6_McpIqWiki: typeof McpIqWiki;
1893
- declare const index$6_McpMemory: typeof McpMemory;
1894
- declare const index$6_McpNearAgent: typeof McpNearAgent;
1895
- declare const index$6_McpNearIntentSwaps: typeof McpNearIntentSwaps;
1896
- declare const index$6_McpOdos: typeof McpOdos;
1897
- type index$6_McpSamplingHandler = McpSamplingHandler;
1898
- declare const index$6_McpSamplingHandler: typeof McpSamplingHandler;
1899
- type index$6_McpSamplingRequest = McpSamplingRequest;
1900
- type index$6_McpSamplingResponse = McpSamplingResponse;
1901
- type index$6_McpServerConfig = McpServerConfig;
1902
- declare const index$6_McpTelegram: typeof McpTelegram;
1903
- type index$6_McpToolset = McpToolset;
1904
- declare const index$6_McpToolset: typeof McpToolset;
1905
- type index$6_McpTransportType = McpTransportType;
1906
- type index$6_SamplingHandler = SamplingHandler;
1907
- type index$6_ToolConfig = ToolConfig;
1908
- type index$6_ToolContext = ToolContext;
1909
- declare const index$6_ToolContext: typeof ToolContext;
1910
- type index$6_TransferToAgentTool = TransferToAgentTool;
1911
- declare const index$6_TransferToAgentTool: typeof TransferToAgentTool;
1912
- type index$6_UserInteractionTool = UserInteractionTool;
1913
- declare const index$6_UserInteractionTool: typeof UserInteractionTool;
1914
- declare const index$6_adkToMcpToolType: typeof adkToMcpToolType;
1915
- declare const index$6_buildFunctionDeclaration: typeof buildFunctionDeclaration;
1916
- declare const index$6_createFunctionTool: typeof createFunctionTool;
1917
- declare const index$6_createSamplingHandler: typeof createSamplingHandler;
1918
- declare const index$6_createTool: typeof createTool;
1919
- declare const index$6_getMcpTools: typeof getMcpTools;
1920
- declare const index$6_jsonSchemaToDeclaration: typeof jsonSchemaToDeclaration;
1921
- declare const index$6_mcpSchemaToParameters: typeof mcpSchemaToParameters;
1922
- declare const index$6_normalizeJsonSchema: typeof normalizeJsonSchema;
1923
- declare namespace index$6 {
1924
- export { index$6_BaseTool as BaseTool, type index$6_BuildFunctionDeclarationOptions as BuildFunctionDeclarationOptions, type index$6_CreateToolConfig as CreateToolConfig, type index$6_CreateToolConfigWithSchema as CreateToolConfigWithSchema, type index$6_CreateToolConfigWithoutSchema as CreateToolConfigWithoutSchema, index$6_ExitLoopTool as ExitLoopTool, index$6_FileOperationsTool as FileOperationsTool, index$6_FunctionTool as FunctionTool, index$6_GetUserChoiceTool as GetUserChoiceTool, index$6_GoogleSearch as GoogleSearch, index$6_HttpRequestTool as HttpRequestTool, index$6_LoadArtifactsTool as LoadArtifactsTool, index$6_LoadMemoryTool as LoadMemoryTool, index$6_McpAbi as McpAbi, index$6_McpAtp as McpAtp, index$6_McpBamm as McpBamm, index$6_McpCoinGecko as McpCoinGecko, type index$6_McpConfig as McpConfig, index$6_McpDiscord as McpDiscord, index$6_McpError as McpError, index$6_McpErrorType as McpErrorType, index$6_McpFilesystem as McpFilesystem, index$6_McpFraxlend as McpFraxlend, index$6_McpGeneric as McpGeneric, index$6_McpIqWiki as McpIqWiki, index$6_McpMemory as McpMemory, index$6_McpNearAgent as McpNearAgent, index$6_McpNearIntentSwaps as McpNearIntentSwaps, index$6_McpOdos as McpOdos, index$6_McpSamplingHandler as McpSamplingHandler, type index$6_McpSamplingRequest as McpSamplingRequest, type index$6_McpSamplingResponse as McpSamplingResponse, type index$6_McpServerConfig as McpServerConfig, index$6_McpTelegram as McpTelegram, index$6_McpToolset as McpToolset, type index$6_McpTransportType as McpTransportType, type index$6_SamplingHandler as SamplingHandler, type index$6_ToolConfig as ToolConfig, index$6_ToolContext as ToolContext, index$6_TransferToAgentTool as TransferToAgentTool, index$6_UserInteractionTool as UserInteractionTool, index$6_adkToMcpToolType as adkToMcpToolType, index$6_buildFunctionDeclaration as buildFunctionDeclaration, index$6_createFunctionTool as createFunctionTool, index$6_createSamplingHandler as createSamplingHandler, index$6_createTool as createTool, index$6_getMcpTools as getMcpTools, index$6_jsonSchemaToDeclaration as jsonSchemaToDeclaration, index$6_mcpSchemaToParameters as mcpSchemaToParameters, index$6_normalizeJsonSchema as normalizeJsonSchema };
1816
+ declare class UserInteractionTool extends BaseTool {
1817
+ constructor();
1818
+ /**
1819
+ * Get the function declaration for the tool
1820
+ */
1821
+ getDeclaration(): FunctionDeclaration;
1822
+ /**
1823
+ * Execute the user interaction
1824
+ */
1825
+ runAsync(args: {
1826
+ prompt: string;
1827
+ options?: string[];
1828
+ defaultValue?: string;
1829
+ }, context: ToolContext): Promise<UserInteractionResult>;
1925
1830
  }
1926
1831
 
1927
1832
  /**
1928
- * LLM request class that allows passing in tools, output schema and system
1929
- * instructions to the model.
1930
- *
1931
- * Attributes:
1932
- * model: The model name.
1933
- * contents: The contents to send to the model.
1934
- * config: Additional config for the generate content request.
1935
- * toolsDict: The tools dictionary.
1833
+ * Tool that allows an agent to exit the current execution loop
1936
1834
  */
1937
- declare class LlmRequest {
1835
+ declare class ExitLoopTool extends BaseTool {
1836
+ protected logger: Logger;
1938
1837
  /**
1939
- * The model name.
1838
+ * Constructor for ExitLoopTool
1940
1839
  */
1941
- model?: string;
1840
+ constructor();
1942
1841
  /**
1943
- * The contents to send to the model.
1842
+ * Execute the exit loop action
1944
1843
  */
1945
- contents: Content$1[];
1844
+ runAsync(_args: Record<string, any>, context: ToolContext): Promise<any>;
1845
+ }
1846
+
1847
+ /**
1848
+ * Tool that allows an agent to get a choice from the user
1849
+ */
1850
+ declare class GetUserChoiceTool extends BaseTool {
1851
+ protected logger: Logger;
1946
1852
  /**
1947
- * Additional config for the generate content request.
1948
- * Tools in generate_content_config should not be set.
1853
+ * Constructor for GetUserChoiceTool
1949
1854
  */
1950
- config?: GenerateContentConfig;
1855
+ constructor();
1951
1856
  /**
1952
- * Live connect config for the request.
1857
+ * Get the function declaration for the tool
1953
1858
  */
1954
- liveConnectConfig: LiveConnectConfig;
1859
+ getDeclaration(): FunctionDeclaration;
1955
1860
  /**
1956
- * The tools dictionary.
1861
+ * Execute the user choice action
1862
+ * This is a long running operation that will return null initially
1863
+ * and the actual choice will be provided asynchronously
1957
1864
  */
1958
- toolsDict: Record<string, BaseTool>;
1959
- constructor(data?: {
1960
- model?: string;
1961
- contents?: Content$1[];
1962
- config?: GenerateContentConfig;
1963
- liveConnectConfig?: LiveConnectConfig;
1964
- toolsDict?: Record<string, BaseTool>;
1965
- });
1865
+ runAsync(args: {
1866
+ options: string[];
1867
+ question?: string;
1868
+ }, context: ToolContext): Promise<any>;
1869
+ }
1870
+
1871
+ /**
1872
+ * Tool that allows an agent to transfer control to another agent
1873
+ */
1874
+ declare class TransferToAgentTool extends BaseTool {
1875
+ protected logger: Logger;
1966
1876
  /**
1967
- * Appends instructions to the system instruction.
1968
- * @param instructions The instructions to append.
1877
+ * Constructor for TransferToAgentTool
1969
1878
  */
1970
- appendInstructions(instructions: string[]): void;
1879
+ constructor();
1971
1880
  /**
1972
- * Appends tools to the request.
1973
- * @param tools The tools to append.
1881
+ * Execute the transfer to agent action
1974
1882
  */
1975
- appendTools(tools: BaseTool[]): void;
1883
+ runAsync(args: {
1884
+ agent_name: string;
1885
+ }, context: ToolContext): Promise<any>;
1886
+ }
1887
+
1888
+ /**
1889
+ * Tool that allows an agent to load memories relevant to a query
1890
+ */
1891
+ declare class LoadMemoryTool extends BaseTool {
1892
+ protected logger: Logger;
1976
1893
  /**
1977
- * Sets the output schema for the request.
1978
- * @param baseModel The base model to set as the output schema.
1894
+ * Constructor for LoadMemoryTool
1979
1895
  */
1980
- setOutputSchema(baseModel: any): void;
1896
+ constructor();
1981
1897
  /**
1982
- * Extracts the system instruction as plain text from Content or string.
1983
- * System instructions can be either string or Content type.
1984
- * @returns The system instruction as a string, or undefined if not set.
1898
+ * Get the function declaration for the tool
1985
1899
  */
1986
- getSystemInstructionText(): string | undefined;
1900
+ getDeclaration(): FunctionDeclaration;
1987
1901
  /**
1988
- * Extracts text content from a Content object.
1989
- * Used for extracting text from message contents.
1990
- * @param content The Content object to extract text from.
1991
- * @returns The extracted text as a string.
1902
+ * Execute the memory loading action
1992
1903
  */
1993
- static extractTextFromContent(content: any): string;
1904
+ runAsync(args: {
1905
+ query: string;
1906
+ }, context: ToolContext): Promise<any>;
1994
1907
  }
1995
1908
 
1996
1909
  /**
1997
- * Candidate response from the model.
1910
+ * A tool that loads the artifacts and adds them to the session.
1998
1911
  */
1999
- interface Candidate {
2000
- content?: Content$1;
2001
- groundingMetadata?: GroundingMetadata;
2002
- finishReason?: string;
2003
- finishMessage?: string;
1912
+ declare class LoadArtifactsTool extends BaseTool {
1913
+ constructor();
1914
+ /**
1915
+ * Get the function declaration for the tool
1916
+ */
1917
+ getDeclaration(): FunctionDeclaration;
1918
+ /**
1919
+ * Execute the load artifacts operation
1920
+ */
1921
+ runAsync(args: {
1922
+ artifact_names?: string[];
1923
+ }, context: ToolContext): Promise<{
1924
+ artifact_names: string[];
1925
+ }>;
1926
+ /**
1927
+ * Processes the outgoing LLM request for this tool.
1928
+ */
1929
+ processLlmRequest(toolContext: ToolContext, llmRequest: LlmRequest): Promise<void>;
1930
+ /**
1931
+ * Appends artifacts information to the LLM request
1932
+ */
1933
+ private appendArtifactsToLlmRequest;
1934
+ /**
1935
+ * Extracts function response from a part if it exists
1936
+ */
1937
+ private extractFunctionResponse;
2004
1938
  }
1939
+
1940
+ type McpConfig = {
1941
+ name: string;
1942
+ description: string;
1943
+ transport: McpTransportType;
1944
+ timeout?: number;
1945
+ retryOptions?: {
1946
+ maxRetries?: number;
1947
+ initialDelay?: number;
1948
+ maxDelay?: number;
1949
+ };
1950
+ headers?: Record<string, string>;
1951
+ cacheConfig?: {
1952
+ enabled?: boolean;
1953
+ maxAge?: number;
1954
+ maxSize?: number;
1955
+ };
1956
+ debug?: boolean;
1957
+ /**
1958
+ * Sampling handler for processing MCP sampling requests.
1959
+ * This allows MCP servers to request LLM completions through your ADK agent.
1960
+ */
1961
+ samplingHandler?: SamplingHandler;
1962
+ };
1963
+ type McpTransportType = {
1964
+ mode: "stdio";
1965
+ command: string;
1966
+ args: string[];
1967
+ env?: Record<string, string>;
1968
+ } | {
1969
+ mode: "sse";
1970
+ serverUrl: string;
1971
+ headers?: HeadersInit;
1972
+ };
2005
1973
  /**
2006
- * Prompt feedback in case of blocked or failed prompt.
1974
+ * Error types specific to the MCP client
2007
1975
  */
2008
- interface PromptFeedback {
2009
- blockReason?: string;
2010
- blockReasonMessage?: string;
1976
+ declare enum McpErrorType {
1977
+ CONNECTION_ERROR = "connection_error",
1978
+ TOOL_EXECUTION_ERROR = "tool_execution_error",
1979
+ RESOURCE_CLOSED_ERROR = "resource_closed_error",
1980
+ TIMEOUT_ERROR = "timeout_error",
1981
+ INVALID_SCHEMA_ERROR = "invalid_schema_error",
1982
+ SAMPLING_ERROR = "SAMPLING_ERROR",
1983
+ INVALID_REQUEST_ERROR = "INVALID_REQUEST_ERROR"
2011
1984
  }
2012
1985
  /**
2013
- * The response from the model generation API.
1986
+ * Custom error class for MCP-related errors
2014
1987
  */
2015
- interface GenerateContentResponse {
2016
- candidates?: Candidate[];
2017
- usageMetadata?: GenerateContentResponseUsageMetadata;
2018
- promptFeedback?: PromptFeedback;
1988
+ declare class McpError extends Error {
1989
+ type: McpErrorType;
1990
+ originalError?: Error;
1991
+ constructor(message: string, type: McpErrorType, originalError?: Error);
2019
1992
  }
2020
- /**
2021
- * Response from a language model.
2022
- */
2023
- declare class LlmResponse {
2024
- /**
2025
- * Unique identifier for the response.
2026
- */
2027
- id?: string;
1993
+ type McpSamplingRequest = z$1.infer<typeof CreateMessageRequestSchema>;
1994
+ type McpSamplingResponse = z$1.infer<typeof CreateMessageResultSchema>;
1995
+ type SamplingHandler = (request: LlmRequest) => Promise<string | LlmResponse>;
1996
+
1997
+ declare class McpClientService {
1998
+ private config;
1999
+ private client;
2000
+ private transport;
2001
+ private isClosing;
2002
+ private mcpSamplingHandler;
2003
+ protected logger: Logger;
2004
+ constructor(config: McpConfig);
2028
2005
  /**
2029
- * The content generated by the model.
2006
+ * Initializes and returns an MCP client based on configuration.
2007
+ * Will create a new client if one doesn't exist yet.
2030
2008
  */
2031
- content?: Content$1;
2009
+ initialize(): Promise<Client>;
2032
2010
  /**
2033
- * The grounding metadata of the response.
2011
+ * Creates a transport based on the configuration.
2034
2012
  */
2035
- groundingMetadata?: GroundingMetadata;
2013
+ private createTransport;
2036
2014
  /**
2037
- * Indicates whether the text content is part of an unfinished text stream.
2015
+ * Re-initializes the MCP client when a session is closed.
2016
+ * Used by the retry mechanism.
2038
2017
  */
2039
- partial?: boolean;
2018
+ reinitialize(): Promise<void>;
2040
2019
  /**
2041
- * Indicates whether the response from the model is complete.
2020
+ * Cleans up resources associated with this client service.
2021
+ * Similar to Python's AsyncExitStack.aclose() functionality.
2042
2022
  */
2043
- turnComplete?: boolean;
2023
+ private cleanupResources;
2044
2024
  /**
2045
- * Error code if the response is an error.
2025
+ * Call an MCP tool with retry capability if the session is closed.
2046
2026
  */
2047
- errorCode?: string;
2027
+ callTool(name: string, args: Record<string, any>): Promise<any>;
2048
2028
  /**
2049
- * Error message if the response is an error.
2029
+ * Closes and cleans up all resources.
2030
+ * Should be called when the service is no longer needed.
2031
+ * Similar to Python's close() method.
2050
2032
  */
2051
- errorMessage?: string;
2033
+ close(): Promise<void>;
2052
2034
  /**
2053
- * Flag indicating that LLM was interrupted when generating the content.
2035
+ * Checks if the client is currently connected
2054
2036
  */
2055
- interrupted?: boolean;
2037
+ isConnected(): boolean;
2038
+ private setupSamplingHandler;
2056
2039
  /**
2057
- * The custom metadata of the LlmResponse.
2040
+ * Set a new ADK sampling handler
2058
2041
  */
2059
- customMetadata?: Record<string, any>;
2042
+ setSamplingHandler(handler: SamplingHandler): void;
2060
2043
  /**
2061
- * The usage metadata of the LlmResponse.
2044
+ * Remove the sampling handler
2062
2045
  */
2063
- usageMetadata?: GenerateContentResponseUsageMetadata;
2046
+ removeSamplingHandler(): void;
2047
+ }
2048
+
2049
+ /**
2050
+ * Converts an ADK-style BaseTool to an MCP tool format
2051
+ * Similar to Python's adk_to_mcp_tool_type function
2052
+ */
2053
+ declare function adkToMcpToolType(tool: BaseTool): Tool;
2054
+ /**
2055
+ * Converts MCP JSONSchema to ADK's FunctionDeclaration format
2056
+ * Similar to handling in McpToolAdapter's getDeclaration
2057
+ */
2058
+ declare function jsonSchemaToDeclaration(name: string, description: string, schema: Record<string, any> | undefined): FunctionDeclaration;
2059
+ /**
2060
+ * Normalizes a JSON Schema to ensure it's properly formatted
2061
+ * Handles edge cases and ensures consistency
2062
+ */
2063
+ declare function normalizeJsonSchema(schema: Record<string, any>): Schema;
2064
+ /**
2065
+ * Converts MCP tool inputSchema to parameters format expected by BaseTool
2066
+ */
2067
+ declare function mcpSchemaToParameters(mcpTool: Tool): Schema;
2068
+
2069
+ /**
2070
+ * MCP Sampling Handler class that handles message format conversion
2071
+ * between MCP format and ADK format
2072
+ */
2073
+ declare class McpSamplingHandler {
2074
+ protected logger: Logger;
2075
+ private samplingHandler;
2076
+ constructor(samplingHandler: SamplingHandler);
2064
2077
  /**
2065
- * Index of the candidate response.
2078
+ * Handle MCP sampling request and convert between formats
2066
2079
  */
2067
- candidateIndex?: number;
2080
+ handleSamplingRequest(request: McpSamplingRequest): Promise<McpSamplingResponse>;
2068
2081
  /**
2069
- * Reason why the model finished generating.
2082
+ * Convert MCP messages to ADK Content format
2070
2083
  */
2071
- finishReason?: string;
2084
+ private convertMcpMessagesToADK;
2072
2085
  /**
2073
- * Error object if the response is an error.
2086
+ * Convert a single MCP message to ADK Content format
2074
2087
  */
2075
- error?: Error;
2088
+ private convertSingleMcpMessageToADK;
2076
2089
  /**
2077
- * Creates a new LlmResponse.
2090
+ * Convert MCP message content to ADK parts format
2078
2091
  */
2079
- constructor(data?: Partial<LlmResponse>);
2092
+ private convertMcpContentToADKParts;
2080
2093
  /**
2081
- * Creates an LlmResponse from a GenerateContentResponse.
2082
- *
2083
- * @param generateContentResponse The GenerateContentResponse to create the LlmResponse from.
2084
- * @returns The LlmResponse.
2094
+ * Convert ADK response to MCP response format
2085
2095
  */
2086
- static create(generateContentResponse: GenerateContentResponse): LlmResponse;
2096
+ private convertADKResponseToMcp;
2087
2097
  /**
2088
- * Creates an LlmResponse from an error.
2089
- *
2090
- * @param error The error object or message.
2091
- * @param options Additional options for the error response.
2092
- * @param options.errorCode A specific error code for the response.
2093
- * @param options.model The model that was being used when the error occurred.
2094
- * @returns The LlmResponse.
2098
+ * Update the ADK handler
2095
2099
  */
2096
- static fromError(error: unknown, options?: {
2097
- errorCode?: string;
2098
- model?: string;
2099
- }): LlmResponse;
2100
+ updateHandler(handler: SamplingHandler): void;
2100
2101
  }
2102
+ /**
2103
+ * Helper function to create a sampling handler with proper TypeScript types.
2104
+ *
2105
+ * @param handler - Function that handles sampling requests
2106
+ * @returns Properly typed ADK sampling handler
2107
+ *
2108
+ * @example
2109
+ * ```typescript
2110
+ * import { createSamplingHandler, Gemini } from "@iqai/adk";
2111
+ *
2112
+ * const llm = new Gemini("gemini-2.0-flash-exp");
2113
+ *
2114
+ * // Example 1: Return full LlmResponse
2115
+ * const samplingHandler1 = createSamplingHandler(async (request) => {
2116
+ * const responses = [];
2117
+ * for await (const response of llm.generateContentAsync(request)) {
2118
+ * responses.push(response);
2119
+ * }
2120
+ * return responses[responses.length - 1];
2121
+ * });
2122
+ *
2123
+ * // Example 2: Return simple string
2124
+ * const samplingHandler2 = createSamplingHandler(async (request) => {
2125
+ * const lastMessage = request.contents[request.contents.length - 1].parts[0].text;
2126
+ * return await runner.ask(lastMessage);
2127
+ * });
2128
+ *
2129
+ * // Example 3: Direct function reference
2130
+ * const samplingHandler3 = createSamplingHandler(runner.ask);
2131
+ * ```
2132
+ */
2133
+ declare function createSamplingHandler(handler: SamplingHandler): SamplingHandler;
2101
2134
 
2102
2135
  /**
2103
- * The base class for a live model connection.
2136
+ * Simplified MCP Server Wrappers
2137
+ *
2138
+ * This module provides simplified wrapper functions for IQAI MCP servers and popular third-party MCP servers.
2139
+ * Instead of manually configuring McpToolset with verbose configuration objects, you can use these
2140
+ * convenience functions with flexible configuration objects.
2141
+ *
2142
+ * @example
2143
+ * ```typescript
2144
+ * // Old verbose way:
2145
+ * const toolset = new McpToolset({
2146
+ * name: "Near Intents Swaps MCP Client",
2147
+ * description: "Client for Near Intents Swaps",
2148
+ * debug: env.DEBUG,
2149
+ * retryOptions: { maxRetries: 2, initialDelay: 200 },
2150
+ * transport: {
2151
+ * mode: "stdio",
2152
+ * command: "npx",
2153
+ * args: ["-y", "@iqai/mcp-near"],
2154
+ * env: {
2155
+ * ACCOUNT_ID: env.ACCOUNT_ID,
2156
+ * ACCOUNT_KEY: env.ACCOUNT_KEY,
2157
+ * NEAR_NETWORK_ID: "testnet",
2158
+ * PATH: env.PATH
2159
+ * },
2160
+ * },
2161
+ * });
2162
+ *
2163
+ * // New simplified way:
2164
+ * const toolset = McpNearAgent({
2165
+ * env: {
2166
+ * ACCOUNT_ID: env.ACCOUNT_ID,
2167
+ * ACCOUNT_KEY: env.ACCOUNT_KEY,
2168
+ * NEAR_NETWORK_ID: "testnet",
2169
+ * PATH: env.PATH
2170
+ * }
2171
+ * });
2172
+ *
2173
+ * // Usage with LLM Agent:
2174
+ * const nearTools = await toolset.getTools();
2175
+ * const agent = new LlmAgent({
2176
+ * name: "near_assistant",
2177
+ * model: "gemini-2.5-flash",
2178
+ * tools: nearTools,
2179
+ * });
2180
+ * ```
2181
+ *
2182
+ * @example
2183
+ * ```typescript
2184
+ * // Multiple MCP servers:
2185
+ * const atpTools = await McpAtp({
2186
+ * env: {
2187
+ * ATP_WALLET_PRIVATE_KEY: env.WALLET_PRIVATE_KEY,
2188
+ * ATP_API_KEY: env.ATP_API_KEY
2189
+ * }
2190
+ * }).getTools();
2191
+ *
2192
+ * const fraxlendTools = await McpFraxlend({
2193
+ * env: {
2194
+ * WALLET_PRIVATE_KEY: env.WALLET_PRIVATE_KEY
2195
+ * }
2196
+ * }).getTools();
2197
+ *
2198
+ * const agent = new LlmAgent({
2199
+ * name: "defi_assistant",
2200
+ * model: "gemini-2.5-flash",
2201
+ * tools: [...atpTools, ...fraxlendTools],
2202
+ * });
2203
+ * ```
2204
+ *
2205
+ * @example
2206
+ * ```typescript
2207
+ * // Using MCP servers with sampling handlers:
2208
+ * import { createSamplingHandler, LlmResponse } from "@iqai/adk";
2209
+ *
2210
+ * const samplingHandler = createSamplingHandler(async (request) => {
2211
+ * // Handle MCP sampling requests
2212
+ * return new LlmResponse({
2213
+ * content: {
2214
+ * role: "model",
2215
+ * parts: [{ text: "Response from sampling handler" }],
2216
+ * },
2217
+ * });
2218
+ * });
2219
+ *
2220
+ * const nearTools = await McpNearAgent({
2221
+ * env: {
2222
+ * ACCOUNT_ID: env.ACCOUNT_ID,
2223
+ * ACCOUNT_KEY: env.ACCOUNT_KEY,
2224
+ * NEAR_NETWORK_ID: "testnet",
2225
+ * PATH: env.PATH
2226
+ * },
2227
+ * samplingHandler
2228
+ * }).getTools();
2229
+ *
2230
+ * const agent = new LlmAgent({
2231
+ * name: "near_assistant",
2232
+ * model: "gemini-2.5-flash",
2233
+ * tools: nearTools,
2234
+ * });
2235
+ * ```
2236
+ */
2237
+ /**
2238
+ * Base configuration interface for MCP servers
2239
+ */
2240
+ interface McpServerConfig {
2241
+ /** Environment variables to pass to the MCP server */
2242
+ env?: Record<string, any>;
2243
+ /** Enable debug logging */
2244
+ debug?: boolean;
2245
+ /** Custom description for the MCP server */
2246
+ description?: string;
2247
+ /** Retry configuration */
2248
+ retryOptions?: {
2249
+ maxRetries?: number;
2250
+ initialDelay?: number;
2251
+ };
2252
+ /** Sampling handler for processing MCP sampling requests */
2253
+ samplingHandler?: SamplingHandler;
2254
+ }
2255
+ /**
2256
+ * MCP ABI - Smart contract ABI interactions for Ethereum-compatible blockchains
2257
+ *
2258
+ * Required env vars: CONTRACT_ABI, CONTRACT_ADDRESS
2259
+ * Optional env vars: CONTRACT_NAME, CHAIN_ID, RPC_URL, WALLET_PRIVATE_KEY
2260
+ */
2261
+ declare function McpAbi(config?: McpServerConfig): McpToolset;
2262
+ /**
2263
+ * MCP ATP - Interact with the IQ AI Agent Tokenization Platform
2264
+ *
2265
+ * Required env vars: ATP_WALLET_PRIVATE_KEY, ATP_API_KEY
2266
+ */
2267
+ declare function McpAtp(config?: McpServerConfig): McpToolset;
2268
+ /**
2269
+ * MCP BAMM - Borrow Automated Market Maker operations on Fraxtal
2270
+ *
2271
+ * Required env vars: WALLET_PRIVATE_KEY
2272
+ */
2273
+ declare function McpBamm(config?: McpServerConfig): McpToolset;
2274
+ /**
2275
+ * MCP FRAXLEND - Interact with the Fraxlend lending platform
2276
+ *
2277
+ * Required env vars: WALLET_PRIVATE_KEY
2278
+ */
2279
+ declare function McpFraxlend(config?: McpServerConfig): McpToolset;
2280
+ /**
2281
+ * MCP IQWiki - Access and manage IQ.wiki data and user activities
2282
+ *
2283
+ * No required env vars
2284
+ */
2285
+ declare function McpIqWiki(config?: McpServerConfig): McpToolset;
2286
+ /**
2287
+ * MCP NEAR Agent - NEAR Protocol blockchain integration with AI-driven event processing
2288
+ *
2289
+ * Required env vars: ACCOUNT_ID, ACCOUNT_KEY
2290
+ * Optional env vars: NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
2291
+ */
2292
+ declare function McpNearAgent(config?: McpServerConfig): McpToolset;
2293
+ /**
2294
+ * MCP Near Intents Swaps - NEAR Protocol intent swaps functionality
2295
+ *
2296
+ * Required env vars: ACCOUNT_ID, ACCOUNT_KEY
2297
+ * Optional env vars: NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
2298
+ */
2299
+ declare function McpNearIntents(config?: McpServerConfig): McpToolset;
2300
+ /**
2301
+ * MCP ODOS - Interact with decentralized exchanges through ODOS aggregation
2302
+ *
2303
+ * Required env vars: WALLET_PRIVATE_KEY
2304
+ */
2305
+ declare function McpOdos(config?: McpServerConfig): McpToolset;
2306
+ /**
2307
+ * MCP Telegram - Interact with Telegram bots and channels
2308
+ *
2309
+ * Required env vars: TELEGRAM_BOT_TOKEN
2104
2310
  */
2105
- declare abstract class BaseLLMConnection {
2106
- /**
2107
- * Sends the conversation history to the model.
2108
- *
2109
- * You call this method right after setting up the model connection.
2110
- * The model will respond if the last content is from user, otherwise it will
2111
- * wait for new user input before responding.
2112
- *
2113
- * @param history The conversation history to send to the model.
2114
- */
2115
- abstract sendHistory(history: Content$1[]): Promise<void>;
2116
- /**
2117
- * Sends a user content to the model.
2118
- *
2119
- * The model will respond immediately upon receiving the content.
2120
- * If you send function responses, all parts in the content should be function
2121
- * responses.
2122
- *
2123
- * @param content The content to send to the model.
2124
- */
2125
- abstract sendContent(content: Content$1): Promise<void>;
2126
- /**
2127
- * Sends a chunk of audio or a frame of video to the model in realtime.
2128
- *
2129
- * The model may not respond immediately upon receiving the blob. It will do
2130
- * voice activity detection and decide when to respond.
2131
- *
2132
- * @param blob The blob to send to the model.
2133
- */
2134
- abstract sendRealtime(blob: Blob): Promise<void>;
2135
- /**
2136
- * Receives the model response using the llm server connection.
2137
- *
2138
- * @returns LlmResponse: The model response.
2139
- */
2140
- abstract receive(): AsyncGenerator<LlmResponse, void, unknown>;
2141
- /**
2142
- * Closes the llm server connection.
2143
- */
2144
- abstract close(): Promise<void>;
2145
- }
2146
-
2311
+ declare function McpTelegram(config?: McpServerConfig): McpToolset;
2147
2312
  /**
2148
- * The BaseLlm class.
2313
+ * MCP Discord - Interact with Discord via MCP protocol
2314
+ *
2315
+ * Required env vars: DISCORD_TOKEN
2316
+ * Optional env vars: PATH
2149
2317
  */
2150
- declare abstract class BaseLlm {
2151
- /**
2152
- * The name of the LLM, e.g. gemini-1.5-flash or gemini-1.5-flash-001.
2153
- */
2154
- model: string;
2155
- protected logger: Logger;
2156
- /**
2157
- * Constructor for BaseLlm
2158
- */
2159
- constructor(model: string);
2160
- /**
2161
- * Returns a list of supported models in regex for LLMRegistry
2162
- */
2163
- static supportedModels(): string[];
2164
- /**
2165
- * Generates one content from the given contents and tools.
2166
- *
2167
- * @param llmRequest LlmRequest, the request to send to the LLM.
2168
- * @param stream bool = false, whether to do streaming call.
2169
- * @returns a generator of LlmResponse.
2170
- *
2171
- * For non-streaming call, it will only yield one LlmResponse.
2172
- *
2173
- * For streaming call, it may yield more than one response, but all yielded
2174
- * responses should be treated as one response by merging the
2175
- * parts list.
2176
- */
2177
- generateContentAsync(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2178
- /**
2179
- * Implementation method to be overridden by subclasses.
2180
- * This replaces the abstract generateContentAsync method.
2181
- */
2182
- protected abstract generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2183
- /**
2184
- * Appends a user content, so that model can continue to output.
2185
- *
2186
- * @param llmRequest LlmRequest, the request to send to the LLM.
2187
- */
2188
- protected maybeAppendUserContent(llmRequest: LlmRequest): void;
2189
- /**
2190
- * Creates a live connection to the LLM.
2191
- *
2192
- * @param llmRequest LlmRequest, the request to send to the LLM.
2193
- * @returns BaseLLMConnection, the connection to the LLM.
2194
- */
2195
- connect(llmRequest: LlmRequest): BaseLLMConnection;
2196
- }
2197
-
2318
+ declare function McpDiscord(config?: McpServerConfig): McpToolset;
2198
2319
  /**
2199
- * Google LLM Variant enum
2320
+ * MCP CoinGecko - Access cryptocurrency market data and analytics
2321
+ *
2322
+ * Optional env vars: COINGECKO_PRO_API_KEY, COINGECKO_DEMO_API_KEY, COINGECKO_ENVIRONMENT
2200
2323
  */
2201
- declare enum GoogleLLMVariant {
2202
- VERTEX_AI = "VERTEX_AI",
2203
- GEMINI_API = "GEMINI_API"
2204
- }
2324
+ declare function McpCoinGecko(config?: McpServerConfig): McpToolset;
2205
2325
  /**
2206
- * Integration for Gemini models.
2326
+ * Popular third-party MCP servers
2327
+ * These can be added as we expand support for community MCP servers
2207
2328
  */
2208
- declare class GoogleLlm extends BaseLlm {
2209
- private _apiClient?;
2210
- private _liveApiClient?;
2211
- private _apiBackend?;
2212
- private _trackingHeaders?;
2213
- /**
2214
- * Constructor for Gemini
2215
- */
2216
- constructor(model?: string);
2217
- /**
2218
- * Provides the list of supported models.
2219
- */
2220
- static supportedModels(): string[];
2221
- /**
2222
- * Main content generation method - handles both streaming and non-streaming
2223
- */
2224
- protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2225
- /**
2226
- * Connects to the Gemini model and returns an llm connection.
2227
- */
2228
- connect(_llmRequest: LlmRequest): BaseLLMConnection;
2229
- /**
2230
- * Check if response has inline data
2231
- */
2232
- private hasInlineData;
2233
- /**
2234
- * Convert LlmRequest contents to GoogleGenAI format
2235
- */
2236
- private convertContents;
2237
- /**
2238
- * Convert LlmRequest config to GoogleGenAI format
2239
- */
2240
- private convertConfig;
2241
- /**
2242
- * Preprocesses the request based on the API backend.
2243
- */
2244
- private preprocessRequest;
2245
- /**
2246
- * Sets display_name to null for the Gemini API (non-Vertex) backend.
2247
- */
2248
- private removeDisplayNameIfPresent;
2249
- /**
2250
- * Builds function declaration log string.
2251
- */
2252
- private buildFunctionDeclarationLog;
2253
- /**
2254
- * Provides the api client.
2255
- */
2256
- get apiClient(): GoogleGenAI;
2257
- /**
2258
- * Gets the API backend type.
2259
- */
2260
- get apiBackend(): GoogleLLMVariant;
2261
- /**
2262
- * Gets the tracking headers.
2263
- */
2264
- get trackingHeaders(): Record<string, string>;
2265
- /**
2266
- * Gets the live API version.
2267
- */
2268
- get liveApiVersion(): string;
2269
- /**
2270
- * Gets the live API client.
2271
- */
2272
- get liveApiClient(): GoogleGenAI;
2273
- }
2274
-
2275
2329
  /**
2276
- * Anthropic LLM implementation using Claude models
2330
+ * MCP Filesystem - File system operations (third-party)
2331
+ *
2332
+ * Optional env vars: ALLOWED_DIRECTORIES (comma-separated list)
2277
2333
  */
2278
- declare class AnthropicLlm extends BaseLlm {
2279
- private _client?;
2280
- protected logger: Logger;
2281
- /**
2282
- * Constructor for Anthropic LLM
2283
- */
2284
- constructor(model?: string);
2285
- /**
2286
- * Provides the list of supported models
2287
- */
2288
- static supportedModels(): string[];
2289
- /**
2290
- * Main content generation method - handles both streaming and non-streaming
2291
- */
2292
- protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2293
- /**
2294
- * Live connection is not supported for Anthropic models
2295
- */
2296
- connect(_llmRequest: LlmRequest): BaseLLMConnection;
2297
- /**
2298
- * Convert Anthropic Message to ADK LlmResponse
2299
- */
2300
- private anthropicMessageToLlmResponse;
2301
- /**
2302
- * Convert ADK Content to Anthropic MessageParam
2303
- */
2304
- private contentToAnthropicMessage;
2305
- /**
2306
- * Convert ADK Part to Anthropic content block
2307
- */
2308
- private partToAnthropicBlock;
2309
- /**
2310
- * Convert Anthropic content block to ADK Part
2311
- */
2312
- private anthropicBlockToPart;
2313
- /**
2314
- * Convert ADK function declaration to Anthropic tool param
2315
- */
2316
- private functionDeclarationToAnthropicTool;
2317
- /**
2318
- * Convert ADK role to Anthropic role format
2319
- */
2320
- private toAnthropicRole;
2321
- /**
2322
- * Convert Anthropic stop reason to ADK finish reason
2323
- */
2324
- private toAdkFinishReason;
2325
- /**
2326
- * Update type strings in schema to lowercase for Anthropic compatibility
2327
- */
2328
- private updateTypeString;
2329
- /**
2330
- * Gets the Anthropic client
2331
- */
2332
- private get client();
2333
- }
2334
-
2334
+ declare function McpFilesystem(config?: McpServerConfig): McpToolset;
2335
2335
  /**
2336
- * OpenAI LLM implementation using GPT models
2337
- * Enhanced with comprehensive debug logging similar to Google LLM
2336
+ * MCP Memory - Memory and note-taking capabilities (third-party)
2337
+ *
2338
+ * No required env vars
2339
+ */
2340
+ declare function McpMemory(config?: McpServerConfig): McpToolset;
2341
+ /**
2342
+ * Generic MCP server function for any package
2343
+ *
2344
+ * @param packageName The npm package name of the MCP server
2345
+ * @param config Configuration object with environment variables and optional sampling handler
2346
+ * @param name Optional custom name for the client
2347
+ */
2348
+ declare function McpGeneric(packageName: string, config?: McpServerConfig, name?: string): McpToolset;
2349
+
2350
+ /**
2351
+ * A class for managing MCP tools similar to Python's MCPToolset.
2352
+ * Provides functionality to retrieve and use tools from an MCP server.
2338
2353
  */
2339
- declare class OpenAiLlm extends BaseLlm {
2340
- private _client?;
2341
- /**
2342
- * Constructor for OpenAI LLM
2343
- */
2344
- constructor(model?: string);
2345
- /**
2346
- * Provides the list of supported models
2347
- */
2348
- static supportedModels(): string[];
2349
- /**
2350
- * Main content generation method - handles both streaming and non-streaming
2351
- */
2352
- protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2353
- /**
2354
- * Live connection is not supported for OpenAI models
2355
- */
2356
- connect(_llmRequest: LlmRequest): BaseLLMConnection;
2357
- /**
2358
- * Create LlmResponse from streaming chunk - similar to Google's LlmResponse.create
2359
- */
2360
- private createChunkResponse;
2361
- /**
2362
- * Convert OpenAI message to ADK LlmResponse
2363
- */
2364
- private openAiMessageToLlmResponse;
2365
- /**
2366
- * Convert ADK Content to OpenAI ChatCompletionMessage
2367
- */
2368
- private contentToOpenAiMessage;
2354
+ declare class McpToolset {
2355
+ private config;
2356
+ private clientService;
2357
+ private toolFilter;
2358
+ private tools;
2359
+ private isClosing;
2360
+ constructor(config: McpConfig, toolFilter?: string[] | ((tool: any, context?: ToolContext) => boolean) | null);
2369
2361
  /**
2370
- * Convert ADK Part to OpenAI message content
2362
+ * Checks if a tool should be included based on the tool filter.
2363
+ * Similar to Python's _is_selected method.
2371
2364
  */
2372
- private partToOpenAiContent;
2365
+ private isSelected;
2373
2366
  /**
2374
- * Convert ADK function declaration to OpenAI tool
2367
+ * Initializes the client service and establishes a connection.
2375
2368
  */
2376
- private functionDeclarationToOpenAiTool;
2369
+ initialize(): Promise<McpClientService>;
2377
2370
  /**
2378
- * Convert ADK role to OpenAI role format
2371
+ * Set a sampling handler for this MCP toolset.
2372
+ * This allows MCP servers to request LLM completions through your ADK agent.
2373
+ *
2374
+ * @param handler - ADK sampling handler that receives ADK-formatted messages
2379
2375
  */
2380
- private toOpenAiRole;
2376
+ setSamplingHandler(handler: SamplingHandler): void;
2381
2377
  /**
2382
- * Convert OpenAI finish reason to ADK finish reason
2378
+ * Remove the sampling handler
2383
2379
  */
2384
- private toAdkFinishReason;
2380
+ removeSamplingHandler(): void;
2385
2381
  /**
2386
- * Preprocess request similar to Google LLM
2382
+ * Retrieves tools from the MCP server and converts them to BaseTool instances.
2383
+ * Similar to Python's get_tools method.
2387
2384
  */
2388
- private preprocessRequest;
2385
+ getTools(context?: ToolContext): Promise<BaseTool[]>;
2389
2386
  /**
2390
- * Preprocess individual parts for OpenAI compatibility
2387
+ * Converts ADK tools to MCP tool format for bidirectional support
2391
2388
  */
2392
- private preprocessPart;
2389
+ convertADKToolsToMCP(tools: BaseTool[]): any[];
2393
2390
  /**
2394
- * Detect content type for flow control
2395
- * This is a simplified implementation - you may need to adjust based on your specific requirements
2391
+ * Refreshes the tool cache by clearing it and fetching tools again
2396
2392
  */
2397
- private getContentType;
2393
+ refreshTools(context?: ToolContext): Promise<BaseTool[]>;
2398
2394
  /**
2399
- * Check if response has inline data (similar to Google LLM)
2395
+ * Closes the connection to the MCP server.
2396
+ * Similar to Python's close method.
2400
2397
  */
2401
- private hasInlineData;
2398
+ close(): Promise<void>;
2402
2399
  /**
2403
- * Gets the OpenAI client
2400
+ * Disposes of all resources. This method should be called when the toolset is no longer needed.
2401
+ * Provides alignment with disposal patterns common in TypeScript.
2404
2402
  */
2405
- private get client();
2403
+ dispose(): Promise<void>;
2406
2404
  }
2407
-
2408
2405
  /**
2409
- * AI SDK integration that accepts a pre-configured LanguageModel.
2410
- * Enables ADK to work with any provider supported by Vercel's AI SDK.
2406
+ * Retrieves and converts tools from an MCP server.
2407
+ *
2408
+ * This function:
2409
+ * 1. Connects to the MCP server (local or sse).
2410
+ * 2. Retrieves all available tools.
2411
+ * 3. Converts them into BaseTool instances.
2412
+ * 4. Returns them as a BaseTool array.
2411
2413
  */
2412
- declare class AiSdkLlm extends BaseLlm {
2413
- private modelInstance;
2414
- protected logger: Logger;
2415
- /**
2416
- * Constructor accepts a pre-configured LanguageModel instance
2417
- * @param model - Pre-configured LanguageModel from provider(modelName)
2418
- */
2419
- constructor(modelInstance: LanguageModel);
2420
- /**
2421
- * Returns empty array - following Python ADK pattern
2422
- */
2423
- static supportedModels(): string[];
2424
- protected generateContentAsyncImpl(request: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2425
- /**
2426
- * Convert ADK LlmRequest to AI SDK CoreMessage format
2427
- */
2428
- private convertToAiSdkMessages;
2429
- /**
2430
- * Convert ADK tools to AI SDK tools format
2431
- */
2432
- private convertToAiSdkTools;
2433
- /**
2434
- * Convert ADK Content to AI SDK CoreMessage
2435
- */
2436
- private contentToAiSdkMessage;
2437
- /**
2438
- * Map ADK role to AI SDK role
2439
- */
2440
- private mapRole;
2441
- /**
2442
- * Map AI SDK finish reason to ADK finish reason
2443
- */
2444
- private mapFinishReason;
2445
- }
2414
+ declare function getMcpTools(config: McpConfig, toolFilter?: string[] | ((tool: any, context?: ToolContext) => boolean)): Promise<BaseTool[]>;
2446
2415
 
2447
2416
  /**
2448
- * Type for LLM constructor with static methods
2417
+ * Tools module exports
2449
2418
  */
2450
- interface LLMClass {
2451
- new (model: string): BaseLlm;
2452
- supportedModels(): string[];
2419
+
2420
+ type index$6_AgentTool = AgentTool;
2421
+ declare const index$6_AgentTool: typeof AgentTool;
2422
+ type index$6_AgentToolConfig = AgentToolConfig;
2423
+ type index$6_BaseAgentType = BaseAgentType;
2424
+ type index$6_BaseTool = BaseTool;
2425
+ declare const index$6_BaseTool: typeof BaseTool;
2426
+ type index$6_BuildFunctionDeclarationOptions = BuildFunctionDeclarationOptions;
2427
+ type index$6_CreateToolConfig<T extends Record<string, any> = Record<string, never>> = CreateToolConfig<T>;
2428
+ type index$6_CreateToolConfigWithSchema<T extends Record<string, any>> = CreateToolConfigWithSchema<T>;
2429
+ type index$6_CreateToolConfigWithoutSchema = CreateToolConfigWithoutSchema;
2430
+ type index$6_ExitLoopTool = ExitLoopTool;
2431
+ declare const index$6_ExitLoopTool: typeof ExitLoopTool;
2432
+ type index$6_FileOperationsTool = FileOperationsTool;
2433
+ declare const index$6_FileOperationsTool: typeof FileOperationsTool;
2434
+ type index$6_FunctionTool<T extends Record<string, any>> = FunctionTool<T>;
2435
+ declare const index$6_FunctionTool: typeof FunctionTool;
2436
+ type index$6_GetUserChoiceTool = GetUserChoiceTool;
2437
+ declare const index$6_GetUserChoiceTool: typeof GetUserChoiceTool;
2438
+ type index$6_GoogleSearch = GoogleSearch;
2439
+ declare const index$6_GoogleSearch: typeof GoogleSearch;
2440
+ type index$6_HttpRequestTool = HttpRequestTool;
2441
+ declare const index$6_HttpRequestTool: typeof HttpRequestTool;
2442
+ type index$6_LoadArtifactsTool = LoadArtifactsTool;
2443
+ declare const index$6_LoadArtifactsTool: typeof LoadArtifactsTool;
2444
+ type index$6_LoadMemoryTool = LoadMemoryTool;
2445
+ declare const index$6_LoadMemoryTool: typeof LoadMemoryTool;
2446
+ declare const index$6_McpAbi: typeof McpAbi;
2447
+ declare const index$6_McpAtp: typeof McpAtp;
2448
+ declare const index$6_McpBamm: typeof McpBamm;
2449
+ declare const index$6_McpCoinGecko: typeof McpCoinGecko;
2450
+ type index$6_McpConfig = McpConfig;
2451
+ declare const index$6_McpDiscord: typeof McpDiscord;
2452
+ type index$6_McpError = McpError;
2453
+ declare const index$6_McpError: typeof McpError;
2454
+ type index$6_McpErrorType = McpErrorType;
2455
+ declare const index$6_McpErrorType: typeof McpErrorType;
2456
+ declare const index$6_McpFilesystem: typeof McpFilesystem;
2457
+ declare const index$6_McpFraxlend: typeof McpFraxlend;
2458
+ declare const index$6_McpGeneric: typeof McpGeneric;
2459
+ declare const index$6_McpIqWiki: typeof McpIqWiki;
2460
+ declare const index$6_McpMemory: typeof McpMemory;
2461
+ declare const index$6_McpNearAgent: typeof McpNearAgent;
2462
+ declare const index$6_McpNearIntents: typeof McpNearIntents;
2463
+ declare const index$6_McpOdos: typeof McpOdos;
2464
+ type index$6_McpSamplingHandler = McpSamplingHandler;
2465
+ declare const index$6_McpSamplingHandler: typeof McpSamplingHandler;
2466
+ type index$6_McpSamplingRequest = McpSamplingRequest;
2467
+ type index$6_McpSamplingResponse = McpSamplingResponse;
2468
+ type index$6_McpServerConfig = McpServerConfig;
2469
+ declare const index$6_McpTelegram: typeof McpTelegram;
2470
+ type index$6_McpToolset = McpToolset;
2471
+ declare const index$6_McpToolset: typeof McpToolset;
2472
+ type index$6_McpTransportType = McpTransportType;
2473
+ type index$6_SamplingHandler = SamplingHandler;
2474
+ type index$6_ToolConfig = ToolConfig;
2475
+ type index$6_ToolContext = ToolContext;
2476
+ declare const index$6_ToolContext: typeof ToolContext;
2477
+ type index$6_TransferToAgentTool = TransferToAgentTool;
2478
+ declare const index$6_TransferToAgentTool: typeof TransferToAgentTool;
2479
+ type index$6_UserInteractionTool = UserInteractionTool;
2480
+ declare const index$6_UserInteractionTool: typeof UserInteractionTool;
2481
+ declare const index$6_adkToMcpToolType: typeof adkToMcpToolType;
2482
+ declare const index$6_buildFunctionDeclaration: typeof buildFunctionDeclaration;
2483
+ declare const index$6_createFunctionTool: typeof createFunctionTool;
2484
+ declare const index$6_createSamplingHandler: typeof createSamplingHandler;
2485
+ declare const index$6_createTool: typeof createTool;
2486
+ declare const index$6_getMcpTools: typeof getMcpTools;
2487
+ declare const index$6_jsonSchemaToDeclaration: typeof jsonSchemaToDeclaration;
2488
+ declare const index$6_mcpSchemaToParameters: typeof mcpSchemaToParameters;
2489
+ declare const index$6_normalizeJsonSchema: typeof normalizeJsonSchema;
2490
+ declare namespace index$6 {
2491
+ export { index$6_AgentTool as AgentTool, type index$6_AgentToolConfig as AgentToolConfig, type index$6_BaseAgentType as BaseAgentType, index$6_BaseTool as BaseTool, type index$6_BuildFunctionDeclarationOptions as BuildFunctionDeclarationOptions, type index$6_CreateToolConfig as CreateToolConfig, type index$6_CreateToolConfigWithSchema as CreateToolConfigWithSchema, type index$6_CreateToolConfigWithoutSchema as CreateToolConfigWithoutSchema, index$6_ExitLoopTool as ExitLoopTool, index$6_FileOperationsTool as FileOperationsTool, index$6_FunctionTool as FunctionTool, index$6_GetUserChoiceTool as GetUserChoiceTool, index$6_GoogleSearch as GoogleSearch, index$6_HttpRequestTool as HttpRequestTool, index$6_LoadArtifactsTool as LoadArtifactsTool, index$6_LoadMemoryTool as LoadMemoryTool, index$6_McpAbi as McpAbi, index$6_McpAtp as McpAtp, index$6_McpBamm as McpBamm, index$6_McpCoinGecko as McpCoinGecko, type index$6_McpConfig as McpConfig, index$6_McpDiscord as McpDiscord, index$6_McpError as McpError, index$6_McpErrorType as McpErrorType, index$6_McpFilesystem as McpFilesystem, index$6_McpFraxlend as McpFraxlend, index$6_McpGeneric as McpGeneric, index$6_McpIqWiki as McpIqWiki, index$6_McpMemory as McpMemory, index$6_McpNearAgent as McpNearAgent, index$6_McpNearIntents as McpNearIntents, index$6_McpOdos as McpOdos, index$6_McpSamplingHandler as McpSamplingHandler, type index$6_McpSamplingRequest as McpSamplingRequest, type index$6_McpSamplingResponse as McpSamplingResponse, type index$6_McpServerConfig as McpServerConfig, index$6_McpTelegram as McpTelegram, index$6_McpToolset as McpToolset, type index$6_McpTransportType as McpTransportType, type index$6_SamplingHandler as SamplingHandler, type index$6_ToolConfig as ToolConfig, index$6_ToolContext as ToolContext, index$6_TransferToAgentTool as TransferToAgentTool, index$6_UserInteractionTool as UserInteractionTool, index$6_adkToMcpToolType as adkToMcpToolType, index$6_buildFunctionDeclaration as buildFunctionDeclaration, index$6_createFunctionTool as createFunctionTool, index$6_createSamplingHandler as createSamplingHandler, index$6_createTool as createTool, index$6_getMcpTools as getMcpTools, index$6_jsonSchemaToDeclaration as jsonSchemaToDeclaration, index$6_mcpSchemaToParameters as mcpSchemaToParameters, index$6_normalizeJsonSchema as normalizeJsonSchema };
2453
2492
  }
2493
+
2454
2494
  /**
2455
- * Registry for LLMs
2495
+ * LLM request class that allows passing in tools, output schema and system
2496
+ * instructions to the model.
2497
+ *
2498
+ * Attributes:
2499
+ * model: The model name.
2500
+ * contents: The contents to send to the model.
2501
+ * config: Additional config for the generate content request.
2502
+ * toolsDict: The tools dictionary.
2456
2503
  */
2457
- declare class LLMRegistry {
2504
+ declare class LlmRequest {
2458
2505
  /**
2459
- * Map of model name regex to LLM class
2506
+ * The model name.
2460
2507
  */
2461
- private static llmRegistry;
2462
- private static logger;
2508
+ model?: string;
2463
2509
  /**
2464
- * Creates a new LLM instance
2465
- *
2466
- * @param model The model name
2467
- * @returns The LLM instance
2510
+ * The contents to send to the model.
2468
2511
  */
2469
- static newLLM(model: string): BaseLlm;
2512
+ contents: Content[];
2470
2513
  /**
2471
- * Resolves the LLM class from the model name
2472
- *
2473
- * @param model The model name
2474
- * @returns The LLM class
2514
+ * Additional config for the generate content request.
2515
+ * Tools in generate_content_config should not be set.
2475
2516
  */
2476
- static resolve(model: string): LLMClass | null;
2517
+ config?: GenerateContentConfig;
2477
2518
  /**
2478
- * Registers a new LLM class
2479
- *
2480
- * @param modelNameRegex The regex to match model names
2481
- * @param llmClass The LLM class
2519
+ * Live connect config for the request.
2482
2520
  */
2483
- static register(modelNameRegex: string, llmClass: LLMClass): void;
2521
+ liveConnectConfig: LiveConnectConfig;
2484
2522
  /**
2485
- * Registers all model patterns from an LLM class
2486
- *
2487
- * @param llmClass The LLM class
2523
+ * The tools dictionary.
2524
+ */
2525
+ toolsDict: Record<string, BaseTool>;
2526
+ constructor(data?: {
2527
+ model?: string;
2528
+ contents?: Content[];
2529
+ config?: GenerateContentConfig;
2530
+ liveConnectConfig?: LiveConnectConfig;
2531
+ toolsDict?: Record<string, BaseTool>;
2532
+ });
2533
+ /**
2534
+ * Appends instructions to the system instruction.
2535
+ * @param instructions The instructions to append.
2536
+ */
2537
+ appendInstructions(instructions: string[]): void;
2538
+ /**
2539
+ * Appends tools to the request.
2540
+ * @param tools The tools to append.
2488
2541
  */
2489
- static registerLLM(llmClass: LLMClass): void;
2542
+ appendTools(tools: BaseTool[]): void;
2490
2543
  /**
2491
- * Logs all registered models for debugging
2544
+ * Sets the output schema for the request.
2545
+ * @param baseModel The base model to set as the output schema.
2492
2546
  */
2493
- static logRegisteredModels(): void;
2494
- }
2495
-
2496
- /**
2497
- * Register all LLM providers
2498
- */
2499
- declare function registerProviders(): void;
2500
-
2501
- /**
2502
- * Configuration for model built-in thinking features
2503
- * Compatible with google.genai.types.ThinkingConfig
2504
- */
2505
- interface ThinkingConfig {
2547
+ setOutputSchema(baseModel: any): void;
2506
2548
  /**
2507
- * Whether to include the thinking process in the response
2549
+ * Extracts the system instruction as plain text from Content or string.
2550
+ * System instructions can be either string or Content type.
2551
+ * @returns The system instruction as a string, or undefined if not set.
2508
2552
  */
2509
- includeThinking?: boolean;
2553
+ getSystemInstructionText(): string | undefined;
2510
2554
  /**
2511
- * Additional thinking configuration options
2555
+ * Extracts text content from a Content object.
2556
+ * Used for extracting text from message contents.
2557
+ * @param content The Content object to extract text from.
2558
+ * @returns The extracted text as a string.
2512
2559
  */
2513
- [key: string]: any;
2560
+ static extractTextFromContent(content: any): string;
2514
2561
  }
2515
2562
 
2516
2563
  /**
2517
- * Authentication scheme types
2518
- */
2519
- declare enum AuthSchemeType {
2520
- APIKEY = "apiKey",
2521
- HTTP = "http",
2522
- OAUTH2 = "oauth2",
2523
- OPENID_CONNECT = "openIdConnect"
2524
- }
2525
- /**
2526
- * Base class for authentication schemes
2564
+ * Google LLM Variant enum
2527
2565
  */
2528
- declare abstract class AuthScheme {
2529
- /**
2530
- * The type of authentication scheme
2531
- */
2532
- type: AuthSchemeType;
2533
- constructor(type: AuthSchemeType);
2566
+ declare enum GoogleLLMVariant {
2567
+ VERTEX_AI = "VERTEX_AI",
2568
+ GEMINI_API = "GEMINI_API"
2534
2569
  }
2535
2570
  /**
2536
- * API Key authentication scheme
2571
+ * Integration for Gemini models.
2537
2572
  */
2538
- declare class ApiKeyScheme extends AuthScheme {
2573
+ declare class GoogleLlm extends BaseLlm {
2574
+ private _apiClient?;
2575
+ private _liveApiClient?;
2576
+ private _apiBackend?;
2577
+ private _trackingHeaders?;
2539
2578
  /**
2540
- * Where the API key is sent
2579
+ * Constructor for Gemini
2541
2580
  */
2542
- in: "query" | "header" | "cookie";
2581
+ constructor(model?: string);
2543
2582
  /**
2544
- * Name of the parameter
2583
+ * Provides the list of supported models.
2545
2584
  */
2546
- name: string;
2585
+ static supportedModels(): string[];
2547
2586
  /**
2548
- * Description of the API key
2587
+ * Main content generation method - handles both streaming and non-streaming
2549
2588
  */
2550
- description?: string;
2589
+ protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2551
2590
  /**
2552
- * Constructor for ApiKeyScheme
2591
+ * Connects to the Gemini model and returns an llm connection.
2553
2592
  */
2554
- constructor(config: {
2555
- in: "query" | "header" | "cookie";
2556
- name: string;
2557
- description?: string;
2558
- });
2559
- }
2560
- /**
2561
- * HTTP authentication scheme
2562
- */
2563
- declare class HttpScheme extends AuthScheme {
2593
+ connect(_llmRequest: LlmRequest): BaseLLMConnection;
2564
2594
  /**
2565
- * The HTTP authentication scheme
2595
+ * Check if response has inline data
2566
2596
  */
2567
- scheme: "basic" | "bearer" | "digest" | "other";
2597
+ private hasInlineData;
2568
2598
  /**
2569
- * Bearer format when scheme is 'bearer'
2599
+ * Convert LlmRequest contents to GoogleGenAI format
2570
2600
  */
2571
- bearerFormat?: string;
2601
+ private convertContents;
2572
2602
  /**
2573
- * Description of the scheme
2603
+ * Preprocesses the request based on the API backend.
2574
2604
  */
2575
- description?: string;
2605
+ private preprocessRequest;
2576
2606
  /**
2577
- * Constructor for HttpScheme
2607
+ * Sets display_name to null for the Gemini API (non-Vertex) backend.
2578
2608
  */
2579
- constructor(config: {
2580
- scheme: "basic" | "bearer" | "digest" | "other";
2581
- bearerFormat?: string;
2582
- description?: string;
2583
- });
2584
- }
2585
- /**
2586
- * OAuth flow configuration
2587
- */
2588
- interface OAuthFlow {
2589
- authorizationUrl?: string;
2590
- tokenUrl?: string;
2591
- refreshUrl?: string;
2592
- scopes: Record<string, string>;
2593
- }
2594
- /**
2595
- * OAuth flows configuration
2596
- */
2597
- interface OAuthFlows {
2598
- implicit?: OAuthFlow;
2599
- password?: OAuthFlow;
2600
- clientCredentials?: OAuthFlow;
2601
- authorizationCode?: OAuthFlow;
2602
- }
2603
- /**
2604
- * OAuth2 authentication scheme
2605
- */
2606
- declare class OAuth2Scheme extends AuthScheme {
2609
+ private removeDisplayNameIfPresent;
2607
2610
  /**
2608
- * OAuth flows
2611
+ * Builds function declaration log string.
2609
2612
  */
2610
- flows: OAuthFlows;
2613
+ private buildFunctionDeclarationLog;
2611
2614
  /**
2612
- * Description of the scheme
2615
+ * Provides the api client.
2613
2616
  */
2614
- description?: string;
2617
+ get apiClient(): GoogleGenAI;
2615
2618
  /**
2616
- * Constructor for OAuth2Scheme
2619
+ * Gets the API backend type.
2617
2620
  */
2618
- constructor(config: {
2619
- flows: OAuthFlows;
2620
- description?: string;
2621
- });
2622
- }
2623
- /**
2624
- * OpenID Connect authentication scheme
2625
- */
2626
- declare class OpenIdConnectScheme extends AuthScheme {
2621
+ get apiBackend(): GoogleLLMVariant;
2627
2622
  /**
2628
- * OpenID Connect URL
2623
+ * Gets the tracking headers.
2629
2624
  */
2630
- openIdConnectUrl: string;
2625
+ get trackingHeaders(): Record<string, string>;
2631
2626
  /**
2632
- * Description of the scheme
2627
+ * Gets the live API version.
2633
2628
  */
2634
- description?: string;
2629
+ get liveApiVersion(): string;
2635
2630
  /**
2636
- * Constructor for OpenIdConnectScheme
2631
+ * Gets the live API client.
2637
2632
  */
2638
- constructor(config: {
2639
- openIdConnectUrl: string;
2640
- description?: string;
2641
- });
2633
+ get liveApiClient(): GoogleGenAI;
2642
2634
  }
2643
2635
 
2644
2636
  /**
2645
- * Authentication configuration for tools
2637
+ * Anthropic LLM implementation using Claude models
2646
2638
  */
2647
- declare class AuthConfig {
2639
+ declare class AnthropicLlm extends BaseLlm {
2640
+ private _client?;
2641
+ protected logger: Logger;
2648
2642
  /**
2649
- * The authentication scheme
2643
+ * Constructor for Anthropic LLM
2650
2644
  */
2651
- authScheme: AuthScheme;
2645
+ constructor(model?: string);
2652
2646
  /**
2653
- * Additional context properties
2647
+ * Provides the list of supported models
2654
2648
  */
2655
- context?: Record<string, any>;
2649
+ static supportedModels(): string[];
2656
2650
  /**
2657
- * Constructor for AuthConfig
2651
+ * Main content generation method - handles both streaming and non-streaming
2658
2652
  */
2659
- constructor(config: {
2660
- authScheme: AuthScheme;
2661
- context?: Record<string, any>;
2662
- });
2663
- }
2664
-
2665
- /**
2666
- * Handler for authentication in tools
2667
- */
2668
- declare class AuthHandler {
2653
+ protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2669
2654
  /**
2670
- * The authentication configuration
2655
+ * Live connection is not supported for Anthropic models
2671
2656
  */
2672
- authConfig: AuthConfig;
2657
+ connect(_llmRequest: LlmRequest): BaseLLMConnection;
2673
2658
  /**
2674
- * The authentication credential
2659
+ * Convert Anthropic Message to ADK LlmResponse
2675
2660
  */
2676
- credential?: AuthCredential;
2661
+ private anthropicMessageToLlmResponse;
2677
2662
  /**
2678
- * Constructor for AuthHandler
2663
+ * Convert ADK Content to Anthropic MessageParam
2679
2664
  */
2680
- constructor(config: {
2681
- authConfig: AuthConfig;
2682
- credential?: AuthCredential;
2683
- });
2665
+ private contentToAnthropicMessage;
2684
2666
  /**
2685
- * Gets the authentication token
2667
+ * Convert ADK Part to Anthropic content block
2686
2668
  */
2687
- getToken(): string | undefined;
2669
+ private partToAnthropicBlock;
2688
2670
  /**
2689
- * Gets headers for HTTP requests
2671
+ * Convert Anthropic content block to ADK Part
2690
2672
  */
2691
- getHeaders(): Record<string, string>;
2673
+ private anthropicBlockToPart;
2692
2674
  /**
2693
- * Refreshes the token if necessary
2675
+ * Convert ADK function declaration to Anthropic tool param
2694
2676
  */
2695
- refreshToken(): Promise<void>;
2696
- }
2697
-
2698
- /**
2699
- * Base class for LLM request processors.
2700
- */
2701
- declare abstract class BaseLlmRequestProcessor {
2677
+ private functionDeclarationToAnthropicTool;
2702
2678
  /**
2703
- * Runs the processor on the given invocation context and LLM request.
2704
- * @param invocationContext The invocation context
2705
- * @param llmRequest The LLM request to process
2706
- * @returns An async generator yielding events
2679
+ * Convert ADK role to Anthropic role format
2707
2680
  */
2708
- abstract runAsync(invocationContext: InvocationContext, llmRequest: LlmRequest): AsyncGenerator<Event, void, unknown>;
2709
- }
2710
- /**
2711
- * Base class for LLM response processors.
2712
- */
2713
- declare abstract class BaseLlmResponseProcessor {
2681
+ private toAnthropicRole;
2714
2682
  /**
2715
- * Processes the LLM response.
2716
- * @param invocationContext The invocation context
2717
- * @param llmResponse The LLM response to process
2718
- * @returns An async generator yielding events
2683
+ * Convert Anthropic stop reason to ADK finish reason
2719
2684
  */
2720
- abstract runAsync(invocationContext: InvocationContext, llmResponse: LlmResponse): AsyncGenerator<Event, void, unknown>;
2721
- }
2722
-
2723
- /**
2724
- * Auth LLM request processor that handles authentication information
2725
- * to build the LLM request with credential processing
2726
- */
2727
- declare class AuthLlmRequestProcessor extends BaseLlmRequestProcessor {
2685
+ private toAdkFinishReason;
2728
2686
  /**
2729
- * Processes authentication information from session events
2730
- * and resumes function calls that required authentication
2687
+ * Update type strings in schema to lowercase for Anthropic compatibility
2731
2688
  */
2732
- runAsync(invocationContext: InvocationContext, llmRequest: LlmRequest): AsyncGenerator<Event>;
2689
+ private updateTypeString;
2733
2690
  /**
2734
- * Parses and stores authentication response in session state
2691
+ * Gets the Anthropic client
2735
2692
  */
2736
- private parseAndStoreAuthResponse;
2693
+ private get client();
2737
2694
  }
2738
- /**
2739
- * Exported request processor instance for use in flow configurations
2740
- */
2741
- declare const requestProcessor$7: AuthLlmRequestProcessor;
2742
2695
 
2743
2696
  /**
2744
- * Enhanced auth configuration with credential handling
2745
- * This extends the basic AuthConfig with raw and exchanged credentials
2697
+ * OpenAI LLM implementation using GPT models
2698
+ * Enhanced with comprehensive debug logging similar to Google LLM
2746
2699
  */
2747
- declare class EnhancedAuthConfig {
2700
+ declare class OpenAiLlm extends BaseLlm {
2701
+ private _client?;
2748
2702
  /**
2749
- * The authentication scheme
2703
+ * Constructor for OpenAI LLM
2750
2704
  */
2751
- authScheme: AuthScheme;
2705
+ constructor(model?: string);
2752
2706
  /**
2753
- * Raw auth credential used to collect credentials
2754
- * Used in auth schemes that need to exchange credentials (e.g. OAuth2, OIDC)
2707
+ * Provides the list of supported models
2755
2708
  */
2756
- rawAuthCredential?: AuthCredential;
2709
+ static supportedModels(): string[];
2757
2710
  /**
2758
- * Exchanged auth credential after processing
2759
- * Filled by ADK and client working together
2711
+ * Main content generation method - handles both streaming and non-streaming
2760
2712
  */
2761
- exchangedAuthCredential?: AuthCredential;
2713
+ protected generateContentAsyncImpl(llmRequest: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2762
2714
  /**
2763
- * User-specified key for credential storage and retrieval
2715
+ * Live connection is not supported for OpenAI models
2764
2716
  */
2765
- credentialKey?: string;
2717
+ connect(_llmRequest: LlmRequest): BaseLLMConnection;
2766
2718
  /**
2767
- * Additional context properties
2719
+ * Create LlmResponse from streaming chunk - similar to Google's LlmResponse.create
2768
2720
  */
2769
- context?: Record<string, any>;
2721
+ private createChunkResponse;
2770
2722
  /**
2771
- * Constructor for EnhancedAuthConfig
2723
+ * Convert OpenAI message to ADK LlmResponse
2772
2724
  */
2773
- constructor(config: {
2774
- authScheme: AuthScheme;
2775
- rawAuthCredential?: AuthCredential;
2776
- exchangedAuthCredential?: AuthCredential;
2777
- credentialKey?: string;
2778
- context?: Record<string, any>;
2779
- });
2725
+ private openAiMessageToLlmResponse;
2780
2726
  /**
2781
- * Generates a credential key based on auth scheme and raw credential
2782
- * Used for saving/loading credentials from credential service
2727
+ * Convert ADK Content to OpenAI ChatCompletionMessage
2783
2728
  */
2784
- private generateCredentialKey;
2729
+ private contentToOpenAiMessage;
2785
2730
  /**
2786
- * Gets the credential key for storage
2731
+ * Convert ADK Part to OpenAI message content
2787
2732
  */
2788
- getCredentialKey(): string;
2789
- }
2790
- /**
2791
- * Arguments for the special long-running function tool used to request
2792
- * end-user credentials
2793
- */
2794
- interface AuthToolArguments extends Record<string, unknown> {
2733
+ private partToOpenAiContent;
2795
2734
  /**
2796
- * The ID of the function call that requires authentication
2735
+ * Convert ADK function declaration to OpenAI tool
2797
2736
  */
2798
- function_call_id: string;
2737
+ private functionDeclarationToOpenAiTool;
2799
2738
  /**
2800
- * The authentication configuration
2739
+ * Convert ADK role to OpenAI role format
2801
2740
  */
2802
- auth_config: AuthConfig | EnhancedAuthConfig;
2803
- }
2804
- /**
2805
- * Auth tool for handling credential requests
2806
- */
2807
- declare class AuthTool {
2741
+ private toOpenAiRole;
2808
2742
  /**
2809
- * Processes auth tool arguments and returns appropriate response
2743
+ * Convert OpenAI finish reason to ADK finish reason
2810
2744
  */
2811
- static processAuthRequest(args: AuthToolArguments): Promise<{
2812
- status: string;
2813
- authConfig?: AuthConfig | EnhancedAuthConfig;
2814
- credentialKey?: string;
2815
- }>;
2745
+ private toAdkFinishReason;
2816
2746
  /**
2817
- * Validates auth tool arguments
2747
+ * Preprocess request similar to Google LLM
2818
2748
  */
2819
- static validateAuthArguments(args: any): args is AuthToolArguments;
2820
- }
2821
- /**
2822
- * Creates an AuthToolArguments object with proper typing
2823
- */
2824
- declare function createAuthToolArguments(functionCallId: string, authConfig: AuthConfig | EnhancedAuthConfig): AuthToolArguments;
2825
- /**
2826
- * Type guard to check if an auth config is enhanced
2827
- */
2828
- declare function isEnhancedAuthConfig(config: AuthConfig | EnhancedAuthConfig): config is EnhancedAuthConfig;
2829
-
2830
- /**
2831
- * Types of authentication credentials
2832
- */
2833
- declare enum AuthCredentialType {
2834
- API_KEY = "api_key",
2835
- BASIC = "basic",
2836
- BEARER = "bearer",
2837
- OAUTH2 = "oauth2",
2838
- CUSTOM = "custom"
2839
- }
2840
- /**
2841
- * Base class for authentication credentials
2842
- */
2843
- declare abstract class AuthCredential {
2749
+ private preprocessRequest;
2844
2750
  /**
2845
- * Type of credential
2751
+ * Preprocess individual parts for OpenAI compatibility
2846
2752
  */
2847
- type: AuthCredentialType;
2753
+ private preprocessPart;
2848
2754
  /**
2849
- * Constructor for AuthCredential
2755
+ * Detect content type for flow control
2756
+ * This is a simplified implementation - you may need to adjust based on your specific requirements
2850
2757
  */
2851
- constructor(type: AuthCredentialType);
2758
+ private getContentType;
2852
2759
  /**
2853
- * Gets the authentication token
2760
+ * Check if response has inline data (similar to Google LLM)
2854
2761
  */
2855
- abstract getToken(): string | undefined;
2762
+ private hasInlineData;
2856
2763
  /**
2857
- * Gets headers for HTTP requests
2764
+ * Gets the OpenAI client
2858
2765
  */
2859
- abstract getHeaders(config: AuthConfig): Record<string, string>;
2766
+ private get client();
2767
+ }
2768
+
2769
+ /**
2770
+ * AI SDK integration that accepts a pre-configured LanguageModel.
2771
+ * Enables ADK to work with any provider supported by Vercel's AI SDK.
2772
+ */
2773
+ declare class AiSdkLlm extends BaseLlm {
2774
+ private modelInstance;
2775
+ protected logger: Logger;
2860
2776
  /**
2861
- * Whether the token can be refreshed
2777
+ * Constructor accepts a pre-configured LanguageModel instance
2778
+ * @param model - Pre-configured LanguageModel from provider(modelName)
2862
2779
  */
2863
- canRefresh(): boolean;
2780
+ constructor(modelInstance: LanguageModel);
2864
2781
  /**
2865
- * Refreshes the token
2782
+ * Returns empty array - following Python ADK pattern
2866
2783
  */
2867
- refresh(): Promise<void>;
2868
- }
2869
- /**
2870
- * API Key credential
2871
- */
2872
- declare class ApiKeyCredential extends AuthCredential {
2784
+ static supportedModels(): string[];
2785
+ protected generateContentAsyncImpl(request: LlmRequest, stream?: boolean): AsyncGenerator<LlmResponse, void, unknown>;
2873
2786
  /**
2874
- * The API key
2787
+ * Convert ADK LlmRequest to AI SDK CoreMessage format
2875
2788
  */
2876
- apiKey: string;
2789
+ private convertToAiSdkMessages;
2877
2790
  /**
2878
- * Constructor for ApiKeyCredential
2791
+ * Convert ADK tools to AI SDK tools format
2879
2792
  */
2880
- constructor(apiKey: string);
2793
+ private convertToAiSdkTools;
2881
2794
  /**
2882
- * Gets the API key as the token
2795
+ * Convert ADK Content to AI SDK CoreMessage
2883
2796
  */
2884
- getToken(): string;
2797
+ private contentToAiSdkMessage;
2885
2798
  /**
2886
- * Gets headers for HTTP requests
2799
+ * Map ADK role to AI SDK role
2887
2800
  */
2888
- getHeaders(config: AuthConfig): Record<string, string>;
2801
+ private mapRole;
2802
+ /**
2803
+ * Map AI SDK finish reason to ADK finish reason
2804
+ */
2805
+ private mapFinishReason;
2889
2806
  }
2807
+
2890
2808
  /**
2891
- * Basic authentication credential
2809
+ * Type for LLM constructor with static methods
2892
2810
  */
2893
- declare class BasicAuthCredential extends AuthCredential {
2811
+ interface LLMClass {
2812
+ new (model: string): BaseLlm;
2813
+ supportedModels(): string[];
2814
+ }
2815
+ /**
2816
+ * Registry for LLMs
2817
+ */
2818
+ declare class LLMRegistry {
2894
2819
  /**
2895
- * The username
2820
+ * Map of model name regex to LLM class
2896
2821
  */
2897
- username: string;
2822
+ private static llmRegistry;
2823
+ private static logger;
2898
2824
  /**
2899
- * The password
2825
+ * Creates a new LLM instance
2826
+ *
2827
+ * @param model The model name
2828
+ * @returns The LLM instance
2900
2829
  */
2901
- password: string;
2830
+ static newLLM(model: string): BaseLlm;
2902
2831
  /**
2903
- * Constructor for BasicAuthCredential
2832
+ * Resolves the LLM class from the model name
2833
+ *
2834
+ * @param model The model name
2835
+ * @returns The LLM class
2904
2836
  */
2905
- constructor(username: string, password: string);
2837
+ static resolve(model: string): LLMClass | null;
2906
2838
  /**
2907
- * Gets the encoded basic auth token
2839
+ * Registers a new LLM class
2840
+ *
2841
+ * @param modelNameRegex The regex to match model names
2842
+ * @param llmClass The LLM class
2908
2843
  */
2909
- getToken(): string;
2844
+ static register(modelNameRegex: string, llmClass: LLMClass): void;
2910
2845
  /**
2911
- * Gets headers for HTTP requests
2846
+ * Registers all model patterns from an LLM class
2847
+ *
2848
+ * @param llmClass The LLM class
2912
2849
  */
2913
- getHeaders(): Record<string, string>;
2850
+ static registerLLM(llmClass: LLMClass): void;
2851
+ /**
2852
+ * Logs all registered models for debugging
2853
+ */
2854
+ static logRegisteredModels(): void;
2914
2855
  }
2856
+
2915
2857
  /**
2916
- * Bearer token credential
2858
+ * Register all LLM providers
2917
2859
  */
2918
- declare class BearerTokenCredential extends AuthCredential {
2919
- /**
2920
- * The bearer token
2921
- */
2922
- token: string;
2923
- /**
2924
- * Constructor for BearerTokenCredential
2925
- */
2926
- constructor(token: string);
2860
+ declare function registerProviders(): void;
2861
+
2862
+ /**
2863
+ * Configuration for model built-in thinking features
2864
+ * Compatible with google.genai.types.ThinkingConfig
2865
+ */
2866
+ interface ThinkingConfig {
2927
2867
  /**
2928
- * Gets the bearer token
2868
+ * Whether to include the thinking process in the response
2929
2869
  */
2930
- getToken(): string;
2870
+ includeThinking?: boolean;
2931
2871
  /**
2932
- * Gets headers for HTTP requests
2872
+ * Additional thinking configuration options
2933
2873
  */
2934
- getHeaders(): Record<string, string>;
2874
+ [key: string]: any;
2875
+ }
2876
+
2877
+ /**
2878
+ * Authentication scheme types
2879
+ */
2880
+ declare enum AuthSchemeType {
2881
+ APIKEY = "apiKey",
2882
+ HTTP = "http",
2883
+ OAUTH2 = "oauth2",
2884
+ OPENID_CONNECT = "openIdConnect"
2935
2885
  }
2936
2886
  /**
2937
- * OAuth2 token credential with refresh capability
2887
+ * Base class for authentication schemes
2938
2888
  */
2939
- declare class OAuth2Credential extends AuthCredential {
2889
+ declare abstract class AuthScheme {
2940
2890
  /**
2941
- * The access token
2891
+ * The type of authentication scheme
2942
2892
  */
2943
- accessToken: string;
2893
+ type: AuthSchemeType;
2894
+ constructor(type: AuthSchemeType);
2895
+ }
2896
+ /**
2897
+ * API Key authentication scheme
2898
+ */
2899
+ declare class ApiKeyScheme extends AuthScheme {
2944
2900
  /**
2945
- * The refresh token
2901
+ * Where the API key is sent
2946
2902
  */
2947
- refreshToken?: string;
2903
+ in: "query" | "header" | "cookie";
2948
2904
  /**
2949
- * When the token expires
2905
+ * Name of the parameter
2950
2906
  */
2951
- expiresAt?: Date;
2907
+ name: string;
2952
2908
  /**
2953
- * Function to refresh the token
2909
+ * Description of the API key
2954
2910
  */
2955
- private refreshFunction?;
2911
+ description?: string;
2956
2912
  /**
2957
- * Constructor for OAuth2Credential
2913
+ * Constructor for ApiKeyScheme
2958
2914
  */
2959
2915
  constructor(config: {
2960
- accessToken: string;
2961
- refreshToken?: string;
2962
- expiresIn?: number;
2963
- refreshFunction?: (refreshToken: string) => Promise<{
2964
- accessToken: string;
2965
- refreshToken?: string;
2966
- expiresIn?: number;
2967
- }>;
2916
+ in: "query" | "header" | "cookie";
2917
+ name: string;
2918
+ description?: string;
2968
2919
  });
2920
+ }
2921
+ /**
2922
+ * HTTP authentication scheme
2923
+ */
2924
+ declare class HttpScheme extends AuthScheme {
2969
2925
  /**
2970
- * Gets the access token
2971
- */
2972
- getToken(): string;
2973
- /**
2974
- * Gets headers for HTTP requests
2926
+ * The HTTP authentication scheme
2975
2927
  */
2976
- getHeaders(): Record<string, string>;
2928
+ scheme: "basic" | "bearer" | "digest" | "other";
2977
2929
  /**
2978
- * Whether the token can be refreshed
2930
+ * Bearer format when scheme is 'bearer'
2979
2931
  */
2980
- canRefresh(): boolean;
2932
+ bearerFormat?: string;
2981
2933
  /**
2982
- * Whether the token is expired
2934
+ * Description of the scheme
2983
2935
  */
2984
- isExpired(): boolean;
2936
+ description?: string;
2985
2937
  /**
2986
- * Refreshes the token
2938
+ * Constructor for HttpScheme
2987
2939
  */
2988
- refresh(): Promise<void>;
2940
+ constructor(config: {
2941
+ scheme: "basic" | "bearer" | "digest" | "other";
2942
+ bearerFormat?: string;
2943
+ description?: string;
2944
+ });
2989
2945
  }
2990
-
2991
2946
  /**
2992
- * Models module exports - consolidated to match Python structure
2947
+ * OAuth flow configuration
2993
2948
  */
2994
-
2995
- type index$5_AiSdkLlm = AiSdkLlm;
2996
- declare const index$5_AiSdkLlm: typeof AiSdkLlm;
2997
- type index$5_AnthropicLlm = AnthropicLlm;
2998
- declare const index$5_AnthropicLlm: typeof AnthropicLlm;
2999
- type index$5_ApiKeyCredential = ApiKeyCredential;
3000
- declare const index$5_ApiKeyCredential: typeof ApiKeyCredential;
3001
- type index$5_ApiKeyScheme = ApiKeyScheme;
3002
- declare const index$5_ApiKeyScheme: typeof ApiKeyScheme;
3003
- type index$5_AuthConfig = AuthConfig;
3004
- declare const index$5_AuthConfig: typeof AuthConfig;
3005
- type index$5_AuthCredential = AuthCredential;
3006
- declare const index$5_AuthCredential: typeof AuthCredential;
3007
- type index$5_AuthCredentialType = AuthCredentialType;
3008
- declare const index$5_AuthCredentialType: typeof AuthCredentialType;
3009
- type index$5_AuthHandler = AuthHandler;
3010
- declare const index$5_AuthHandler: typeof AuthHandler;
3011
- type index$5_AuthScheme = AuthScheme;
3012
- declare const index$5_AuthScheme: typeof AuthScheme;
3013
- type index$5_AuthSchemeType = AuthSchemeType;
3014
- declare const index$5_AuthSchemeType: typeof AuthSchemeType;
3015
- type index$5_BaseLLMConnection = BaseLLMConnection;
3016
- declare const index$5_BaseLLMConnection: typeof BaseLLMConnection;
3017
- type index$5_BaseLlm = BaseLlm;
3018
- declare const index$5_BaseLlm: typeof BaseLlm;
3019
- type index$5_BaseMemoryService = BaseMemoryService;
3020
- type index$5_BasicAuthCredential = BasicAuthCredential;
3021
- declare const index$5_BasicAuthCredential: typeof BasicAuthCredential;
3022
- type index$5_BearerTokenCredential = BearerTokenCredential;
3023
- declare const index$5_BearerTokenCredential: typeof BearerTokenCredential;
3024
- declare const index$5_Blob: typeof Blob;
3025
- type index$5_FunctionDeclaration = FunctionDeclaration;
3026
- type index$5_GoogleLlm = GoogleLlm;
3027
- declare const index$5_GoogleLlm: typeof GoogleLlm;
3028
- type index$5_HttpScheme = HttpScheme;
3029
- declare const index$5_HttpScheme: typeof HttpScheme;
3030
- type index$5_JSONSchema = JSONSchema;
3031
- type index$5_LLMRegistry = LLMRegistry;
3032
- declare const index$5_LLMRegistry: typeof LLMRegistry;
3033
- type index$5_LlmRequest = LlmRequest;
3034
- declare const index$5_LlmRequest: typeof LlmRequest;
3035
- type index$5_LlmResponse = LlmResponse;
3036
- declare const index$5_LlmResponse: typeof LlmResponse;
3037
- type index$5_OAuth2Credential = OAuth2Credential;
3038
- declare const index$5_OAuth2Credential: typeof OAuth2Credential;
3039
- type index$5_OAuth2Scheme = OAuth2Scheme;
3040
- declare const index$5_OAuth2Scheme: typeof OAuth2Scheme;
3041
- type index$5_OAuthFlow = OAuthFlow;
3042
- type index$5_OAuthFlows = OAuthFlows;
3043
- type index$5_OpenAiLlm = OpenAiLlm;
3044
- declare const index$5_OpenAiLlm: typeof OpenAiLlm;
3045
- type index$5_OpenIdConnectScheme = OpenIdConnectScheme;
3046
- declare const index$5_OpenIdConnectScheme: typeof OpenIdConnectScheme;
3047
- type index$5_SearchMemoryResponse = SearchMemoryResponse;
3048
- type index$5_Session = Session;
3049
- type index$5_State = State;
3050
- declare const index$5_State: typeof State;
3051
- type index$5_ThinkingConfig = ThinkingConfig;
3052
- declare const index$5_registerProviders: typeof registerProviders;
3053
- declare namespace index$5 {
3054
- export { index$5_AiSdkLlm as AiSdkLlm, index$5_AnthropicLlm as AnthropicLlm, index$5_ApiKeyCredential as ApiKeyCredential, index$5_ApiKeyScheme as ApiKeyScheme, index$5_AuthConfig as AuthConfig, index$5_AuthCredential as AuthCredential, index$5_AuthCredentialType as AuthCredentialType, index$5_AuthHandler as AuthHandler, index$5_AuthScheme as AuthScheme, index$5_AuthSchemeType as AuthSchemeType, index$5_BaseLLMConnection as BaseLLMConnection, index$5_BaseLlm as BaseLlm, type index$5_BaseMemoryService as BaseMemoryService, index$5_BasicAuthCredential as BasicAuthCredential, index$5_BearerTokenCredential as BearerTokenCredential, index$5_Blob as Blob, Content$1 as Content, type index$5_FunctionDeclaration as FunctionDeclaration, index$5_GoogleLlm as GoogleLlm, index$5_HttpScheme as HttpScheme, type index$5_JSONSchema as JSONSchema, index$5_LLMRegistry as LLMRegistry, index$5_LlmRequest as LlmRequest, index$5_LlmResponse as LlmResponse, index$5_OAuth2Credential as OAuth2Credential, index$5_OAuth2Scheme as OAuth2Scheme, type index$5_OAuthFlow as OAuthFlow, type index$5_OAuthFlows as OAuthFlows, index$5_OpenAiLlm as OpenAiLlm, index$5_OpenIdConnectScheme as OpenIdConnectScheme, type index$5_SearchMemoryResponse as SearchMemoryResponse, type index$5_Session as Session, index$5_State as State, type index$5_ThinkingConfig as ThinkingConfig, index$5_registerProviders as registerProviders };
2949
+ interface OAuthFlow {
2950
+ authorizationUrl?: string;
2951
+ tokenUrl?: string;
2952
+ refreshUrl?: string;
2953
+ scopes: Record<string, string>;
3055
2954
  }
3056
-
3057
2955
  /**
3058
- * Options for creating an Event.
2956
+ * OAuth flows configuration
3059
2957
  */
3060
- interface EventOpts {
3061
- invocationId?: string;
3062
- author: string;
3063
- actions?: EventActions;
3064
- longRunningToolIds?: Set<string>;
3065
- branch?: string;
3066
- id?: string;
3067
- timestamp?: number;
3068
- content?: any;
3069
- partial?: boolean;
2958
+ interface OAuthFlows {
2959
+ implicit?: OAuthFlow;
2960
+ password?: OAuthFlow;
2961
+ clientCredentials?: OAuthFlow;
2962
+ authorizationCode?: OAuthFlow;
3070
2963
  }
3071
2964
  /**
3072
- * Represents an event in a conversation between agents and users.
3073
- * It is used to store the content of the conversation, as well as the actions
3074
- * taken by the agents like function calls, etc.
2965
+ * OAuth2 authentication scheme
3075
2966
  */
3076
- declare class Event extends LlmResponse {
3077
- /** The invocation ID of the event. */
3078
- invocationId: string;
3079
- /** 'user' or the name of the agent, indicating who appended the event to the session. */
3080
- author: string;
3081
- /** The actions taken by the agent. */
3082
- actions: EventActions;
2967
+ declare class OAuth2Scheme extends AuthScheme {
3083
2968
  /**
3084
- * Set of ids of the long running function calls.
3085
- * Agent client will know from this field about which function call is long running.
3086
- * Only valid for function call event.
2969
+ * OAuth flows
3087
2970
  */
3088
- longRunningToolIds?: Set<string>;
2971
+ flows: OAuthFlows;
3089
2972
  /**
3090
- * The branch of the event.
3091
- * The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
3092
- * agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple
3093
- * sub-agents shouldn't see their peer agents' conversation history.
2973
+ * Description of the scheme
3094
2974
  */
3095
- branch?: string;
3096
- /** The unique identifier of the event. */
3097
- id: string;
3098
- /** The timestamp of the event (seconds since epoch). */
3099
- timestamp: number;
2975
+ description?: string;
3100
2976
  /**
3101
- * Constructor for Event.
2977
+ * Constructor for OAuth2Scheme
3102
2978
  */
3103
- constructor(opts: EventOpts);
2979
+ constructor(config: {
2980
+ flows: OAuthFlows;
2981
+ description?: string;
2982
+ });
2983
+ }
2984
+ /**
2985
+ * OpenID Connect authentication scheme
2986
+ */
2987
+ declare class OpenIdConnectScheme extends AuthScheme {
3104
2988
  /**
3105
- * Returns whether the event is the final response of the agent.
2989
+ * OpenID Connect URL
3106
2990
  */
3107
- isFinalResponse(): boolean;
2991
+ openIdConnectUrl: string;
3108
2992
  /**
3109
- * Returns the function calls in the event.
2993
+ * Description of the scheme
3110
2994
  */
3111
- getFunctionCalls(): any[];
2995
+ description?: string;
3112
2996
  /**
3113
- * Returns the function responses in the event.
2997
+ * Constructor for OpenIdConnectScheme
3114
2998
  */
3115
- getFunctionResponses(): any[];
2999
+ constructor(config: {
3000
+ openIdConnectUrl: string;
3001
+ description?: string;
3002
+ });
3003
+ }
3004
+
3005
+ /**
3006
+ * Authentication configuration for tools
3007
+ */
3008
+ declare class AuthConfig {
3116
3009
  /**
3117
- * Returns whether the event has a trailing code execution result.
3010
+ * The authentication scheme
3118
3011
  */
3119
- hasTrailingCodeExecutionResult(): boolean;
3012
+ authScheme: AuthScheme;
3120
3013
  /**
3121
- * Generates a new random ID for an event.
3014
+ * Additional context properties
3122
3015
  */
3123
- static newId(): string;
3016
+ context?: Record<string, any>;
3017
+ /**
3018
+ * Constructor for AuthConfig
3019
+ */
3020
+ constructor(config: {
3021
+ authScheme: AuthScheme;
3022
+ context?: Record<string, any>;
3023
+ });
3124
3024
  }
3125
3025
 
3126
3026
  /**
3127
- * Single agent callback type
3128
- */
3129
- type SingleAgentCallback = (callbackContext: CallbackContext) => Promise<Content$1 | undefined> | Content$1 | undefined;
3130
- /**
3131
- * Before agent callback type
3132
- */
3133
- type BeforeAgentCallback = SingleAgentCallback | SingleAgentCallback[];
3134
- /**
3135
- * After agent callback type
3136
- */
3137
- type AfterAgentCallback = SingleAgentCallback | SingleAgentCallback[];
3138
- /**
3139
- * Base class for all agents in Agent Development Kit.
3027
+ * Handler for authentication in tools
3140
3028
  */
3141
- declare abstract class BaseAgent {
3142
- /**
3143
- * The agent's name.
3144
- * Agent name must be a valid identifier and unique within the agent tree.
3145
- * Agent name cannot be "user", since it's reserved for end-user's input.
3146
- */
3147
- name: string;
3029
+ declare class AuthHandler {
3148
3030
  /**
3149
- * Description about the agent's capability.
3150
- * The model uses this to determine whether to delegate control to the agent.
3151
- * One-line description is enough and preferred.
3031
+ * The authentication configuration
3152
3032
  */
3153
- description: string;
3033
+ authConfig: AuthConfig;
3154
3034
  /**
3155
- * The parent agent of this agent.
3156
- * Note that an agent can ONLY be added as sub-agent once.
3157
- * If you want to add one agent twice as sub-agent, consider to create two agent
3158
- * instances with identical config, but with different name and add them to the
3159
- * agent tree.
3035
+ * The authentication credential
3160
3036
  */
3161
- parentAgent?: BaseAgent;
3037
+ credential?: AuthCredential;
3162
3038
  /**
3163
- * The sub-agents of this agent.
3039
+ * Constructor for AuthHandler
3164
3040
  */
3165
- subAgents: BaseAgent[];
3041
+ constructor(config: {
3042
+ authConfig: AuthConfig;
3043
+ credential?: AuthCredential;
3044
+ });
3166
3045
  /**
3167
- * Callback or list of callbacks to be invoked before the agent run.
3168
- * When a list of callbacks is provided, the callbacks will be called in the
3169
- * order they are listed until a callback does not return undefined.
3170
- *
3171
- * Args:
3172
- * callbackContext: The callback context.
3173
- *
3174
- * Returns:
3175
- * Content | undefined: The content to return to the user.
3176
- * When the content is present, the agent run will be skipped and the
3177
- * provided content will be returned to user.
3046
+ * Gets the authentication token
3178
3047
  */
3179
- beforeAgentCallback?: BeforeAgentCallback;
3048
+ getToken(): string | undefined;
3180
3049
  /**
3181
- * Callback or list of callbacks to be invoked after the agent run.
3182
- * When a list of callbacks is provided, the callbacks will be called in the
3183
- * order they are listed until a callback does not return undefined.
3184
- *
3185
- * Args:
3186
- * callbackContext: The callback context.
3187
- *
3188
- * Returns:
3189
- * Content | undefined: The content to return to the user.
3190
- * When the content is present, the provided content will be used as agent
3191
- * response and appended to event history as agent response.
3050
+ * Gets headers for HTTP requests
3192
3051
  */
3193
- afterAgentCallback?: AfterAgentCallback;
3052
+ getHeaders(): Record<string, string>;
3194
3053
  /**
3195
- * Constructor for BaseAgent
3054
+ * Refreshes the token if necessary
3196
3055
  */
3197
- constructor(config: {
3198
- name: string;
3199
- description?: string;
3200
- subAgents?: BaseAgent[];
3201
- beforeAgentCallback?: BeforeAgentCallback;
3202
- afterAgentCallback?: AfterAgentCallback;
3203
- });
3056
+ refreshToken(): Promise<void>;
3057
+ }
3058
+
3059
+ /**
3060
+ * Base class for LLM request processors.
3061
+ */
3062
+ declare abstract class BaseLlmRequestProcessor {
3204
3063
  /**
3205
- * Entry method to run an agent via text-based conversation.
3064
+ * Runs the processor on the given invocation context and LLM request.
3065
+ * @param invocationContext The invocation context
3066
+ * @param llmRequest The LLM request to process
3067
+ * @returns An async generator yielding events
3206
3068
  */
3207
- runAsync(parentContext: InvocationContext): AsyncGenerator<Event, void, unknown>;
3069
+ abstract runAsync(invocationContext: InvocationContext, llmRequest: LlmRequest): AsyncGenerator<Event, void, unknown>;
3070
+ }
3071
+ /**
3072
+ * Base class for LLM response processors.
3073
+ */
3074
+ declare abstract class BaseLlmResponseProcessor {
3208
3075
  /**
3209
- * Entry method to run an agent via video/audio-based conversation.
3076
+ * Processes the LLM response.
3077
+ * @param invocationContext The invocation context
3078
+ * @param llmResponse The LLM response to process
3079
+ * @returns An async generator yielding events
3210
3080
  */
3211
- runLive(parentContext: InvocationContext): AsyncGenerator<Event, void, unknown>;
3081
+ abstract runAsync(invocationContext: InvocationContext, llmResponse: LlmResponse): AsyncGenerator<Event, void, unknown>;
3082
+ }
3083
+
3084
+ /**
3085
+ * Auth LLM request processor that handles authentication information
3086
+ * to build the LLM request with credential processing
3087
+ */
3088
+ declare class AuthLlmRequestProcessor extends BaseLlmRequestProcessor {
3212
3089
  /**
3213
- * Internal implementation for runAsync
3090
+ * Processes authentication information from session events
3091
+ * and resumes function calls that required authentication
3214
3092
  */
3215
- private runAsyncInternal;
3093
+ runAsync(invocationContext: InvocationContext, llmRequest: LlmRequest): AsyncGenerator<Event>;
3216
3094
  /**
3217
- * Internal implementation for runLive
3095
+ * Parses and stores authentication response in session state
3218
3096
  */
3219
- private runLiveInternal;
3097
+ private parseAndStoreAuthResponse;
3098
+ }
3099
+ /**
3100
+ * Exported request processor instance for use in flow configurations
3101
+ */
3102
+ declare const requestProcessor$7: AuthLlmRequestProcessor;
3103
+
3104
+ /**
3105
+ * Enhanced auth configuration with credential handling
3106
+ * This extends the basic AuthConfig with raw and exchanged credentials
3107
+ */
3108
+ declare class EnhancedAuthConfig {
3220
3109
  /**
3221
- * Core logic to run this agent via text-based conversation.
3222
- *
3223
- * @param ctx - The invocation context for this agent.
3224
- * @yields Event - The events generated by the agent.
3110
+ * The authentication scheme
3225
3111
  */
3226
- protected runAsyncImpl(_ctx: InvocationContext): AsyncGenerator<Event, void, unknown>;
3112
+ authScheme: AuthScheme;
3227
3113
  /**
3228
- * Core logic to run this agent via video/audio-based conversation.
3229
- *
3230
- * @param ctx - The invocation context for this agent.
3231
- * @yields Event - The events generated by the agent.
3114
+ * Raw auth credential used to collect credentials
3115
+ * Used in auth schemes that need to exchange credentials (e.g. OAuth2, OIDC)
3232
3116
  */
3233
- protected runLiveImpl(_ctx: InvocationContext): AsyncGenerator<Event, void, unknown>;
3117
+ rawAuthCredential?: AuthCredential;
3234
3118
  /**
3235
- * Gets the root agent of this agent.
3119
+ * Exchanged auth credential after processing
3120
+ * Filled by ADK and client working together
3236
3121
  */
3237
- get rootAgent(): BaseAgent;
3122
+ exchangedAuthCredential?: AuthCredential;
3238
3123
  /**
3239
- * Finds the agent with the given name in this agent and its descendants.
3240
- *
3241
- * @param name - The name of the agent to find.
3242
- * @returns The agent with the matching name, or undefined if no such agent is found.
3124
+ * User-specified key for credential storage and retrieval
3243
3125
  */
3244
- findAgent(name: string): BaseAgent | undefined;
3126
+ credentialKey?: string;
3245
3127
  /**
3246
- * Finds the agent with the given name in this agent's descendants.
3247
- *
3248
- * @param name - The name of the agent to find.
3249
- * @returns The agent with the matching name, or undefined if no such agent is found.
3128
+ * Additional context properties
3250
3129
  */
3251
- findSubAgent(name: string): BaseAgent | undefined;
3130
+ context?: Record<string, any>;
3252
3131
  /**
3253
- * Creates a new invocation context for this agent.
3132
+ * Constructor for EnhancedAuthConfig
3254
3133
  */
3255
- private createInvocationContext;
3134
+ constructor(config: {
3135
+ authScheme: AuthScheme;
3136
+ rawAuthCredential?: AuthCredential;
3137
+ exchangedAuthCredential?: AuthCredential;
3138
+ credentialKey?: string;
3139
+ context?: Record<string, any>;
3140
+ });
3256
3141
  /**
3257
- * The resolved beforeAgentCallback field as a list of SingleAgentCallback.
3258
- * This method is only for use by Agent Development Kit.
3142
+ * Generates a credential key based on auth scheme and raw credential
3143
+ * Used for saving/loading credentials from credential service
3259
3144
  */
3260
- get canonicalBeforeAgentCallbacks(): SingleAgentCallback[];
3145
+ private generateCredentialKey;
3261
3146
  /**
3262
- * The resolved afterAgentCallback field as a list of SingleAgentCallback.
3263
- * This method is only for use by Agent Development Kit.
3147
+ * Gets the credential key for storage
3264
3148
  */
3265
- get canonicalAfterAgentCallbacks(): SingleAgentCallback[];
3149
+ getCredentialKey(): string;
3150
+ }
3151
+ /**
3152
+ * Arguments for the special long-running function tool used to request
3153
+ * end-user credentials
3154
+ */
3155
+ interface AuthToolArguments extends Record<string, unknown> {
3266
3156
  /**
3267
- * Runs the beforeAgentCallback if it exists.
3268
- *
3269
- * @returns An event if callback provides content or changed state.
3157
+ * The ID of the function call that requires authentication
3270
3158
  */
3271
- private handleBeforeAgentCallback;
3159
+ function_call_id: string;
3272
3160
  /**
3273
- * Runs the afterAgentCallback if it exists.
3274
- *
3275
- * @returns An event if callback provides content or changed state.
3161
+ * The authentication configuration
3276
3162
  */
3277
- private handleAfterAgentCallback;
3163
+ auth_config: AuthConfig | EnhancedAuthConfig;
3164
+ }
3165
+ /**
3166
+ * Auth tool for handling credential requests
3167
+ */
3168
+ declare class AuthTool {
3278
3169
  /**
3279
- * Validates the agent name.
3170
+ * Processes auth tool arguments and returns appropriate response
3280
3171
  */
3281
- private validateName;
3172
+ static processAuthRequest(args: AuthToolArguments): Promise<{
3173
+ status: string;
3174
+ authConfig?: AuthConfig | EnhancedAuthConfig;
3175
+ credentialKey?: string;
3176
+ }>;
3282
3177
  /**
3283
- * Sets parent agent for sub-agents.
3178
+ * Validates auth tool arguments
3284
3179
  */
3285
- private setParentAgentForSubAgents;
3180
+ static validateAuthArguments(args: any): args is AuthToolArguments;
3286
3181
  }
3182
+ /**
3183
+ * Creates an AuthToolArguments object with proper typing
3184
+ */
3185
+ declare function createAuthToolArguments(functionCallId: string, authConfig: AuthConfig | EnhancedAuthConfig): AuthToolArguments;
3186
+ /**
3187
+ * Type guard to check if an auth config is enhanced
3188
+ */
3189
+ declare function isEnhancedAuthConfig(config: AuthConfig | EnhancedAuthConfig): config is EnhancedAuthConfig;
3287
3190
 
3288
- interface File {
3289
- /** The name of the file with file extension (e.g., "file.csv") */
3290
- name: string;
3291
- /** The base64-encoded bytes of the file content */
3292
- content: string;
3293
- /** The mime type of the file (e.g., "image/png") */
3294
- mimeType: string;
3295
- }
3296
- interface CodeExecutionInput {
3297
- /** The code to execute */
3298
- code: string;
3299
- /** The input files available to the code */
3300
- inputFiles: File[];
3301
- /** The execution ID for the stateful code execution */
3302
- executionId?: string;
3303
- }
3304
- interface CodeExecutionResult {
3305
- /** The standard output of the code execution */
3306
- stdout: string;
3307
- /** The standard error of the code execution */
3308
- stderr: string;
3309
- /** The output files from the code execution */
3310
- outputFiles: File[];
3191
+ /**
3192
+ * Types of authentication credentials
3193
+ */
3194
+ declare enum AuthCredentialType {
3195
+ API_KEY = "api_key",
3196
+ BASIC = "basic",
3197
+ BEARER = "bearer",
3198
+ OAUTH2 = "oauth2",
3199
+ CUSTOM = "custom"
3311
3200
  }
3312
- declare class CodeExecutionUtils {
3201
+ /**
3202
+ * Base class for authentication credentials
3203
+ */
3204
+ declare abstract class AuthCredential {
3205
+ /**
3206
+ * Type of credential
3207
+ */
3208
+ type: AuthCredentialType;
3209
+ /**
3210
+ * Constructor for AuthCredential
3211
+ */
3212
+ constructor(type: AuthCredentialType);
3213
+ /**
3214
+ * Gets the authentication token
3215
+ */
3216
+ abstract getToken(): string | undefined;
3217
+ /**
3218
+ * Gets headers for HTTP requests
3219
+ */
3220
+ abstract getHeaders(config: AuthConfig): Record<string, string>;
3313
3221
  /**
3314
- * Gets the file content as a base64-encoded string
3222
+ * Whether the token can be refreshed
3315
3223
  */
3316
- static getEncodedFileContent(data: string | ArrayBuffer): string;
3317
- private static isBase64Encoded;
3224
+ canRefresh(): boolean;
3318
3225
  /**
3319
- * Extracts the first code block from the content and truncates everything after it
3226
+ * Refreshes the token
3320
3227
  */
3321
- static extractCodeAndTruncateContent(content: Content$1, codeBlockDelimiters: Array<[string, string]>): string | null;
3322
- private static escapeRegex;
3228
+ refresh(): Promise<void>;
3229
+ }
3230
+ /**
3231
+ * API Key credential
3232
+ */
3233
+ declare class ApiKeyCredential extends AuthCredential {
3323
3234
  /**
3324
- * Builds an executable code part with code string
3235
+ * The API key
3325
3236
  */
3326
- static buildExecutableCodePart(code: string): Part;
3237
+ apiKey: string;
3327
3238
  /**
3328
- * Builds the code execution result part from the code execution result
3239
+ * Constructor for ApiKeyCredential
3329
3240
  */
3330
- static buildCodeExecutionResultPart(codeExecutionResult: CodeExecutionResult): Part;
3241
+ constructor(apiKey: string);
3331
3242
  /**
3332
- * Converts the code execution parts to text parts in a Content
3243
+ * Gets the API key as the token
3333
3244
  */
3334
- static convertCodeExecutionParts(content: Content$1, codeBlockDelimiter: [string, string], executionResultDelimiters: [string, string]): void;
3335
- }
3336
-
3337
- interface BaseCodeExecutorConfig {
3245
+ getToken(): string;
3338
3246
  /**
3339
- * If true, extract and process data files from the model request
3340
- * and attach them to the code executor.
3341
- * Supported data file MimeTypes are [text/csv].
3342
- * Default to false.
3247
+ * Gets headers for HTTP requests
3343
3248
  */
3344
- optimizeDataFile?: boolean;
3249
+ getHeaders(config: AuthConfig): Record<string, string>;
3250
+ }
3251
+ /**
3252
+ * Basic authentication credential
3253
+ */
3254
+ declare class BasicAuthCredential extends AuthCredential {
3345
3255
  /**
3346
- * Whether the code executor is stateful. Default to false.
3256
+ * The username
3347
3257
  */
3348
- stateful?: boolean;
3258
+ username: string;
3349
3259
  /**
3350
- * The number of attempts to retry on consecutive code execution errors.
3351
- * Default to 2.
3260
+ * The password
3352
3261
  */
3353
- errorRetryAttempts?: number;
3262
+ password: string;
3354
3263
  /**
3355
- * The list of the enclosing delimiters to identify the code blocks.
3356
- * For example, the delimiter ['```python\n', '\n```'] can be
3357
- * used to identify code blocks with the following format:
3358
- *
3359
- * ```python
3360
- * print("hello")
3361
- * ```
3264
+ * Constructor for BasicAuthCredential
3362
3265
  */
3363
- codeBlockDelimiters?: Array<[string, string]>;
3266
+ constructor(username: string, password: string);
3364
3267
  /**
3365
- * The delimiters to format the code execution result.
3268
+ * Gets the encoded basic auth token
3366
3269
  */
3367
- executionResultDelimiters?: [string, string];
3368
- }
3369
- declare abstract class BaseCodeExecutor {
3370
- protected readonly config: Required<BaseCodeExecutorConfig>;
3371
- constructor(config?: BaseCodeExecutorConfig);
3270
+ getToken(): string;
3372
3271
  /**
3373
- * Executes code and returns the code execution result.
3272
+ * Gets headers for HTTP requests
3374
3273
  */
3375
- abstract executeCode(invocationContext: InvocationContext, codeExecutionInput: CodeExecutionInput): Promise<CodeExecutionResult>;
3376
- get optimizeDataFile(): boolean;
3377
- get stateful(): boolean;
3378
- get errorRetryAttempts(): number;
3379
- get codeBlockDelimiters(): Array<[string, string]>;
3380
- get executionResultDelimiters(): [string, string];
3274
+ getHeaders(): Record<string, string>;
3381
3275
  }
3382
-
3383
3276
  /**
3384
- * Abstract base class for all planners.
3385
- *
3386
- * The planner allows the agent to generate plans for the queries to guide its action.
3277
+ * Bearer token credential
3387
3278
  */
3388
- declare abstract class BasePlanner {
3279
+ declare class BearerTokenCredential extends AuthCredential {
3389
3280
  /**
3390
- * Builds the system instruction to be appended to the LLM request for planning.
3391
- *
3392
- * @param readonlyContext The readonly context of the invocation
3393
- * @param llmRequest The LLM request. Readonly.
3394
- * @returns The planning system instruction, or undefined if no instruction is needed
3281
+ * The bearer token
3395
3282
  */
3396
- abstract buildPlanningInstruction(readonlyContext: ReadonlyContext, llmRequest: LlmRequest): string | undefined;
3283
+ token: string;
3397
3284
  /**
3398
- * Processes the LLM response for planning.
3399
- *
3400
- * @param callbackContext The callback context of the invocation
3401
- * @param responseParts The LLM response parts. Readonly.
3402
- * @returns The processed response parts, or undefined if no processing is needed
3285
+ * Constructor for BearerTokenCredential
3403
3286
  */
3404
- abstract processPlanningResponse(callbackContext: CallbackContext, responseParts: Part[]): Part[] | undefined;
3405
- }
3406
-
3407
- /**
3408
- * Type for instruction providers that can be functions
3409
- */
3410
- type InstructionProvider = (ctx: ReadonlyContext) => string | Promise<string>;
3411
- /**
3412
- * Union type for tools (supporting functions, tools, and toolsets)
3413
- */
3414
- type ToolUnion = BaseTool | ((...args: any[]) => any);
3415
- /**
3416
- * Configuration for LlmAgent
3417
- */
3418
- interface LlmAgentConfig<T extends BaseLlm = BaseLlm> {
3287
+ constructor(token: string);
3419
3288
  /**
3420
- * Name of the agent
3289
+ * Gets the bearer token
3421
3290
  */
3422
- name: string;
3291
+ getToken(): string;
3423
3292
  /**
3424
- * Description of the agent
3293
+ * Gets headers for HTTP requests
3425
3294
  */
3426
- description: string;
3295
+ getHeaders(): Record<string, string>;
3296
+ }
3297
+ /**
3298
+ * OAuth2 token credential with refresh capability
3299
+ */
3300
+ declare class OAuth2Credential extends AuthCredential {
3427
3301
  /**
3428
- * The LLM model to use
3429
- * When not set, the agent will inherit the model from its ancestor
3302
+ * The access token
3430
3303
  */
3431
- model?: string | T | LanguageModel;
3304
+ accessToken: string;
3432
3305
  /**
3433
- * Instructions for the LLM model, guiding the agent's behavior
3306
+ * The refresh token
3434
3307
  */
3435
- instruction?: string | InstructionProvider;
3308
+ refreshToken?: string;
3436
3309
  /**
3437
- * Instructions for all the agents in the entire agent tree
3438
- * ONLY the global_instruction in root agent will take effect
3310
+ * When the token expires
3439
3311
  */
3440
- globalInstruction?: string | InstructionProvider;
3312
+ expiresAt?: Date;
3441
3313
  /**
3442
- * Tools available to this agent
3314
+ * Function to refresh the token
3443
3315
  */
3444
- tools?: ToolUnion[];
3316
+ private refreshFunction?;
3445
3317
  /**
3446
- * Code executor for this agent
3318
+ * Constructor for OAuth2Credential
3447
3319
  */
3448
- codeExecutor?: BaseCodeExecutor;
3320
+ constructor(config: {
3321
+ accessToken: string;
3322
+ refreshToken?: string;
3323
+ expiresIn?: number;
3324
+ refreshFunction?: (refreshToken: string) => Promise<{
3325
+ accessToken: string;
3326
+ refreshToken?: string;
3327
+ expiresIn?: number;
3328
+ }>;
3329
+ });
3449
3330
  /**
3450
- * Disallows LLM-controlled transferring to the parent agent
3331
+ * Gets the access token
3451
3332
  */
3452
- disallowTransferToParent?: boolean;
3333
+ getToken(): string;
3453
3334
  /**
3454
- * Disallows LLM-controlled transferring to the peer agents
3335
+ * Gets headers for HTTP requests
3455
3336
  */
3456
- disallowTransferToPeers?: boolean;
3337
+ getHeaders(): Record<string, string>;
3457
3338
  /**
3458
- * Whether to include contents in the model request
3339
+ * Whether the token can be refreshed
3459
3340
  */
3460
- includeContents?: "default" | "none";
3341
+ canRefresh(): boolean;
3461
3342
  /**
3462
- * The output key in session state to store the output of the agent
3343
+ * Whether the token is expired
3463
3344
  */
3464
- outputKey?: string;
3345
+ isExpired(): boolean;
3465
3346
  /**
3466
- * Instructs the agent to make a plan and execute it step by step
3347
+ * Refreshes the token
3467
3348
  */
3468
- planner?: BasePlanner;
3349
+ refresh(): Promise<void>;
3350
+ }
3351
+
3352
+ /**
3353
+ * Models module exports - consolidated to match Python structure
3354
+ */
3355
+
3356
+ type index$5_AiSdkLlm = AiSdkLlm;
3357
+ declare const index$5_AiSdkLlm: typeof AiSdkLlm;
3358
+ type index$5_AnthropicLlm = AnthropicLlm;
3359
+ declare const index$5_AnthropicLlm: typeof AnthropicLlm;
3360
+ type index$5_ApiKeyCredential = ApiKeyCredential;
3361
+ declare const index$5_ApiKeyCredential: typeof ApiKeyCredential;
3362
+ type index$5_ApiKeyScheme = ApiKeyScheme;
3363
+ declare const index$5_ApiKeyScheme: typeof ApiKeyScheme;
3364
+ type index$5_AuthConfig = AuthConfig;
3365
+ declare const index$5_AuthConfig: typeof AuthConfig;
3366
+ type index$5_AuthCredential = AuthCredential;
3367
+ declare const index$5_AuthCredential: typeof AuthCredential;
3368
+ type index$5_AuthCredentialType = AuthCredentialType;
3369
+ declare const index$5_AuthCredentialType: typeof AuthCredentialType;
3370
+ type index$5_AuthHandler = AuthHandler;
3371
+ declare const index$5_AuthHandler: typeof AuthHandler;
3372
+ type index$5_AuthScheme = AuthScheme;
3373
+ declare const index$5_AuthScheme: typeof AuthScheme;
3374
+ type index$5_AuthSchemeType = AuthSchemeType;
3375
+ declare const index$5_AuthSchemeType: typeof AuthSchemeType;
3376
+ type index$5_BaseLLMConnection = BaseLLMConnection;
3377
+ declare const index$5_BaseLLMConnection: typeof BaseLLMConnection;
3378
+ type index$5_BaseLlm = BaseLlm;
3379
+ declare const index$5_BaseLlm: typeof BaseLlm;
3380
+ type index$5_BaseMemoryService = BaseMemoryService;
3381
+ type index$5_BasicAuthCredential = BasicAuthCredential;
3382
+ declare const index$5_BasicAuthCredential: typeof BasicAuthCredential;
3383
+ type index$5_BearerTokenCredential = BearerTokenCredential;
3384
+ declare const index$5_BearerTokenCredential: typeof BearerTokenCredential;
3385
+ declare const index$5_Blob: typeof Blob;
3386
+ declare const index$5_Content: typeof Content;
3387
+ declare const index$5_FunctionDeclaration: typeof FunctionDeclaration;
3388
+ type index$5_GoogleLlm = GoogleLlm;
3389
+ declare const index$5_GoogleLlm: typeof GoogleLlm;
3390
+ type index$5_HttpScheme = HttpScheme;
3391
+ declare const index$5_HttpScheme: typeof HttpScheme;
3392
+ type index$5_LLMRegistry = LLMRegistry;
3393
+ declare const index$5_LLMRegistry: typeof LLMRegistry;
3394
+ type index$5_LlmRequest = LlmRequest;
3395
+ declare const index$5_LlmRequest: typeof LlmRequest;
3396
+ type index$5_LlmResponse = LlmResponse;
3397
+ declare const index$5_LlmResponse: typeof LlmResponse;
3398
+ type index$5_OAuth2Credential = OAuth2Credential;
3399
+ declare const index$5_OAuth2Credential: typeof OAuth2Credential;
3400
+ type index$5_OAuth2Scheme = OAuth2Scheme;
3401
+ declare const index$5_OAuth2Scheme: typeof OAuth2Scheme;
3402
+ type index$5_OAuthFlow = OAuthFlow;
3403
+ type index$5_OAuthFlows = OAuthFlows;
3404
+ type index$5_OpenAiLlm = OpenAiLlm;
3405
+ declare const index$5_OpenAiLlm: typeof OpenAiLlm;
3406
+ type index$5_OpenIdConnectScheme = OpenIdConnectScheme;
3407
+ declare const index$5_OpenIdConnectScheme: typeof OpenIdConnectScheme;
3408
+ type index$5_SearchMemoryResponse = SearchMemoryResponse;
3409
+ type index$5_Session = Session;
3410
+ type index$5_State = State;
3411
+ declare const index$5_State: typeof State;
3412
+ type index$5_ThinkingConfig = ThinkingConfig;
3413
+ declare const index$5_registerProviders: typeof registerProviders;
3414
+ declare namespace index$5 {
3415
+ export { index$5_AiSdkLlm as AiSdkLlm, index$5_AnthropicLlm as AnthropicLlm, index$5_ApiKeyCredential as ApiKeyCredential, index$5_ApiKeyScheme as ApiKeyScheme, index$5_AuthConfig as AuthConfig, index$5_AuthCredential as AuthCredential, index$5_AuthCredentialType as AuthCredentialType, index$5_AuthHandler as AuthHandler, index$5_AuthScheme as AuthScheme, index$5_AuthSchemeType as AuthSchemeType, index$5_BaseLLMConnection as BaseLLMConnection, index$5_BaseLlm as BaseLlm, type index$5_BaseMemoryService as BaseMemoryService, index$5_BasicAuthCredential as BasicAuthCredential, index$5_BearerTokenCredential as BearerTokenCredential, index$5_Blob as Blob, index$5_Content as Content, index$5_FunctionDeclaration as FunctionDeclaration, index$5_GoogleLlm as GoogleLlm, index$5_HttpScheme as HttpScheme, Schema as JSONSchema, index$5_LLMRegistry as LLMRegistry, index$5_LlmRequest as LlmRequest, index$5_LlmResponse as LlmResponse, index$5_OAuth2Credential as OAuth2Credential, index$5_OAuth2Scheme as OAuth2Scheme, type index$5_OAuthFlow as OAuthFlow, type index$5_OAuthFlows as OAuthFlows, index$5_OpenAiLlm as OpenAiLlm, index$5_OpenIdConnectScheme as OpenIdConnectScheme, type index$5_SearchMemoryResponse as SearchMemoryResponse, type index$5_Session as Session, index$5_State as State, type index$5_ThinkingConfig as ThinkingConfig, index$5_registerProviders as registerProviders };
3416
+ }
3417
+
3418
+ /**
3419
+ * Options for creating an Event.
3420
+ */
3421
+ interface EventOpts {
3422
+ invocationId?: string;
3423
+ author: string;
3424
+ actions?: EventActions;
3425
+ longRunningToolIds?: Set<string>;
3426
+ branch?: string;
3427
+ id?: string;
3428
+ timestamp?: number;
3429
+ content?: any;
3430
+ partial?: boolean;
3431
+ }
3432
+ /**
3433
+ * Represents an event in a conversation between agents and users.
3434
+ * It is used to store the content of the conversation, as well as the actions
3435
+ * taken by the agents like function calls, etc.
3436
+ */
3437
+ declare class Event extends LlmResponse {
3438
+ /** The invocation ID of the event. */
3439
+ invocationId: string;
3440
+ /** 'user' or the name of the agent, indicating who appended the event to the session. */
3441
+ author: string;
3442
+ /** The actions taken by the agent. */
3443
+ actions: EventActions;
3469
3444
  /**
3470
- * Memory service for long-term storage and retrieval
3445
+ * Set of ids of the long running function calls.
3446
+ * Agent client will know from this field about which function call is long running.
3447
+ * Only valid for function call event.
3471
3448
  */
3472
- memoryService?: BaseMemoryService;
3449
+ longRunningToolIds?: Set<string>;
3473
3450
  /**
3474
- * Session service for managing conversations
3451
+ * The branch of the event.
3452
+ * The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
3453
+ * agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple
3454
+ * sub-agents shouldn't see their peer agents' conversation history.
3475
3455
  */
3476
- sessionService?: BaseSessionService;
3456
+ branch?: string;
3457
+ /** The unique identifier of the event. */
3458
+ id: string;
3459
+ /** The timestamp of the event (seconds since epoch). */
3460
+ timestamp: number;
3477
3461
  /**
3478
- * Artifact service for file storage and management
3462
+ * Constructor for Event.
3479
3463
  */
3480
- artifactService?: BaseArtifactService;
3464
+ constructor(opts: EventOpts);
3481
3465
  /**
3482
- * User ID for the session
3466
+ * Returns whether the event is the final response of the agent.
3483
3467
  */
3484
- userId?: string;
3468
+ isFinalResponse(): boolean;
3485
3469
  /**
3486
- * Application name
3470
+ * Returns the function calls in the event.
3487
3471
  */
3488
- appName?: string;
3472
+ getFunctionCalls(): any[];
3489
3473
  /**
3490
- * Additional content generation configurations
3491
- * NOTE: not all fields are usable, e.g. tools must be configured via `tools`,
3492
- * thinking_config must be configured via `planner` in LlmAgent.
3474
+ * Returns the function responses in the event.
3493
3475
  */
3494
- generateContentConfig?: GenerateContentConfig;
3476
+ getFunctionResponses(): any[];
3495
3477
  /**
3496
- * The input schema when agent is used as a tool
3478
+ * Returns whether the event has a trailing code execution result.
3497
3479
  */
3498
- inputSchema?: any;
3480
+ hasTrailingCodeExecutionResult(): boolean;
3499
3481
  /**
3500
- * The output schema when agent replies
3501
- * NOTE: when this is set, agent can ONLY reply and CANNOT use any tools
3482
+ * Generates a new random ID for an event.
3502
3483
  */
3503
- outputSchema?: any;
3484
+ static newId(): string;
3504
3485
  }
3486
+
3505
3487
  /**
3506
- * LLM-based Agent
3488
+ * Single agent callback type
3507
3489
  */
3508
- declare class LlmAgent<T extends BaseLlm = BaseLlm> extends BaseAgent {
3509
- /**
3510
- * The model to use for the agent
3511
- * When not set, the agent will inherit the model from its ancestor
3512
- */
3513
- model: string | T | LanguageModel;
3514
- /**
3515
- * Instructions for the LLM model, guiding the agent's behavior
3516
- */
3517
- instruction: string | InstructionProvider;
3518
- /**
3519
- * Instructions for all the agents in the entire agent tree
3520
- * ONLY the global_instruction in root agent will take effect
3521
- */
3522
- globalInstruction: string | InstructionProvider;
3490
+ type SingleAgentCallback = (callbackContext: CallbackContext) => Promise<Content | undefined> | Content | undefined;
3491
+ /**
3492
+ * Before agent callback type
3493
+ */
3494
+ type BeforeAgentCallback = SingleAgentCallback | SingleAgentCallback[];
3495
+ /**
3496
+ * After agent callback type
3497
+ */
3498
+ type AfterAgentCallback = SingleAgentCallback | SingleAgentCallback[];
3499
+ /**
3500
+ * Base class for all agents in Agent Development Kit.
3501
+ */
3502
+ declare abstract class BaseAgent {
3523
3503
  /**
3524
- * Tools available to this agent
3504
+ * The agent's name.
3505
+ * Agent name must be a valid identifier and unique within the agent tree.
3506
+ * Agent name cannot be "user", since it's reserved for end-user's input.
3525
3507
  */
3526
- tools: ToolUnion[];
3508
+ name: string;
3527
3509
  /**
3528
- * Code executor for this agent
3510
+ * Description about the agent's capability.
3511
+ * The model uses this to determine whether to delegate control to the agent.
3512
+ * One-line description is enough and preferred.
3529
3513
  */
3530
- codeExecutor?: BaseCodeExecutor;
3514
+ description: string;
3531
3515
  /**
3532
- * Disallows LLM-controlled transferring to the parent agent
3516
+ * The parent agent of this agent.
3517
+ * Note that an agent can ONLY be added as sub-agent once.
3518
+ * If you want to add one agent twice as sub-agent, consider to create two agent
3519
+ * instances with identical config, but with different name and add them to the
3520
+ * agent tree.
3533
3521
  */
3534
- disallowTransferToParent: boolean;
3522
+ parentAgent?: BaseAgent;
3535
3523
  /**
3536
- * Disallows LLM-controlled transferring to the peer agents
3524
+ * The sub-agents of this agent.
3537
3525
  */
3538
- disallowTransferToPeers: boolean;
3526
+ subAgents: BaseAgent[];
3539
3527
  /**
3540
- * Whether to include contents in the model request
3528
+ * Callback or list of callbacks to be invoked before the agent run.
3529
+ * When a list of callbacks is provided, the callbacks will be called in the
3530
+ * order they are listed until a callback does not return undefined.
3531
+ *
3532
+ * Args:
3533
+ * callbackContext: The callback context.
3534
+ *
3535
+ * Returns:
3536
+ * Content | undefined: The content to return to the user.
3537
+ * When the content is present, the agent run will be skipped and the
3538
+ * provided content will be returned to user.
3541
3539
  */
3542
- includeContents: "default" | "none";
3540
+ beforeAgentCallback?: BeforeAgentCallback;
3543
3541
  /**
3544
- * The output key in session state to store the output of the agent
3542
+ * Callback or list of callbacks to be invoked after the agent run.
3543
+ * When a list of callbacks is provided, the callbacks will be called in the
3544
+ * order they are listed until a callback does not return undefined.
3545
+ *
3546
+ * Args:
3547
+ * callbackContext: The callback context.
3548
+ *
3549
+ * Returns:
3550
+ * Content | undefined: The content to return to the user.
3551
+ * When the content is present, the provided content will be used as agent
3552
+ * response and appended to event history as agent response.
3545
3553
  */
3546
- outputKey?: string;
3554
+ afterAgentCallback?: AfterAgentCallback;
3547
3555
  /**
3548
- * Instructs the agent to make a plan and execute it step by step
3556
+ * Constructor for BaseAgent
3549
3557
  */
3550
- planner?: BasePlanner;
3558
+ constructor(config: {
3559
+ name: string;
3560
+ description?: string;
3561
+ subAgents?: BaseAgent[];
3562
+ beforeAgentCallback?: BeforeAgentCallback;
3563
+ afterAgentCallback?: AfterAgentCallback;
3564
+ });
3551
3565
  /**
3552
- * Memory service for long-term storage and retrieval
3566
+ * Entry method to run an agent via text-based conversation.
3553
3567
  */
3554
- private memoryService?;
3568
+ runAsync(parentContext: InvocationContext): AsyncGenerator<Event, void, unknown>;
3555
3569
  /**
3556
- * Session service for managing conversations
3570
+ * Entry method to run an agent via video/audio-based conversation.
3557
3571
  */
3558
- private sessionService?;
3572
+ runLive(parentContext: InvocationContext): AsyncGenerator<Event, void, unknown>;
3559
3573
  /**
3560
- * Artifact service for file storage and management
3574
+ * Internal implementation for runAsync
3561
3575
  */
3562
- private artifactService?;
3576
+ private runAsyncInternal;
3563
3577
  /**
3564
- * User ID for the session
3578
+ * Internal implementation for runLive
3565
3579
  */
3566
- private userId?;
3580
+ private runLiveInternal;
3567
3581
  /**
3568
- * Application name
3582
+ * Core logic to run this agent via text-based conversation.
3583
+ *
3584
+ * @param ctx - The invocation context for this agent.
3585
+ * @yields Event - The events generated by the agent.
3569
3586
  */
3570
- private appName?;
3587
+ protected runAsyncImpl(_ctx: InvocationContext): AsyncGenerator<Event, void, unknown>;
3571
3588
  /**
3572
- * Additional content generation configurations
3589
+ * Core logic to run this agent via video/audio-based conversation.
3590
+ *
3591
+ * @param ctx - The invocation context for this agent.
3592
+ * @yields Event - The events generated by the agent.
3573
3593
  */
3574
- generateContentConfig?: GenerateContentConfig;
3594
+ protected runLiveImpl(_ctx: InvocationContext): AsyncGenerator<Event, void, unknown>;
3575
3595
  /**
3576
- * The input schema when agent is used as a tool
3596
+ * Gets the root agent of this agent.
3577
3597
  */
3578
- inputSchema?: any;
3598
+ get rootAgent(): BaseAgent;
3579
3599
  /**
3580
- * The output schema when agent replies
3600
+ * Finds the agent with the given name in this agent and its descendants.
3601
+ *
3602
+ * @param name - The name of the agent to find.
3603
+ * @returns The agent with the matching name, or undefined if no such agent is found.
3581
3604
  */
3582
- outputSchema?: any;
3583
- protected logger: Logger;
3605
+ findAgent(name: string): BaseAgent | undefined;
3584
3606
  /**
3585
- * Constructor for LlmAgent
3607
+ * Finds the agent with the given name in this agent's descendants.
3608
+ *
3609
+ * @param name - The name of the agent to find.
3610
+ * @returns The agent with the matching name, or undefined if no such agent is found.
3586
3611
  */
3587
- constructor(config: LlmAgentConfig<T>);
3612
+ findSubAgent(name: string): BaseAgent | undefined;
3588
3613
  /**
3589
- * The resolved model field as BaseLLM
3590
- * This method is only for use by Agent Development Kit
3614
+ * Creates a new invocation context for this agent.
3591
3615
  */
3592
- get canonicalModel(): BaseLlm;
3616
+ private createInvocationContext;
3593
3617
  /**
3594
- * The resolved instruction field to construct instruction for this agent
3595
- * This method is only for use by Agent Development Kit
3618
+ * The resolved beforeAgentCallback field as a list of SingleAgentCallback.
3619
+ * This method is only for use by Agent Development Kit.
3596
3620
  */
3597
- canonicalInstruction(ctx: ReadonlyContext): Promise<[string, boolean]>;
3621
+ get canonicalBeforeAgentCallbacks(): SingleAgentCallback[];
3598
3622
  /**
3599
- * The resolved global_instruction field to construct global instruction
3600
- * This method is only for use by Agent Development Kit
3623
+ * The resolved afterAgentCallback field as a list of SingleAgentCallback.
3624
+ * This method is only for use by Agent Development Kit.
3601
3625
  */
3602
- canonicalGlobalInstruction(ctx: ReadonlyContext): Promise<[string, boolean]>;
3626
+ get canonicalAfterAgentCallbacks(): SingleAgentCallback[];
3603
3627
  /**
3604
- * The resolved tools field as a list of BaseTool based on the context
3605
- * This method is only for use by Agent Development Kit
3628
+ * Runs the beforeAgentCallback if it exists.
3629
+ *
3630
+ * @returns An event if callback provides content or changed state.
3606
3631
  */
3607
- canonicalTools(ctx?: ReadonlyContext): Promise<BaseTool[]>;
3632
+ private handleBeforeAgentCallback;
3608
3633
  /**
3609
- * Gets the appropriate LLM flow for this agent
3610
- * This matches the Python implementation's _llm_flow property
3634
+ * Runs the afterAgentCallback if it exists.
3635
+ *
3636
+ * @returns An event if callback provides content or changed state.
3611
3637
  */
3612
- private get llmFlow();
3638
+ private handleAfterAgentCallback;
3613
3639
  /**
3614
- * Saves the model output to state if needed
3615
- * This matches the Python implementation's __maybe_save_output_to_state
3640
+ * Validates the agent name.
3616
3641
  */
3617
- private maybeSaveOutputToState;
3642
+ private validateName;
3618
3643
  /**
3619
- * Core logic to run this agent via text-based conversation
3620
- * This matches the Python implementation's _run_async_impl
3644
+ * Sets parent agent for sub-agents.
3621
3645
  */
3622
- protected runAsyncImpl(context: InvocationContext): AsyncGenerator<Event, void, unknown>;
3646
+ private setParentAgentForSubAgents;
3623
3647
  }
3624
3648
 
3625
3649
  /**
@@ -3895,10 +3919,12 @@ interface AgentBuilderConfig {
3895
3919
  instruction?: string;
3896
3920
  tools?: BaseTool[];
3897
3921
  planner?: BasePlanner;
3922
+ codeExecutor?: BaseCodeExecutor;
3898
3923
  subAgents?: BaseAgent[];
3899
3924
  maxIterations?: number;
3900
3925
  nodes?: LangGraphNode[];
3901
3926
  rootNode?: string;
3927
+ outputKey?: string;
3902
3928
  }
3903
3929
  /**
3904
3930
  * Session configuration options
@@ -3906,6 +3932,8 @@ interface AgentBuilderConfig {
3906
3932
  interface SessionOptions {
3907
3933
  userId?: string;
3908
3934
  appName?: string;
3935
+ state?: Record<string, any>;
3936
+ sessionId?: string;
3909
3937
  }
3910
3938
  /**
3911
3939
  * Message part interface for flexible message input
@@ -3916,7 +3944,7 @@ interface MessagePart extends Part {
3916
3944
  /**
3917
3945
  * Full message interface for advanced usage
3918
3946
  */
3919
- interface FullMessage extends Content$1 {
3947
+ interface FullMessage extends Content {
3920
3948
  parts?: MessagePart[];
3921
3949
  }
3922
3950
  /**
@@ -3962,13 +3990,21 @@ type AgentType = "llm" | "sequential" | "parallel" | "loop" | "langgraph";
3962
3990
  * .withInstruction("You are a research assistant")
3963
3991
  * .build();
3964
3992
  *
3993
+ * // With code executor for running code
3994
+ * const { runner } = await AgentBuilder
3995
+ * .create("code-agent")
3996
+ * .withModel("gemini-2.5-flash")
3997
+ * .withCodeExecutor(new ContainerCodeExecutor())
3998
+ * .withInstruction("You can execute code to solve problems")
3999
+ * .build();
4000
+ *
3965
4001
  * // With memory and artifact services
3966
4002
  * const { runner } = await AgentBuilder
3967
4003
  * .create("persistent-agent")
3968
4004
  * .withModel("gemini-2.5-flash")
3969
4005
  * .withMemory(new RedisMemoryService())
3970
4006
  * .withArtifactService(new S3ArtifactService())
3971
- * .withSession(new DatabaseSessionService(), { userId: "user123", appName: "myapp" })
4007
+ * .withSessionService(new DatabaseSessionService(), { userId: "user123", appName: "myapp" })
3972
4008
  * .build();
3973
4009
  *
3974
4010
  * // Multi-agent workflow
@@ -3980,10 +4016,12 @@ type AgentType = "llm" | "sequential" | "parallel" | "loop" | "langgraph";
3980
4016
  */
3981
4017
  declare class AgentBuilder {
3982
4018
  private config;
3983
- private sessionConfig?;
4019
+ private sessionService?;
4020
+ private sessionOptions?;
3984
4021
  private memoryService?;
3985
4022
  private artifactService?;
3986
4023
  private agentType;
4024
+ private existingSession?;
3987
4025
  /**
3988
4026
  * Private constructor - use static create() method
3989
4027
  */
@@ -4030,6 +4068,18 @@ declare class AgentBuilder {
4030
4068
  * @returns This builder instance for chaining
4031
4069
  */
4032
4070
  withPlanner(planner: BasePlanner): this;
4071
+ /**
4072
+ * Set the code executor for the agent
4073
+ * @param codeExecutor The code executor to use for running code
4074
+ * @returns This builder instance for chaining
4075
+ */
4076
+ withCodeExecutor(codeExecutor: BaseCodeExecutor): this;
4077
+ /**
4078
+ * Set the output key for the agent
4079
+ * @param outputKey The output key in session state to store the output of the agent
4080
+ * @returns This builder instance for chaining
4081
+ */
4082
+ withOutputKey(outputKey: string): this;
4033
4083
  /**
4034
4084
  * Configure as a sequential agent
4035
4085
  * @param subAgents Sub-agents to execute in sequence
@@ -4062,7 +4112,14 @@ declare class AgentBuilder {
4062
4112
  * @param options Session configuration options (userId and appName)
4063
4113
  * @returns This builder instance for chaining
4064
4114
  */
4065
- withSession(service: BaseSessionService, options?: SessionOptions): this;
4115
+ withSessionService(service: BaseSessionService, options?: SessionOptions): this;
4116
+ /**
4117
+ * Configure with an existing session instance
4118
+ * @param session Existing session to use
4119
+ * @returns This builder instance for chaining
4120
+ * @throws Error if no session service has been configured via withSessionService()
4121
+ */
4122
+ withSession(session: Session): this;
4066
4123
  /**
4067
4124
  * Configure memory service for the agent
4068
4125
  * @param memoryService Memory service to use for conversation history and context
@@ -4782,7 +4839,7 @@ declare function populateClientFunctionCallId(modelResponseEvent: Event): void;
4782
4839
  /**
4783
4840
  * Removes client function call IDs from content
4784
4841
  */
4785
- declare function removeClientFunctionCallId(content: Content$1): void;
4842
+ declare function removeClientFunctionCallId(content: Content): void;
4786
4843
  /**
4787
4844
  * Gets long running function call IDs from a list of function calls
4788
4845
  */
@@ -4990,7 +5047,7 @@ declare class Runner<T extends BaseAgent = BaseAgent> {
4990
5047
  run({ userId, sessionId, newMessage, runConfig, }: {
4991
5048
  userId: string;
4992
5049
  sessionId: string;
4993
- newMessage: Content$1;
5050
+ newMessage: Content;
4994
5051
  runConfig?: RunConfig;
4995
5052
  }): Generator<Event, void, unknown>;
4996
5053
  /**
@@ -4999,7 +5056,7 @@ declare class Runner<T extends BaseAgent = BaseAgent> {
4999
5056
  runAsync({ userId, sessionId, newMessage, runConfig, }: {
5000
5057
  userId: string;
5001
5058
  sessionId: string;
5002
- newMessage: Content$1;
5059
+ newMessage: Content;
5003
5060
  runConfig?: RunConfig;
5004
5061
  }): AsyncGenerator<Event, void, unknown>;
5005
5062
  /**
@@ -5107,4 +5164,4 @@ declare const traceLlmCall: (invocationContext: InvocationContext, eventId: stri
5107
5164
 
5108
5165
  declare const VERSION = "0.1.0";
5109
5166
 
5110
- export { AF_FUNCTION_CALL_ID_PREFIX, type AfterAgentCallback, LlmAgent as Agent, AgentBuilder, type AgentBuilderConfig, type AgentType, index$4 as Agents, AiSdkLlm, AnthropicLlm, ApiKeyCredential, ApiKeyScheme, AuthConfig, AuthCredential, AuthCredentialType, AuthHandler, AuthScheme, AuthSchemeType, AuthTool, type AuthToolArguments, AutoFlow, BaseAgent, BaseCodeExecutor, type BaseCodeExecutorConfig, BaseLLMConnection, BaseLlm, BaseLlmFlow, BaseLlmRequestProcessor, BaseLlmResponseProcessor, type BaseMemoryService, BasePlanner, BaseSessionService, BaseTool, BasicAuthCredential, BearerTokenCredential, type BeforeAgentCallback, type BuildFunctionDeclarationOptions, type BuiltAgent, BuiltInCodeExecutor, BuiltInPlanner, CallbackContext, type CodeExecutionInput, type CodeExecutionResult, CodeExecutionUtils, CodeExecutorContext, type CreateToolConfig, type CreateToolConfigWithSchema, type CreateToolConfigWithoutSchema, DatabaseSessionService, EnhancedAuthConfig, type EnhancedRunner, Event, EventActions, index$1 as Events, ExitLoopTool, type File, FileOperationsTool, index as Flows, type FullMessage, type FunctionDeclaration, FunctionTool, GcsArtifactService, type GetSessionConfig, GetUserChoiceTool, GoogleLlm, GoogleSearch, HttpRequestTool, HttpScheme, InMemoryArtifactService, InMemoryMemoryService, InMemoryRunner, InMemorySessionService, type InstructionProvider, InvocationContext, type JSONSchema, LLMRegistry, LangGraphAgent, type LangGraphAgentConfig, type LangGraphNode, type ListSessionsResponse, LlmAgent, type LlmAgentConfig, LlmCallsLimitExceededError, LlmRequest, LlmResponse, LoadArtifactsTool, LoadMemoryTool, LoopAgent, type LoopAgentConfig, McpAbi, McpAtp, McpBamm, McpCoinGecko, type McpConfig, McpDiscord, McpError, McpErrorType, McpFilesystem, McpFraxlend, McpGeneric, McpIqWiki, McpMemory, McpNearAgent, McpNearIntentSwaps, McpOdos, McpSamplingHandler, type McpSamplingRequest, type McpSamplingResponse, type McpServerConfig, McpTelegram, McpToolset, type McpTransportType, index$3 as Memory, type MessagePart, index$5 as Models, OAuth2Credential, OAuth2Scheme, type OAuthFlow, type OAuthFlows, OpenAiLlm, OpenIdConnectScheme, ParallelAgent, type ParallelAgentConfig, PlanReActPlanner, REQUEST_EUC_FUNCTION_CALL_NAME, ReadonlyContext, RunConfig, Runner, type SamplingHandler, type SearchMemoryResponse, SequentialAgent, type SequentialAgentConfig, type Session, type SessionOptions, index$2 as Sessions, type SingleAgentCallback, SingleFlow, State, StreamingMode, type TelemetryConfig, TelemetryService, type ThinkingConfig, type ToolConfig, ToolContext, type ToolUnion, index$6 as Tools, TransferToAgentTool, UserInteractionTool, VERSION, VertexAiSessionService, _findFunctionCallEventIfLastEventIsFunctionResponse, adkToMcpToolType, requestProcessor$2 as agentTransferRequestProcessor, requestProcessor$6 as basicRequestProcessor, buildFunctionDeclaration, requestProcessor as codeExecutionRequestProcessor, responseProcessor as codeExecutionResponseProcessor, requestProcessor$3 as contentRequestProcessor, createAuthToolArguments, createBranchContextForSubAgent, createDatabaseSessionService, createFunctionTool, createMysqlSessionService, createPostgresSessionService, createSamplingHandler, createSqliteSessionService, createTool, generateAuthEvent, generateClientFunctionCallId, getLongRunningFunctionCalls, getMcpTools, handleFunctionCallsAsync, handleFunctionCallsLive, requestProcessor$5 as identityRequestProcessor, initializeTelemetry, injectSessionState, requestProcessor$4 as instructionsRequestProcessor, isEnhancedAuthConfig, jsonSchemaToDeclaration, mcpSchemaToParameters, mergeAgentRun, mergeParallelFunctionResponseEvents, newInvocationContextId, requestProcessor$1 as nlPlanningRequestProcessor, responseProcessor$1 as nlPlanningResponseProcessor, normalizeJsonSchema, populateClientFunctionCallId, registerProviders, removeClientFunctionCallId, requestProcessor$7 as requestProcessor, shutdownTelemetry, telemetryService, traceLlmCall, traceToolCall, tracer };
5167
+ export { AF_FUNCTION_CALL_ID_PREFIX, type AfterAgentCallback, LlmAgent as Agent, AgentBuilder, type AgentBuilderConfig, AgentTool, type AgentToolConfig, type AgentType, index$4 as Agents, AiSdkLlm, AnthropicLlm, ApiKeyCredential, ApiKeyScheme, AuthConfig, AuthCredential, AuthCredentialType, AuthHandler, AuthScheme, AuthSchemeType, AuthTool, type AuthToolArguments, AutoFlow, BaseAgent, type BaseAgentType, BaseCodeExecutor, type BaseCodeExecutorConfig, BaseLLMConnection, BaseLlm, BaseLlmFlow, BaseLlmRequestProcessor, BaseLlmResponseProcessor, type BaseMemoryService, BasePlanner, BaseSessionService, BaseTool, BasicAuthCredential, BearerTokenCredential, type BeforeAgentCallback, type BuildFunctionDeclarationOptions, type BuiltAgent, BuiltInCodeExecutor, BuiltInPlanner, CallbackContext, type CodeExecutionInput, type CodeExecutionResult, CodeExecutionUtils, CodeExecutorContext, type CreateToolConfig, type CreateToolConfigWithSchema, type CreateToolConfigWithoutSchema, DatabaseSessionService, EnhancedAuthConfig, type EnhancedRunner, Event, EventActions, index$1 as Events, ExitLoopTool, type File, FileOperationsTool, index as Flows, type FullMessage, FunctionTool, GcsArtifactService, type GetSessionConfig, GetUserChoiceTool, GoogleLlm, GoogleSearch, HttpRequestTool, HttpScheme, InMemoryArtifactService, InMemoryMemoryService, InMemoryRunner, InMemorySessionService, type InstructionProvider, InvocationContext, LLMRegistry, LangGraphAgent, type LangGraphAgentConfig, type LangGraphNode, type ListSessionsResponse, LlmAgent, type LlmAgentConfig, LlmCallsLimitExceededError, LlmRequest, LlmResponse, LoadArtifactsTool, LoadMemoryTool, LoopAgent, type LoopAgentConfig, McpAbi, McpAtp, McpBamm, McpCoinGecko, type McpConfig, McpDiscord, McpError, McpErrorType, McpFilesystem, McpFraxlend, McpGeneric, McpIqWiki, McpMemory, McpNearAgent, McpNearIntents, McpOdos, McpSamplingHandler, type McpSamplingRequest, type McpSamplingResponse, type McpServerConfig, McpTelegram, McpToolset, type McpTransportType, index$3 as Memory, type MessagePart, index$5 as Models, OAuth2Credential, OAuth2Scheme, type OAuthFlow, type OAuthFlows, OpenAiLlm, OpenIdConnectScheme, ParallelAgent, type ParallelAgentConfig, PlanReActPlanner, REQUEST_EUC_FUNCTION_CALL_NAME, ReadonlyContext, RunConfig, Runner, type SamplingHandler, type SearchMemoryResponse, SequentialAgent, type SequentialAgentConfig, type Session, type SessionOptions, index$2 as Sessions, type SingleAgentCallback, SingleFlow, State, StreamingMode, type TelemetryConfig, TelemetryService, type ThinkingConfig, type ToolConfig, ToolContext, type ToolUnion, index$6 as Tools, TransferToAgentTool, UserInteractionTool, VERSION, VertexAiSessionService, _findFunctionCallEventIfLastEventIsFunctionResponse, adkToMcpToolType, requestProcessor$2 as agentTransferRequestProcessor, requestProcessor$6 as basicRequestProcessor, buildFunctionDeclaration, requestProcessor as codeExecutionRequestProcessor, responseProcessor as codeExecutionResponseProcessor, requestProcessor$3 as contentRequestProcessor, createAuthToolArguments, createBranchContextForSubAgent, createDatabaseSessionService, createFunctionTool, createMysqlSessionService, createPostgresSessionService, createSamplingHandler, createSqliteSessionService, createTool, generateAuthEvent, generateClientFunctionCallId, getLongRunningFunctionCalls, getMcpTools, handleFunctionCallsAsync, handleFunctionCallsLive, requestProcessor$5 as identityRequestProcessor, initializeTelemetry, injectSessionState, requestProcessor$4 as instructionsRequestProcessor, isEnhancedAuthConfig, jsonSchemaToDeclaration, mcpSchemaToParameters, mergeAgentRun, mergeParallelFunctionResponseEvents, newInvocationContextId, requestProcessor$1 as nlPlanningRequestProcessor, responseProcessor$1 as nlPlanningResponseProcessor, normalizeJsonSchema, populateClientFunctionCallId, registerProviders, removeClientFunctionCallId, requestProcessor$7 as requestProcessor, shutdownTelemetry, telemetryService, traceLlmCall, traceToolCall, tracer };