1package ext
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "time"
8
9 "github.com/patriceckhart/zot/packages/agent/extproto"
10)
11
12type parentCallKey struct{}
13
14// CallTool asks zot to invoke an active built-in or extension tool. Tool
15// failures are returned as ToolResult.IsError, transport failures as err.
16// Calls made from tool handlers inherit their parent call for cycle detection
17// and cancellation.
18func (e *Extension) CallTool(ctx context.Context, name string, args any) (ToolResult, error) {
19 if !e.callToolReady.Load() {
20 return ToolResult{}, fmt.Errorf("host does not support call_tool")
21 }
22 if ctx == nil {
23 return ToolResult{}, fmt.Errorf("call_tool requires a context")
24 }
25 data, err := json.Marshal(args)
26 if err != nil {
27 return ToolResult{}, fmt.Errorf("encode tool args: %w", err)
28 }
29 if len(data) == 0 || data[0] != '{' {
30 return ToolResult{}, fmt.Errorf("call_tool args must be a JSON object")
31 }
32 ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
33 defer cancel()
34 id := fmt.Sprintf("sdk-%d", e.callSeq.Add(1))
35 ch := make(chan extproto.ToolResultFromHost, 1)
36 e.mu.Lock()
37 e.pendingCalls[id] = ch
38 e.mu.Unlock()
39 defer func() {
40 e.mu.Lock()
41 delete(e.pendingCalls, id)
42 e.mu.Unlock()
43 }()
44 parent, _ := ctx.Value(parentCallKey{}).(string)
45 if err := e.send(extproto.CallToolFromExt{Type: "call_tool", ID: id, Name: name, Args: data, ParentID: parent}); err != nil {
46 return ToolResult{}, err
47 }
48 select {
49 case reply := <-ch:
50 out := ToolResult{IsError: reply.IsError}
51 for _, block := range reply.Content {
52 out.Content = append(out.Content, ToolContent{Type: block.Type, Text: block.Text, MimeType: block.MimeType, Data: block.Data})
53 }
54 if reply.Truncated {
55 out.Content = append(out.Content, Text("[tool result truncated by host]"))
56 }
57 return out, nil
58 case <-ctx.Done():
59 _ = e.send(extproto.Frame{Type: "call_tool_cancel", ID: id})
60 return ToolResult{}, ctx.Err()
61 case <-e.done:
62 return ToolResult{}, fmt.Errorf("host disconnected")
63 }
64}