* Executes a tool handler and sends the result back via RPC. * @internal
(
requestId: string,
toolName: string,
toolCallId: string,
args: unknown,
handler: ToolHandler,
traceparent?: string,
tracestate?: string
)
| 597 | * @internal |
| 598 | */ |
| 599 | private async _executeToolAndRespond( |
| 600 | requestId: string, |
| 601 | toolName: string, |
| 602 | toolCallId: string, |
| 603 | args: unknown, |
| 604 | handler: ToolHandler, |
| 605 | traceparent?: string, |
| 606 | tracestate?: string |
| 607 | ): Promise<void> { |
| 608 | try { |
| 609 | const rawResult = await handler(args, { |
| 610 | sessionId: this.sessionId, |
| 611 | toolCallId, |
| 612 | toolName, |
| 613 | arguments: args, |
| 614 | traceparent, |
| 615 | tracestate, |
| 616 | }); |
| 617 | let result: ToolResult; |
| 618 | if (rawResult == null) { |
| 619 | result = ""; |
| 620 | } else if (typeof rawResult === "string") { |
| 621 | result = rawResult; |
| 622 | } else if (isToolResultObject(rawResult)) { |
| 623 | result = rawResult; |
| 624 | } else { |
| 625 | result = JSON.stringify(rawResult); |
| 626 | } |
| 627 | if (this.disconnected) { |
| 628 | return; |
| 629 | } |
| 630 | await this.rpc.tools.handlePendingToolCall({ requestId, result }); |
| 631 | } catch (error) { |
| 632 | if (this.disconnected) { |
| 633 | return; |
| 634 | } |
| 635 | const message = error instanceof Error ? error.message : String(error); |
| 636 | try { |
| 637 | await this.rpc.tools.handlePendingToolCall({ requestId, error: message }); |
| 638 | } catch (rpcError) { |
| 639 | if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) { |
| 640 | throw rpcError; |
| 641 | } |
| 642 | // Connection lost or RPC error — nothing we can do |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | /** |
| 648 | * Executes a permission handler and sends the result back via RPC. |
no test coverage detected