-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathdefinetool.go
More file actions
232 lines (201 loc) · 6.34 KB
/
definetool.go
File metadata and controls
232 lines (201 loc) · 6.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package copilot
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/google/jsonschema-go/jsonschema"
)
// DefineTool creates a Tool with automatic JSON schema generation from a typed handler function.
// The handler receives typed arguments (automatically unmarshaled from JSON) and the raw ToolInvocation.
// The handler can return any value - strings pass through directly, other types are JSON-serialized.
//
// Example:
//
// type GetWeatherParams struct {
// City string `json:"city" jsonschema:"city name"`
// Unit string `json:"unit" jsonschema:"temperature unit (celsius or fahrenheit)"`
// }
//
// tool := copilot.DefineTool("get_weather", "Get weather for a city",
// func(params GetWeatherParams, inv copilot.ToolInvocation) (any, error) {
// return fmt.Sprintf("Weather in %s: 22°%s", params.City, params.Unit), nil
// })
func DefineTool[T any, U any](name, description string, handler func(T, ToolInvocation) (U, error)) Tool {
var zero T
schema := generateSchemaForType(reflect.TypeOf(zero))
return Tool{
Name: name,
Description: description,
Parameters: schema,
Handler: createTypedHandler(handler),
}
}
// createTypedHandler wraps a typed handler function into the standard ToolHandler signature.
func createTypedHandler[T any, U any](handler func(T, ToolInvocation) (U, error)) ToolHandler {
return func(inv ToolInvocation) (ToolResult, error) {
var params T
// Convert arguments to typed struct via JSON round-trip
// Arguments is already map[string]any from JSON-RPC parsing
jsonBytes, err := json.Marshal(inv.Arguments)
if err != nil {
return ToolResult{}, fmt.Errorf("failed to marshal arguments: %w", err)
}
if err := json.Unmarshal(jsonBytes, ¶ms); err != nil {
return ToolResult{}, fmt.Errorf("failed to unmarshal arguments into %T: %w", params, err)
}
result, err := handler(params, inv)
if err != nil {
return ToolResult{}, err
}
return normalizeResult(result)
}
}
// normalizeResult converts any value to a ToolResult.
// Strings pass through directly, ToolResult passes through, and other types
// are JSON-serialized.
func normalizeResult(result any) (ToolResult, error) {
if result == nil {
return ToolResult{
TextResultForLLM: "",
ResultType: "success",
}, nil
}
// ToolResult passes through directly
if tr, ok := result.(ToolResult); ok {
return tr, nil
}
// Strings pass through directly
if str, ok := result.(string); ok {
return ToolResult{
TextResultForLLM: str,
ResultType: "success",
}, nil
}
// Everything else gets JSON-serialized
jsonBytes, err := json.Marshal(result)
if err != nil {
return ToolResult{}, fmt.Errorf("failed to serialize result: %w", err)
}
return ToolResult{
TextResultForLLM: string(jsonBytes),
ResultType: "success",
}, nil
}
// ConvertMCPCallToolResult converts an MCP CallToolResult value (a map or struct
// with a "content" array and optional "isError" bool) into a ToolResult.
// Returns the converted ToolResult and true if the value matched the expected
// shape, or a zero ToolResult and false otherwise.
func ConvertMCPCallToolResult(value any) (ToolResult, bool) {
m, ok := value.(map[string]any)
if !ok {
jsonBytes, err := json.Marshal(value)
if err != nil {
return ToolResult{}, false
}
if err := json.Unmarshal(jsonBytes, &m); err != nil {
return ToolResult{}, false
}
}
contentRaw, exists := m["content"]
if !exists {
return ToolResult{}, false
}
contentSlice, ok := contentRaw.([]any)
if !ok {
return ToolResult{}, false
}
// Verify every element has a string "type" field
for _, item := range contentSlice {
block, ok := item.(map[string]any)
if !ok {
return ToolResult{}, false
}
if _, ok := block["type"].(string); !ok {
return ToolResult{}, false
}
}
var textParts []string
var binaryResults []ToolBinaryResult
for _, item := range contentSlice {
block := item.(map[string]any)
blockType := block["type"].(string)
switch blockType {
case "text":
if text, ok := block["text"].(string); ok {
textParts = append(textParts, text)
}
case "image":
data, _ := block["data"].(string)
mimeType, _ := block["mimeType"].(string)
if data == "" {
continue
}
binaryResults = append(binaryResults, ToolBinaryResult{
Data: data,
MimeType: mimeType,
Type: "image",
})
case "resource":
if resRaw, ok := block["resource"].(map[string]any); ok {
if text, ok := resRaw["text"].(string); ok && text != "" {
textParts = append(textParts, text)
}
if blob, ok := resRaw["blob"].(string); ok && blob != "" {
mimeType, _ := resRaw["mimeType"].(string)
if mimeType == "" {
mimeType = "application/octet-stream"
}
uri, _ := resRaw["uri"].(string)
binaryResults = append(binaryResults, ToolBinaryResult{
Data: blob,
MimeType: mimeType,
Type: "resource",
Description: uri,
})
}
}
}
}
resultType := "success"
if isErr, ok := m["isError"].(bool); ok && isErr {
resultType = "failure"
}
tr := ToolResult{
TextResultForLLM: strings.Join(textParts, "\n"),
ResultType: resultType,
}
if len(binaryResults) > 0 {
tr.BinaryResultsForLLM = binaryResults
}
return tr, true
}
// generateSchemaForType generates a JSON schema map from a Go type using reflection.
// Panics if schema generation fails, as this indicates a programming error.
func generateSchemaForType(t reflect.Type) map[string]any {
if t == nil {
return nil
}
// Handle pointer types
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
// Use google/jsonschema-go to generate the schema
schema, err := jsonschema.ForType(t, nil)
if err != nil {
panic(fmt.Sprintf("failed to generate schema for type %v: %v", t, err))
}
// Convert schema to map[string]any
schemaBytes, err := json.Marshal(schema)
if err != nil {
panic(fmt.Sprintf("failed to marshal schema for type %v: %v", t, err))
}
var schemaMap map[string]any
if err := json.Unmarshal(schemaBytes, &schemaMap); err != nil {
panic(fmt.Sprintf("failed to unmarshal schema for type %v: %v", t, err))
}
return schemaMap
}