-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool.go
More file actions
289 lines (261 loc) · 9.37 KB
/
Copy pathtool.go
File metadata and controls
289 lines (261 loc) · 9.37 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package agent
import (
"context"
"encoding/json"
"errors"
"reflect"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/components"
"github.com/OpenRouterTeam/go-sdk/optionalnullable"
"github.com/invopop/jsonschema"
)
var ErrReservedToolName = errors.New("tool name 'shared' is reserved")
type ToolConfig[In any] struct {
Name string
Description string
InputSchema map[string]any
OutputSchema map[string]any
EventSchema map[string]any
Execute func(context.Context, In, ToolExecuteContext) (any, error)
Generate func(context.Context, In, ToolExecuteContext, func(any) error) (any, error)
Manual bool
RequireApproval bool
Approval ToolApprovalCheck
OnToolCalled func(context.Context, In, ToolExecuteContext) (any, bool, error)
OnResponseReceived func(context.Context, any, ToolExecuteContext) (any, error)
}
type TypedTool[In any] struct {
config ToolConfig[In]
schema map[string]any
}
func NewTool[In any](config ToolConfig[In]) (*TypedTool[In], error) {
if config.Name == "shared" {
return nil, ErrReservedToolName
}
if config.Name == "" {
return nil, errors.New("tool name is required")
}
t := &TypedTool[In]{config: config}
if config.InputSchema != nil {
t.schema = copyMap(config.InputSchema)
} else {
schema, err := schemaFor[In]()
if err != nil {
return nil, err
}
t.schema = schema
}
t.schema = SanitizeSchema(t.schema)
return t, nil
}
func MustNewTool[In any](config ToolConfig[In]) *TypedTool[In] {
t, err := NewTool(config)
if err != nil {
panic(err)
}
return t
}
func (t *TypedTool[In]) ToolName() string { return t.config.Name }
func (t *TypedTool[In]) ToolDescription() string { return t.config.Description }
func (t *TypedTool[In]) InputSchema() map[string]any { return copyMap(t.schema) }
func (t *TypedTool[In]) OutputSchema() map[string]any { return copyMap(t.config.OutputSchema) }
func (t *TypedTool[In]) EventSchema() map[string]any { return copyMap(t.config.EventSchema) }
func (t *TypedTool[In]) ToolType() ToolType {
switch {
case t.config.OnToolCalled != nil:
return ToolTypeHITL
case t.config.Manual || (t.config.Execute == nil && t.config.Generate == nil):
return ToolTypeManual
case t.config.Generate != nil:
return ToolTypeGenerator
default:
return ToolTypeRegular
}
}
func (t *TypedTool[In]) RequiresApproval(ctx context.Context, call ParsedToolCall, turn TurnContext) (bool, error) {
if t.config.Approval != nil {
return t.config.Approval(ctx, call, turn)
}
return t.config.RequireApproval, nil
}
func (t *TypedTool[In]) HandleResponseReceived(ctx context.Context, output any, execCtx ToolExecuteContext) (any, error) {
if t.config.OnResponseReceived == nil {
return output, nil
}
return t.config.OnResponseReceived(ctx, output, execCtx)
}
func (t *TypedTool[In]) ToAPITool() components.ResponsesRequestToolUnion {
fn := components.ResponsesRequestToolFunction{
Name: t.config.Name,
Parameters: t.InputSchema(),
Type: components.ResponsesRequestTypeFunction,
}
if t.config.Description != "" {
fn.Description = optionalnullable.From(openrouter.String(t.config.Description))
}
strict := true
fn.Strict = optionalnullable.From(&strict)
return components.CreateResponsesRequestToolUnionFunction(fn)
}
func (t *TypedTool[In]) Execute(ctx context.Context, raw json.RawMessage, execCtx ToolExecuteContext) (ToolExecutionResult, error) {
var input In
if len(raw) == 0 || string(raw) == "null" {
raw = []byte("{}")
}
if err := json.Unmarshal(raw, &input); err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil
}
if err := ValidateAgainstSchema(raw, t.schema); err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil
}
if t.config.OnToolCalled != nil {
out, proceed, err := t.config.OnToolCalled(ctx, input, execCtx)
if err != nil || !proceed {
if err == nil && !proceed {
err = ErrHITLPause
}
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Error: err}, nil
}
if err := t.validateOutput(out); err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Error: err}, nil
}
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out}, nil
}
if t.config.Generate != nil {
var events []any
out, err := t.config.Generate(ctx, input, execCtx, func(v any) error {
if err := validateAny(v, t.config.EventSchema); err != nil {
return err
}
events = append(events, v)
if execCtx.Emit != nil {
execCtx.Emit(v)
}
return nil
})
if err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Events: events, Error: err}, nil
}
if err := t.validateOutput(out); err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Events: events, Error: err}, nil
}
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Events: events}, nil
}
if t.config.Execute == nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: ErrManualTool}, nil
}
out, err := t.config.Execute(ctx, input, execCtx)
if err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil
}
if err := t.validateOutput(out); err != nil {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Error: err}, nil
}
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out}, nil
}
func (t *TypedTool[In]) validateOutput(out any) error { return validateAny(out, t.config.OutputSchema) }
func validateAny(v any, schema map[string]any) error {
if len(schema) == 0 {
return nil
}
b, err := json.Marshal(v)
if err != nil {
return err
}
return ValidateAgainstSchema(b, schema)
}
type ServerToolConfig struct {
Name string
Config components.ResponsesRequestToolUnion
}
type serverToolImpl struct{ config ServerToolConfig }
func NewServerTool(config ServerToolConfig) Tool {
return serverToolImpl{config: config}
}
func (s serverToolImpl) ToolName() string { return s.config.Name }
func (s serverToolImpl) ToolDescription() string { return "" }
func (s serverToolImpl) ToolType() ToolType { return ToolTypeServer }
func (s serverToolImpl) InputSchema() map[string]any { return nil }
func (s serverToolImpl) OutputSchema() map[string]any { return nil }
func (s serverToolImpl) EventSchema() map[string]any { return nil }
func (s serverToolImpl) RequiresApproval(context.Context, ParsedToolCall, TurnContext) (bool, error) {
return false, nil
}
func (s serverToolImpl) HandleResponseReceived(_ context.Context, output any, _ ToolExecuteContext) (any, error) {
return output, nil
}
func (s serverToolImpl) ToAPITool() components.ResponsesRequestToolUnion { return s.config.Config }
func schemaFor[T any]() (map[string]any, error) {
var zero T
s := jsonschema.Reflect(zero)
b, err := json.Marshal(s)
if err != nil {
return nil, err
}
var out map[string]any
if err := json.Unmarshal(b, &out); err != nil {
return nil, err
}
if out["type"] == nil && reflect.TypeOf(zero).Kind() == reflect.Struct {
out["type"] = "object"
}
return out, nil
}
func copyMap(in map[string]any) map[string]any {
if in == nil {
return nil
}
out := make(map[string]any, len(in))
for k, v := range in {
out[k] = deepCopyJSONValue(v)
}
return out
}
func deepCopyJSONValue(v any) any {
switch x := v.(type) {
case map[string]any:
return copyMap(x)
case []any:
out := make([]any, len(x))
for i, child := range x {
out[i] = deepCopyJSONValue(child)
}
return out
default:
return x
}
}
// mcpBrand wraps a Tool with the additive MCP marker (see MarkMcp/IsMcpTool).
// Non-mutating: it forwards every Tool method to the wrapped tool unchanged,
// so runtime behavior and wire shape (ToAPITool) are identical to the
// unmarked tool. Execute is forwarded explicitly (rather than inherited via
// embedding, which only promotes the narrow Tool interface) so a marked
// executable tool keeps executing normally.
type mcpBrand struct{ Tool }
func (b mcpBrand) isMcpTool() {}
func (b mcpBrand) Execute(ctx context.Context, raw json.RawMessage, execCtx ToolExecuteContext) (ToolExecutionResult, error) {
exec, ok := b.Tool.(ToolWithExecute)
if !ok {
return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: b.Tool.ToolName(), Error: ErrManualTool}, nil
}
return exec.Execute(ctx, raw, execCtx)
}
// mcpMarked is implemented only by mcpBrand; IsMcpTool structurally checks
// for it rather than requiring a cast to a concrete type.
type mcpMarked interface{ isMcpTool() }
// MarkMcp adds the additive MCP brand to an already-built client tool. The
// tool's runtime behavior and wire shape are unchanged; only IsMcpTool's
// classification (and downstream Source discrimination on
// ToolExecutionResult/ToolStreamEvent) now identifies it as MCP-originated.
// Intended for use by an MCP integration package that wraps remote tools.
func MarkMcp(t Tool) Tool {
return mcpBrand{Tool: t}
}
// IsMcpTool reports whether tool carries the additive MCP brand (see MarkMcp).
func IsMcpTool(t Tool) bool {
if t == nil {
return false
}
_, ok := t.(mcpMarked)
return ok
}