-
Notifications
You must be signed in to change notification settings - Fork 984
Expand file tree
/
Copy pathtool.go
More file actions
348 lines (306 loc) · 9.9 KB
/
Copy pathtool.go
File metadata and controls
348 lines (306 loc) · 9.9 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mcptoolset
import (
"errors"
"fmt"
"mime"
"strings"
"unicode/utf8"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/genai"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/internal/toolinternal"
"google.golang.org/adk/v2/model"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/toolutils"
)
func convertTool(t *mcp.Tool, client MCPClient, requireConfirmation bool, requireConfirmationProvider tool.ConfirmationProvider) (tool.Tool, error) {
mcp := &mcpTool{
name: t.Name,
description: t.Description,
funcDeclaration: &genai.FunctionDeclaration{
Name: t.Name,
Description: t.Description,
},
mcpClient: client,
requireConfirmation: requireConfirmation,
requireConfirmationProvider: requireConfirmationProvider,
}
// Since t.InputSchema and t.OutputSchema are pointers (*jsonschema.Schema) and the destination ResponseJsonSchema
// is an interface (any), we have encountered the type nil problem.
// This will make the omitempty not work since ResponseJsonSchema becomes an interface wrapper
// to a nil pointer and genai converter includes "responseJsonSchema": null in the json sent to the llm which causes it to crash.
// we need the following "if" check to keep ResponseJsonSchema (nil,nil) instead of (*jsonschema.Schema, nil)
if t.InputSchema != nil {
mcp.funcDeclaration.ParametersJsonSchema = t.InputSchema
}
if t.OutputSchema != nil {
mcp.funcDeclaration.ResponseJsonSchema = t.OutputSchema
}
return mcp, nil
}
type mcpTool struct {
name string
description string
funcDeclaration *genai.FunctionDeclaration
mcpClient MCPClient
requireConfirmation bool
requireConfirmationProvider tool.ConfirmationProvider
}
// Name implements the tool.Tool.
func (t *mcpTool) Name() string {
return t.name
}
// Description implements the tool.Tool.
func (t *mcpTool) Description() string {
return t.description
}
// IsLongRunning implements the tool.Tool.
func (t *mcpTool) IsLongRunning() bool {
return false
}
func (t *mcpTool) ProcessRequest(ctx agent.Context, req *model.LLMRequest) error {
return toolutils.PackTool(req, t)
}
func (t *mcpTool) Declaration() *genai.FunctionDeclaration {
return t.funcDeclaration
}
func (t *mcpTool) Run(ctx agent.Context, args any) (map[string]any, error) {
if confirmation := ctx.ToolConfirmation(); confirmation != nil {
if !confirmation.Confirmed {
return nil, fmt.Errorf("error tool %q %w", t.Name(), tool.ErrConfirmationRejected)
}
} else {
requireConfirmation := t.requireConfirmation
// Only run the potentially expensive provider if the static flag didn't already trigger it
// Provider takes precedence/overrides:
if t.requireConfirmationProvider != nil {
requireConfirmation = t.requireConfirmationProvider(t.Name(), args)
}
if requireConfirmation {
err := ctx.RequestConfirmation(
fmt.Sprintf("Please approve or reject the tool call %s() by responding with a FunctionResponse with an expected ToolConfirmation payload.",
t.Name()), nil)
if err != nil {
return nil, err
}
ctx.Actions().SkipSummarization = true
return nil, fmt.Errorf("error tool %q %w", t.Name(), tool.ErrConfirmationRequired)
}
}
res, err := t.mcpClient.CallTool(ctx, &mcp.CallToolParams{
Name: t.name,
Arguments: args,
})
if err != nil {
return nil, fmt.Errorf("failed to call MCP tool %q with err: %w", t.name, err)
}
if res.IsError {
details, _ := formatMCPContent(res.Content)
errMsg := "Tool execution failed."
if details != "" {
errMsg += " Details: " + details
}
return nil, errors.New(errMsg)
}
content, hasNonText := formatMCPContent(res.Content)
if res.StructuredContent != nil {
result := map[string]any{
"output": res.StructuredContent,
}
if hasNonText && content != "" {
result["content"] = content
}
return result, nil
}
if content == "" {
return nil, errors.New("no text content in tool response")
}
return map[string]any{
"output": content,
}, nil
}
type formattedMCPContent struct {
text string
isPlain bool
}
// formatMCPContent renders MCP's ordered content blocks into the text-only
// response shape supported by FunctionTool.Run. The boolean reports whether
// the result contains a non-text block that must accompany structured output.
func formatMCPContent(contents []mcp.Content) (string, bool) {
formatted := make([]formattedMCPContent, 0, len(contents))
hasNonText := false
for _, content := range contents {
block := formattedMCPContent{isPlain: true}
switch content := content.(type) {
case *mcp.TextContent:
if content == nil {
block.text = "[MCP text content: unavailable]"
block.isPlain = false
} else {
block.text = content.Text
}
case *mcp.EmbeddedResource:
block.text = formatEmbeddedResource(content)
block.isPlain = false
case *mcp.ResourceLink:
block.text = formatResourceLink(content)
block.isPlain = false
case *mcp.ImageContent:
if content == nil {
block.text = "[MCP image: unavailable]"
} else {
block.text = formatMediaContent("image", content.MIMEType, len(content.Data))
}
block.isPlain = false
case *mcp.AudioContent:
if content == nil {
block.text = "[MCP audio: unavailable]"
} else {
block.text = formatMediaContent("audio", content.MIMEType, len(content.Data))
}
block.isPlain = false
default:
block.text = fmt.Sprintf("[MCP content: unsupported type %T]", content)
block.isPlain = false
}
if !block.isPlain {
hasNonText = true
}
formatted = append(formatted, block)
}
var result strings.Builder
var previous *formattedMCPContent
for i := range formatted {
block := &formatted[i]
if block.text == "" {
continue
}
if previous != nil && (!previous.isPlain || !block.isPlain) &&
!strings.HasSuffix(previous.text, "\n") && !strings.HasPrefix(block.text, "\n") {
result.WriteByte('\n')
}
result.WriteString(block.text)
previous = block
}
return result.String(), hasNonText
}
func formatEmbeddedResource(content *mcp.EmbeddedResource) string {
if content == nil || content.Resource == nil {
return "[MCP embedded resource: unavailable]"
}
resource := content.Resource
attributes := resourceAttributes(resource.URI, resource.MIMEType)
if resource.Text != "" {
return formatContentWithBody("embedded resource", attributes, resource.Text)
}
if text, ok := decodeTextBlob(resource.Blob, resource.MIMEType); ok {
return formatContentWithBody("embedded resource", attributes, text)
}
if len(resource.Blob) > 0 {
attributes = append(attributes, fmt.Sprintf("size=%d bytes", len(resource.Blob)))
}
return formatContentLabel("embedded resource", attributes)
}
func formatResourceLink(content *mcp.ResourceLink) string {
if content == nil {
return "[MCP resource link: unavailable]"
}
attributes := resourceAttributes(content.URI, content.MIMEType)
if content.Name != "" {
attributes = append(attributes, fmt.Sprintf("name=%q", content.Name))
}
if content.Title != "" {
attributes = append(attributes, fmt.Sprintf("title=%q", content.Title))
}
if content.Description != "" {
attributes = append(attributes, fmt.Sprintf("description=%q", content.Description))
}
if content.Size != nil {
attributes = append(attributes, fmt.Sprintf("size=%d bytes", *content.Size))
}
return formatContentLabel("resource link", attributes)
}
func formatMediaContent(kind, mimeType string, size int) string {
attributes := make([]string, 0, 2)
if mimeType != "" {
attributes = append(attributes, fmt.Sprintf("mimeType=%q", mimeType))
}
attributes = append(attributes, fmt.Sprintf("size=%d bytes", size))
return formatContentLabel(kind, attributes)
}
func resourceAttributes(uri, mimeType string) []string {
attributes := make([]string, 0, 2)
if uri != "" {
attributes = append(attributes, fmt.Sprintf("uri=%q", uri))
}
if mimeType != "" {
attributes = append(attributes, fmt.Sprintf("mimeType=%q", mimeType))
}
return attributes
}
func formatContentWithBody(kind string, attributes []string, body string) string {
return formatContentLabel(kind, attributes) + "\n" + body
}
func formatContentLabel(kind string, attributes []string) string {
if len(attributes) == 0 {
return "[MCP " + kind + "]"
}
return "[MCP " + kind + ": " + strings.Join(attributes, ", ") + "]"
}
func decodeTextBlob(blob []byte, mimeType string) (string, bool) {
if len(blob) == 0 {
return "", false
}
mediaType, params, err := mime.ParseMediaType(mimeType)
if err != nil {
mediaType = strings.ToLower(strings.TrimSpace(strings.SplitN(mimeType, ";", 2)[0]))
}
if !isTextMediaType(mediaType) {
return "", false
}
charset := strings.ToLower(params["charset"])
switch charset {
case "", "utf-8", "utf8":
if !utf8.Valid(blob) {
return "", false
}
case "us-ascii":
for _, b := range blob {
if b >= utf8.RuneSelf {
return "", false
}
}
default:
return "", false
}
return string(blob), true
}
func isTextMediaType(mediaType string) bool {
if strings.HasPrefix(mediaType, "text/") || strings.HasSuffix(mediaType, "+json") || strings.HasSuffix(mediaType, "+xml") {
return true
}
switch mediaType {
case "application/json", "application/javascript", "application/toml", "application/xml",
"application/x-yaml", "application/yaml", "image/svg+xml":
return true
default:
return false
}
}
var (
_ toolinternal.FunctionTool = (*mcpTool)(nil)
_ toolinternal.RequestProcessor = (*mcpTool)(nil)
)