* Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool. * Handles arg parsing, subscriber notifications, handler invocation, result stringification, * and error handling.
({
tool,
toolCall,
agent,
agentId,
handlerArgs,
toolType,
messageId,
}: {
tool: FrontendTool<any>;
toolCall: { id: string; function: { name: string; arguments: string } };
agent: AbstractAgent;
agentId: string;
handlerArgs: unknown;
toolType: string;
messageId?: string;
})
| 487 | * and error handling. |
| 488 | */ |
| 489 | private async executeToolHandler({ |
| 490 | tool, |
| 491 | toolCall, |
| 492 | agent, |
| 493 | agentId, |
| 494 | handlerArgs, |
| 495 | toolType, |
| 496 | messageId, |
| 497 | }: { |
| 498 | tool: FrontendTool<any>; |
| 499 | toolCall: { id: string; function: { name: string; arguments: string } }; |
| 500 | agent: AbstractAgent; |
| 501 | agentId: string; |
| 502 | handlerArgs: unknown; |
| 503 | toolType: string; |
| 504 | messageId?: string; |
| 505 | }): Promise<ExecuteToolHandlerResult> { |
| 506 | let toolCallResult = ""; |
| 507 | let errorMessage: string | undefined; |
| 508 | let isArgumentError = false; |
| 509 | |
| 510 | let parsedArgs: unknown; |
| 511 | try { |
| 512 | parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name); |
| 513 | } catch (error) { |
| 514 | const parseError = |
| 515 | error instanceof Error ? error : new Error(String(error)); |
| 516 | errorMessage = parseError.message; |
| 517 | isArgumentError = true; |
| 518 | await this._internal.emitError({ |
| 519 | error: parseError, |
| 520 | code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED, |
| 521 | context: { |
| 522 | agentId, |
| 523 | toolCallId: toolCall.id, |
| 524 | toolName: toolCall.function.name, |
| 525 | rawArguments: handlerArgs, |
| 526 | toolType, |
| 527 | ...(messageId ? { messageId } : {}), |
| 528 | }, |
| 529 | }); |
| 530 | } |
| 531 | |
| 532 | await this._internal.notifySubscribers( |
| 533 | (subscriber) => |
| 534 | subscriber.onToolExecutionStart?.({ |
| 535 | copilotkit: this.core, |
| 536 | toolCallId: toolCall.id, |
| 537 | agentId, |
| 538 | toolName: toolCall.function.name, |
| 539 | args: parsedArgs, |
| 540 | }), |
| 541 | "Subscriber onToolExecutionStart error:", |
| 542 | ); |
| 543 | |
| 544 | if (!errorMessage) { |
| 545 | try { |
| 546 | const result = await tool.handler!(parsedArgs as any, { |
no test coverage detected