bots-garden/mini-mepublic Fork
⑂ 7944710
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

♻️ Quality: internal/mcp without smells (7 → 0)

- the wrapped tool as an mcpCall value (detector, server, tool, name,
  permissions): wrapTool(g, call), evented/terminal/run/record methods
  instead of 6-8 parameters; permissions with cmp.Or
- toolDescription with a usageHints table (context7)
- lenient split into lenientMap, droppedKeyword, lenientChild
- ConnectAll as connectServer, allowedTools, textOnly
- names.go (built-ins, sanitizing, collisions), schema.go (ModelSchema)

Checked: ModelSchema byte-identical old vs new on 5 sample schemas; live
old vs new binary with a fake MCP HTTP server and a fake model calling
its tool — line mode (auto, ask refused then allowed), -p (refused),
ACP, a call missing a required parameter: identical output (the tool
order in the banner varies run to run with the old binary too: map
iteration in WrapToolsWithNames, untouched).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T12:22:45+01:00 Browse files
7944710 parent: dcb1fec
modified internal/mcp/client.go +53 -44
@@ -170,61 +170,70 @@ func Connect(server config.MCPServer) (*ServerClient, error) {
170170 func ConnectAll(ctx context.Context, servers []config.MCPServer) (map[string]*ServerClient, []string, error) {
171171 clients := make(map[string]*ServerClient)
172172 var warnings []string
173-
174173 for _, server := range servers {
175- // Validate server config
176- if err := server.Validate(); err != nil {
177- warnings = append(warnings, fmt.Sprintf("mcp server %s: %v", server.Name, err))
178- continue
179- }
180-
181- // Create client
182- client, err := Connect(server)
174+ client, warned, err := connectServer(ctx, server)
175+ warnings = append(warnings, warned...)
183176 if err != nil {
184177 warnings = append(warnings, fmt.Sprintf("mcp server %s: %v", server.Name, err))
185178 continue
186179 }
180+ clients[server.Name] = client
181+ }
182+ return clients, warnings, nil
183+}
187184
188- // Perform discovery
189- tools, err := client.ListTools(ctx)
190- if err != nil {
191- _ = client.Close()
192- warnings = append(warnings, fmt.Sprintf("mcp server %s: discovery failed: %v", server.Name, err))
193- continue
194- }
185+// connectServer validates one server's config, connects to it and lists
186+// its tools: the allowed ones (`tools:`, when given), text-only — a tool
187+// with binary I/O is skipped with a warning.
188+func connectServer(ctx context.Context, server config.MCPServer) (*ServerClient, []string, error) {
189+ if err := server.Validate(); err != nil {
190+ return nil, nil, err
191+ }
192+ client, err := Connect(server)
193+ if err != nil {
194+ return nil, nil, err
195+ }
196+ tools, err := client.ListTools(ctx)
197+ if err != nil {
198+ _ = client.Close()
199+ return nil, nil, fmt.Errorf("discovery failed: %v", err)
200+ }
201+ if len(server.Tools) > 0 {
202+ tools = allowedTools(tools, server.Tools)
203+ }
204+ var warnings []string
205+ client.ToolList, warnings = textOnly(server.Name, tools)
206+ return client, warnings, nil
207+}
195208
196- // Filter by allowed tools if specified
197- if len(server.Tools) > 0 {
198- allowed := make(map[string]bool, len(server.Tools))
199- for _, name := range server.Tools {
200- allowed[strings.ToLower(name)] = true
201- }
202- var filtered []Tool
203- for _, tool := range tools {
204- if allowed[strings.ToLower(tool.Name)] {
205- filtered = append(filtered, tool)
206- }
207- }
208- tools = filtered
209+// allowedTools keeps the tools named in names, case aside.
210+func allowedTools(tools []Tool, names []string) []Tool {
211+ allowed := make(map[string]bool, len(names))
212+ for _, name := range names {
213+ allowed[strings.ToLower(name)] = true
214+ }
215+ var filtered []Tool
216+ for _, tool := range tools {
217+ if allowed[strings.ToLower(tool.Name)] {
218+ filtered = append(filtered, tool)
209219 }
220+ }
221+ return filtered
222+}
210223
211- // Filter out binary tools
212- var textTools []Tool
213- for _, tool := range tools {
214- if !tool.IsTextOnly() {
215- warnings = append(warnings,
216- fmt.Sprintf("mcp server %s: tool %s uses binary I/O - skipped (text-only)",
217- server.Name, tool.Name))
218- continue
219- }
220- textTools = append(textTools, tool)
224+// textOnly keeps the text-only tools, with a warning for each one skipped.
225+func textOnly(serverName string, tools []Tool) ([]Tool, []string) {
226+ var textTools []Tool
227+ var warnings []string
228+ for _, tool := range tools {
229+ if !tool.IsTextOnly() {
230+ warnings = append(warnings,
231+ fmt.Sprintf("mcp server %s: tool %s uses binary I/O - skipped (text-only)", serverName, tool.Name))
232+ continue
221233 }
222-
223- client.ToolList = textTools
224- clients[server.Name] = client
234+ textTools = append(textTools, tool)
225235 }
226-
227- return clients, warnings, nil
236+ return textTools, warnings
228237 }
229238
230239 // CloseAll closes all clients.
@@ -170,61 +170,70 @@ func Connect(server config.MCPServer) (*ServerClient, error) {
170 func ConnectAll(ctx context.Context, servers []config.MCPServer) (map[string]*ServerClient, []string, error) {170 func ConnectAll(ctx context.Context, servers []config.MCPServer) (map[string]*ServerClient, []string, error) {
171 clients := make(map[string]*ServerClient)171 clients := make(map[string]*ServerClient)
172 var warnings []string172 var warnings []string
173-
174 for _, server := range servers {173 for _, server := range servers {
175- // Validate server config174+ client, warned, err := connectServer(ctx, server)
176- if err := server.Validate(); err != nil {175+ warnings = append(warnings, warned...)
177- warnings = append(warnings, fmt.Sprintf("mcp server %s: %v", server.Name, err))
178- continue
179- }
180-
181- // Create client
182- client, err := Connect(server)
183 if err != nil {176 if err != nil {
184 warnings = append(warnings, fmt.Sprintf("mcp server %s: %v", server.Name, err))177 warnings = append(warnings, fmt.Sprintf("mcp server %s: %v", server.Name, err))
185 continue178 continue
186 }179 }
180+ clients[server.Name] = client
181+ }
182+ return clients, warnings, nil
183+}
187 184
188- // Perform discovery185+// connectServer validates one server's config, connects to it and lists
189- tools, err := client.ListTools(ctx)186+// its tools: the allowed ones (`tools:`, when given), text-only — a tool
190- if err != nil {187+// with binary I/O is skipped with a warning.
191- _ = client.Close()188+func connectServer(ctx context.Context, server config.MCPServer) (*ServerClient, []string, error) {
192- warnings = append(warnings, fmt.Sprintf("mcp server %s: discovery failed: %v", server.Name, err))189+ if err := server.Validate(); err != nil {
193- continue190+ return nil, nil, err
194- }191+ }
192+ client, err := Connect(server)
193+ if err != nil {
194+ return nil, nil, err
195+ }
196+ tools, err := client.ListTools(ctx)
197+ if err != nil {
198+ _ = client.Close()
199+ return nil, nil, fmt.Errorf("discovery failed: %v", err)
200+ }
201+ if len(server.Tools) > 0 {
202+ tools = allowedTools(tools, server.Tools)
203+ }
204+ var warnings []string
205+ client.ToolList, warnings = textOnly(server.Name, tools)
206+ return client, warnings, nil
207+}
195 208
196- // Filter by allowed tools if specified209+// allowedTools keeps the tools named in names, case aside.
197- if len(server.Tools) > 0 {210+func allowedTools(tools []Tool, names []string) []Tool {
198- allowed := make(map[string]bool, len(server.Tools))211+ allowed := make(map[string]bool, len(names))
199- for _, name := range server.Tools {212+ for _, name := range names {
200- allowed[strings.ToLower(name)] = true213+ allowed[strings.ToLower(name)] = true
201- }214+ }
202- var filtered []Tool215+ var filtered []Tool
203- for _, tool := range tools {216+ for _, tool := range tools {
204- if allowed[strings.ToLower(tool.Name)] {217+ if allowed[strings.ToLower(tool.Name)] {
205- filtered = append(filtered, tool)218+ filtered = append(filtered, tool)
206- }
207- }
208- tools = filtered
209 }219 }
220+ }
221+ return filtered
222+}
210 223
211- // Filter out binary tools224+// textOnly keeps the text-only tools, with a warning for each one skipped.
212- var textTools []Tool225+func textOnly(serverName string, tools []Tool) ([]Tool, []string) {
213- for _, tool := range tools {226+ var textTools []Tool
214- if !tool.IsTextOnly() {227+ var warnings []string
215- warnings = append(warnings,228+ for _, tool := range tools {
216- fmt.Sprintf("mcp server %s: tool %s uses binary I/O - skipped (text-only)",229+ if !tool.IsTextOnly() {
217- server.Name, tool.Name))230+ warnings = append(warnings,
218- continue231+ fmt.Sprintf("mcp server %s: tool %s uses binary I/O - skipped (text-only)", serverName, tool.Name))
219- }232+ continue
220- textTools = append(textTools, tool)
221 }233 }
222-234+ textTools = append(textTools, tool)
223- client.ToolList = textTools
224- clients[server.Name] = client
225 }235 }
226-236+ return textTools, warnings
227- return clients, warnings, nil
228 }237 }
229 238
230 // CloseAll closes all clients.239 // CloseAll closes all clients.
added internal/mcp/names.go +96 -0
new file mode 100644
@@ -0,0 +1,96 @@
1+package mcp
2+
3+import (
4+ "fmt"
5+ "mm/internal/config"
6+ "strings"
7+)
8+
9+// BuiltinTools is the list of mini-me's built-in tool names that must not be collided with.
10+var BuiltinTools = config.BuiltinToolNames
11+
12+// builtinToolSet for fast lookup.
13+var builtinToolSet = func() map[string]bool {
14+ set := make(map[string]bool)
15+ for _, t := range BuiltinTools {
16+ set[t] = true
17+ }
18+ return set
19+}()
20+
21+// IsBuiltinTool checks if a tool name is a mini-me built-in.
22+func IsBuiltinTool(name string) bool {
23+ return builtinToolSet[name]
24+}
25+
26+// SanitizeToolName sanitizes and prefixes a tool name for use in mini-me.
27+// It ensures the name is safe and doesn't collide with built-in tools.
28+func SanitizeToolName(serverName, toolName string) (string, error) {
29+ // Sanitize the tool name: replace special characters
30+ sanitized := sanitizeName(toolName)
31+
32+ // Prefix with server name
33+ fullName := serverName + "_" + sanitized
34+
35+ // Check for collision with built-in tools
36+ if IsBuiltinTool(fullName) {
37+ return "", fmt.Errorf("tool name %q collides with built-in tool", fullName)
38+ }
39+
40+ return fullName, nil
41+}
42+
43+// sanitizeName converts a tool name to a safe identifier.
44+func sanitizeName(name string) string {
45+ // Replace non-alphanumeric characters with underscore
46+ var result strings.Builder
47+ for _, r := range name {
48+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
49+ result.WriteRune(r)
50+ } else {
51+ result.WriteRune('_')
52+ }
53+ }
54+
55+ // Remove leading/trailing underscores and collapse multiple underscores
56+ s := result.String()
57+ s = strings.Trim(s, "_")
58+ for strings.Contains(s, "__") {
59+ s = strings.ReplaceAll(s, "__", "_")
60+ }
61+
62+ if s == "" {
63+ return "tool"
64+ }
65+
66+ return s
67+}
68+
69+// CheckCollisions checks for name collisions between MCP servers.
70+// Returns a list of collision errors.
71+func CheckCollisions(clients map[string]*ServerClient) []string {
72+ var collisions []string
73+
74+ // Collect all tool names
75+ allNames := make(map[string]string) // toolName -> serverName
76+
77+ for serverName, sc := range clients {
78+ for _, tool := range sc.ToolList {
79+ fullName, err := SanitizeToolName(serverName, tool.Name)
80+ if err != nil {
81+ collisions = append(collisions, err.Error())
82+ continue
83+ }
84+
85+ if existingServer, exists := allNames[fullName]; exists {
86+ collisions = append(collisions,
87+ fmt.Sprintf("tool name collision: %q from servers %s and %s",
88+ fullName, existingServer, serverName))
89+ } else {
90+ allNames[fullName] = serverName
91+ }
92+ }
93+ }
94+
95+ return collisions
96+}
new file mode 100644
@@ -0,0 +1,96 @@
1+package mcp
2+
3+import (
4+ "fmt"
5+ "mm/internal/config"
6+ "strings"
7+)
8+
9+// BuiltinTools is the list of mini-me's built-in tool names that must not be collided with.
10+var BuiltinTools = config.BuiltinToolNames
11+
12+// builtinToolSet for fast lookup.
13+var builtinToolSet = func() map[string]bool {
14+ set := make(map[string]bool)
15+ for _, t := range BuiltinTools {
16+ set[t] = true
17+ }
18+ return set
19+}()
20+
21+// IsBuiltinTool checks if a tool name is a mini-me built-in.
22+func IsBuiltinTool(name string) bool {
23+ return builtinToolSet[name]
24+}
25+
26+// SanitizeToolName sanitizes and prefixes a tool name for use in mini-me.
27+// It ensures the name is safe and doesn't collide with built-in tools.
28+func SanitizeToolName(serverName, toolName string) (string, error) {
29+ // Sanitize the tool name: replace special characters
30+ sanitized := sanitizeName(toolName)
31+
32+ // Prefix with server name
33+ fullName := serverName + "_" + sanitized
34+
35+ // Check for collision with built-in tools
36+ if IsBuiltinTool(fullName) {
37+ return "", fmt.Errorf("tool name %q collides with built-in tool", fullName)
38+ }
39+
40+ return fullName, nil
41+}
42+
43+// sanitizeName converts a tool name to a safe identifier.
44+func sanitizeName(name string) string {
45+ // Replace non-alphanumeric characters with underscore
46+ var result strings.Builder
47+ for _, r := range name {
48+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
49+ result.WriteRune(r)
50+ } else {
51+ result.WriteRune('_')
52+ }
53+ }
54+
55+ // Remove leading/trailing underscores and collapse multiple underscores
56+ s := result.String()
57+ s = strings.Trim(s, "_")
58+ for strings.Contains(s, "__") {
59+ s = strings.ReplaceAll(s, "__", "_")
60+ }
61+
62+ if s == "" {
63+ return "tool"
64+ }
65+
66+ return s
67+}
68+
69+// CheckCollisions checks for name collisions between MCP servers.
70+// Returns a list of collision errors.
71+func CheckCollisions(clients map[string]*ServerClient) []string {
72+ var collisions []string
73+
74+ // Collect all tool names
75+ allNames := make(map[string]string) // toolName -> serverName
76+
77+ for serverName, sc := range clients {
78+ for _, tool := range sc.ToolList {
79+ fullName, err := SanitizeToolName(serverName, tool.Name)
80+ if err != nil {
81+ collisions = append(collisions, err.Error())
82+ continue
83+ }
84+
85+ if existingServer, exists := allNames[fullName]; exists {
86+ collisions = append(collisions,
87+ fmt.Sprintf("tool name collision: %q from servers %s and %s",
88+ fullName, existingServer, serverName))
89+ } else {
90+ allNames[fullName] = serverName
91+ }
92+ }
93+ }
94+
95+ return collisions
96+}
added internal/mcp/schema.go +100 -0
new file mode 100644
@@ -0,0 +1,100 @@
1+package mcp
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// ModelSchema is the input schema declared to the model: the server's, with
9+// the parameter names, types and descriptions the model needs to fill a call,
10+// but nothing Genkit would reject a call for. Genkit validates a call against
11+// the declared schema before running the tool, and a rejected call ends the
12+// turn; mm instead answers a missing parameter with an error the model can
13+// read and correct (callMCPTool). So `required` goes (wrapTool lists the
14+// required parameters in the description), each `enum` moves into its
15+// property's description, and `additionalProperties: false` and `$schema` go.
16+// Without a declared schema the model sees no parameter at all: a model whose
17+// tool calls the server parses against the schema (Qwen's XML format on
18+// llama.cpp) then sends every call empty. The ACP client tools (ticket 202)
19+// declare their schemas through it too, for the same reasons.
20+//
21+// schema := mcp.ModelSchema(map[string]any{"type": "object", "required": []any{"q"}})
22+// // schema == {"type": "object", "properties": {}}
23+func ModelSchema(raw map[string]any) map[string]any {
24+ s, _ := lenient(raw).(map[string]any)
25+ if s == nil {
26+ s = map[string]any{}
27+ }
28+ s["type"] = "object"
29+ if _, ok := s["properties"].(map[string]any); !ok {
30+ s["properties"] = map[string]any{}
31+ }
32+ return s
33+}
34+
35+// lenient returns a deep copy of a JSON schema node without the constraints
36+// ModelSchema drops.
37+func lenient(node any) any {
38+ switch v := node.(type) {
39+ case map[string]any:
40+ return lenientMap(v)
41+ case []any:
42+ out := make([]any, len(v))
43+ for i, child := range v {
44+ out[i] = lenient(child)
45+ }
46+ return out
47+ }
48+ return node
49+}
50+
51+// lenientMap is lenient for a schema object: the dropped keywords out, each
52+// child cleaned, and an enum's values moved into the description.
53+func lenientMap(v map[string]any) map[string]any {
54+ out := make(map[string]any, len(v))
55+ for k, child := range v {
56+ if droppedKeyword(k, child) {
57+ continue
58+ }
59+ out[k] = lenientChild(k, child)
60+ }
61+ if enum, ok := v["enum"].([]any); ok && len(enum) > 0 {
62+ values := make([]string, len(enum))
63+ for i, e := range enum {
64+ values[i] = fmt.Sprint(e)
65+ }
66+ desc, _ := out["description"].(string)
67+ out["description"] = strings.TrimSpace(desc + " One of: " + strings.Join(values, ", ") + ".")
68+ }
69+ return out
70+}
71+
72+// droppedKeyword reports a keyword ModelSchema drops: required, $schema,
73+// enum, and additionalProperties: false.
74+func droppedKeyword(k string, child any) bool {
75+ switch k {
76+ case "required", "$schema", "enum":
77+ return true
78+ case "additionalProperties":
79+ b, ok := child.(bool)
80+ return ok && !b
81+ }
82+ return false
83+}
84+
85+// namedSchemas are the keywords whose keys are names, not keywords (a
86+// parameter may be called "enum"): every key is kept, each schema cleaned.
87+var namedSchemas = map[string]bool{"properties": true, "patternProperties": true, "$defs": true, "definitions": true}
88+
89+// lenientChild cleans the value of keyword k.
90+func lenientChild(k string, child any) any {
91+ named, ok := child.(map[string]any)
92+ if !namedSchemas[k] || !ok {
93+ return lenient(child)
94+ }
95+ schemas := make(map[string]any, len(named))
96+ for name, schema := range named {
97+ schemas[name] = lenient(schema)
98+ }
99+ return schemas
100+}
new file mode 100644
@@ -0,0 +1,100 @@
1+package mcp
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// ModelSchema is the input schema declared to the model: the server's, with
9+// the parameter names, types and descriptions the model needs to fill a call,
10+// but nothing Genkit would reject a call for. Genkit validates a call against
11+// the declared schema before running the tool, and a rejected call ends the
12+// turn; mm instead answers a missing parameter with an error the model can
13+// read and correct (callMCPTool). So `required` goes (wrapTool lists the
14+// required parameters in the description), each `enum` moves into its
15+// property's description, and `additionalProperties: false` and `$schema` go.
16+// Without a declared schema the model sees no parameter at all: a model whose
17+// tool calls the server parses against the schema (Qwen's XML format on
18+// llama.cpp) then sends every call empty. The ACP client tools (ticket 202)
19+// declare their schemas through it too, for the same reasons.
20+//
21+// schema := mcp.ModelSchema(map[string]any{"type": "object", "required": []any{"q"}})
22+// // schema == {"type": "object", "properties": {}}
23+func ModelSchema(raw map[string]any) map[string]any {
24+ s, _ := lenient(raw).(map[string]any)
25+ if s == nil {
26+ s = map[string]any{}
27+ }
28+ s["type"] = "object"
29+ if _, ok := s["properties"].(map[string]any); !ok {
30+ s["properties"] = map[string]any{}
31+ }
32+ return s
33+}
34+
35+// lenient returns a deep copy of a JSON schema node without the constraints
36+// ModelSchema drops.
37+func lenient(node any) any {
38+ switch v := node.(type) {
39+ case map[string]any:
40+ return lenientMap(v)
41+ case []any:
42+ out := make([]any, len(v))
43+ for i, child := range v {
44+ out[i] = lenient(child)
45+ }
46+ return out
47+ }
48+ return node
49+}
50+
51+// lenientMap is lenient for a schema object: the dropped keywords out, each
52+// child cleaned, and an enum's values moved into the description.
53+func lenientMap(v map[string]any) map[string]any {
54+ out := make(map[string]any, len(v))
55+ for k, child := range v {
56+ if droppedKeyword(k, child) {
57+ continue
58+ }
59+ out[k] = lenientChild(k, child)
60+ }
61+ if enum, ok := v["enum"].([]any); ok && len(enum) > 0 {
62+ values := make([]string, len(enum))
63+ for i, e := range enum {
64+ values[i] = fmt.Sprint(e)
65+ }
66+ desc, _ := out["description"].(string)
67+ out["description"] = strings.TrimSpace(desc + " One of: " + strings.Join(values, ", ") + ".")
68+ }
69+ return out
70+}
71+
72+// droppedKeyword reports a keyword ModelSchema drops: required, $schema,
73+// enum, and additionalProperties: false.
74+func droppedKeyword(k string, child any) bool {
75+ switch k {
76+ case "required", "$schema", "enum":
77+ return true
78+ case "additionalProperties":
79+ b, ok := child.(bool)
80+ return ok && !b
81+ }
82+ return false
83+}
84+
85+// namedSchemas are the keywords whose keys are names, not keywords (a
86+// parameter may be called "enum"): every key is kept, each schema cleaned.
87+var namedSchemas = map[string]bool{"properties": true, "patternProperties": true, "$defs": true, "definitions": true}
88+
89+// lenientChild cleans the value of keyword k.
90+func lenientChild(k string, child any) any {
91+ named, ok := child.(map[string]any)
92+ if !namedSchemas[k] || !ok {
93+ return lenient(child)
94+ }
95+ schemas := make(map[string]any, len(named))
96+ for name, schema := range named {
97+ schemas[name] = lenient(schema)
98+ }
99+ return schemas
100+}
modified internal/mcp/tool_wrapper.go +70 -254
@@ -1,6 +1,7 @@
11 package mcp
22
33 import (
4+ "cmp"
45 "context"
56 "fmt"
67 "strings"
@@ -14,95 +15,6 @@ import (
1415 "github.com/firebase/genkit/go/genkit"
1516 )
1617
17-// BuiltinTools is the list of mini-me's built-in tool names that must not be collided with.
18-var BuiltinTools = config.BuiltinToolNames
19-
20-// builtinToolSet for fast lookup.
21-var builtinToolSet = func() map[string]bool {
22- set := make(map[string]bool)
23- for _, t := range BuiltinTools {
24- set[t] = true
25- }
26- return set
27-}()
28-
29-// IsBuiltinTool checks if a tool name is a mini-me built-in.
30-func IsBuiltinTool(name string) bool {
31- return builtinToolSet[name]
32-}
33-
34-// SanitizeToolName sanitizes and prefixes a tool name for use in mini-me.
35-// It ensures the name is safe and doesn't collide with built-in tools.
36-func SanitizeToolName(serverName, toolName string) (string, error) {
37- // Sanitize the tool name: replace special characters
38- sanitized := sanitizeName(toolName)
39-
40- // Prefix with server name
41- fullName := serverName + "_" + sanitized
42-
43- // Check for collision with built-in tools
44- if IsBuiltinTool(fullName) {
45- return "", fmt.Errorf("tool name %q collides with built-in tool", fullName)
46- }
47-
48- return fullName, nil
49-}
50-
51-// sanitizeName converts a tool name to a safe identifier.
52-func sanitizeName(name string) string {
53- // Replace non-alphanumeric characters with underscore
54- var result strings.Builder
55- for _, r := range name {
56- if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
57- result.WriteRune(r)
58- } else {
59- result.WriteRune('_')
60- }
61- }
62-
63- // Remove leading/trailing underscores and collapse multiple underscores
64- s := result.String()
65- s = strings.Trim(s, "_")
66- for strings.Contains(s, "__") {
67- s = strings.ReplaceAll(s, "__", "_")
68- }
69-
70- if s == "" {
71- return "tool"
72- }
73-
74- return s
75-}
76-
77-// CheckCollisions checks for name collisions between MCP servers.
78-// Returns a list of collision errors.
79-func CheckCollisions(clients map[string]*ServerClient) []string {
80- var collisions []string
81-
82- // Collect all tool names
83- allNames := make(map[string]string) // toolName -> serverName
84-
85- for serverName, sc := range clients {
86- for _, tool := range sc.ToolList {
87- fullName, err := SanitizeToolName(serverName, tool.Name)
88- if err != nil {
89- collisions = append(collisions, err.Error())
90- continue
91- }
92-
93- if existingServer, exists := allNames[fullName]; exists {
94- collisions = append(collisions,
95- fmt.Sprintf("tool name collision: %q from servers %s and %s",
96- fullName, existingServer, serverName))
97- } else {
98- allNames[fullName] = serverName
99- }
100- }
101- }
102-
103- return collisions
104-}
105-
10618 // WrapTools creates wrapped Genkit tools for all MCP tools from the given clients.
10719 // Each tool is wrapped to respect mini-me's contracts (permissions, truncation, loop detection).
10820 func WrapTools(
@@ -144,7 +56,7 @@ func WrapToolsWithNames(
14456 }
14557
14658 // Create wrapped tool
147- wrapped := wrapTool(g, d, sc, mcpTool, fullName, defaultPermissions)
59+ wrapped := wrapTool(g, newMCPCall(d, sc, mcpTool, fullName, defaultPermissions))
14860 toolRefs = append(toolRefs, wrapped)
14961 toolNames = append(toolNames, fullName)
15062 }
@@ -153,44 +65,27 @@ func WrapToolsWithNames(
15365 return toolRefs, toolNames, warnings, nil
15466 }
15567
156-// wrapTool creates a single wrapped Genkit tool for an MCP tool.
157-func wrapTool(
158- g *genkit.Genkit,
159- d *detector.LoopDetector,
160- sc *ServerClient,
161- mcpTool Tool,
162- fullName string,
163- defaultPermissions string,
164-) ai.ToolRef {
165- // Get the server's permissions, or use default
166- permissions := sc.Server.Permissions
167- if permissions == "" {
168- permissions = defaultPermissions
169- }
170- if permissions == "" {
171- permissions = "ask" // Default for MCP tools
172- }
173-
174- // Create a description that includes the server, original tool info, and required parameters
175- description := fmt.Sprintf("MCP tool from server %s: %s", sc.Server.Name, mcpTool.Description)
176-
177- // Append required parameters info if any
178- if len(mcpTool.InputSchema.Required) > 0 {
179- params := strings.Join(mcpTool.InputSchema.Required, ", ")
180- description += fmt.Sprintf("\nRequired parameters: %s", params)
181- }
68+// mcpCall is one MCP tool as mm calls it: the loop detector its calls
69+// report to, the server, the tool, the name the model calls it by, and the
70+// permissions in force.
71+type mcpCall struct {
72+ d *detector.LoopDetector
73+ sc *ServerClient
74+ tool Tool
75+ fullName string
76+ permissions string
77+}
18278
183- // Add usage hints for specific well-known tools
184- if sc.Server.Name == "context7" {
185- switch mcpTool.Name {
186- case "resolve-library-id":
187- description += "\n\nUsage: Call this first to get a library ID. Example: resolve-library-id(query=\"React hooks\", libraryName=\"react\")"
188- case "query-docs":
189- description += "\n\nUsage: Call resolve-library-id first to get libraryId. Example: query-docs(libraryId=\"/vercel/next.js\", query=\"useEffect examples\")"
190- }
191- }
79+// newMCPCall is the call of mcpTool on sc, with the server's permissions —
80+// else the default ones, else "ask", the default for MCP tools.
81+func newMCPCall(d *detector.LoopDetector, sc *ServerClient, mcpTool Tool, fullName, defaultPermissions string) mcpCall {
82+ permissions := cmp.Or(sc.Server.Permissions, defaultPermissions, "ask")
83+ return mcpCall{d: d, sc: sc, tool: mcpTool, fullName: fullName, permissions: permissions}
84+}
19285
193- return genkit.DefineTool(g, fullName, description,
86+// wrapTool creates a single wrapped Genkit tool for an MCP tool.
87+func wrapTool(g *genkit.Genkit, c mcpCall) ai.ToolRef {
88+ return genkit.DefineTool(g, c.fullName, toolDescription(c.sc.Server.Name, c.tool),
19489 func(tctx *ai.ToolContext, raw any) (string, error) {
19590 in, _ := raw.(map[string]any)
19691 if in == nil {
@@ -198,88 +93,34 @@ func wrapTool(
19893 }
19994 // Event path for ACP/window
20095 if s := ui.ActiveSink(); s != nil {
201- return toolEvented(tctx, s, d, sc, mcpTool, fullName, in, permissions)
96+ return c.evented(tctx, s, in)
20297 }
203-
20498 // Terminal path
205- return toolTerminal(tctx, d, sc, mcpTool, fullName, in, permissions)
99+ return c.terminal(tctx, in)
206100 },
207- ai.WithInputSchema(ModelSchema(mcpTool.RawInputSchema)))
101+ ai.WithInputSchema(ModelSchema(c.tool.RawInputSchema)))
208102 }
209103
210-// ModelSchema is the input schema declared to the model: the server's, with
211-// the parameter names, types and descriptions the model needs to fill a call,
212-// but nothing Genkit would reject a call for. Genkit validates a call against
213-// the declared schema before running the tool, and a rejected call ends the
214-// turn; mm instead answers a missing parameter with an error the model can
215-// read and correct (callMCPTool). So `required` goes (wrapTool lists the
216-// required parameters in the description), each `enum` moves into its
217-// property's description, and `additionalProperties: false` and `$schema` go.
218-// Without a declared schema the model sees no parameter at all: a model whose
219-// tool calls the server parses against the schema (Qwen's XML format on
220-// llama.cpp) then sends every call empty. The ACP client tools (ticket 202)
221-// declare their schemas through it too, for the same reasons.
222-//
223-// schema := mcp.ModelSchema(map[string]any{"type": "object", "required": []any{"q"}})
224-// // schema == {"type": "object", "properties": {}}
225-func ModelSchema(raw map[string]any) map[string]any {
226- s, _ := lenient(raw).(map[string]any)
227- if s == nil {
228- s = map[string]any{}
104+// toolDescription is the description the model reads: the server, the
105+// tool's own description, its required parameters, and a usage hint for the
106+// well-known tools that need one.
107+func toolDescription(serverName string, mcpTool Tool) string {
108+ description := fmt.Sprintf("MCP tool from server %s: %s", serverName, mcpTool.Description)
109+ if len(mcpTool.InputSchema.Required) > 0 {
110+ description += fmt.Sprintf("\nRequired parameters: %s", strings.Join(mcpTool.InputSchema.Required, ", "))
229111 }
230- s["type"] = "object"
231- if _, ok := s["properties"].(map[string]any); !ok {
232- s["properties"] = map[string]any{}
112+ if hint := usageHints[serverName][mcpTool.Name]; hint != "" {
113+ description += "\n\nUsage: " + hint
233114 }
234- return s
115+ return description
235116 }
236117
237-// lenient returns a deep copy of a JSON schema node without the constraints
238-// ModelSchema drops.
239-func lenient(node any) any {
240- switch v := node.(type) {
241- case map[string]any:
242- out := make(map[string]any, len(v))
243- for k, child := range v {
244- switch k {
245- case "required", "$schema", "enum":
246- continue
247- case "additionalProperties":
248- if b, ok := child.(bool); ok && !b {
249- continue
250- }
251- case "properties", "patternProperties", "$defs", "definitions":
252- // Keys are names here (a parameter may be called "enum"):
253- // keep them all, clean each schema.
254- if named, ok := child.(map[string]any); ok {
255- schemas := make(map[string]any, len(named))
256- for name, schema := range named {
257- schemas[name] = lenient(schema)
258- }
259- out[k] = schemas
260- continue
261- }
262- }
263- out[k] = lenient(child)
264- }
265- if enum, ok := v["enum"].([]any); ok && len(enum) > 0 {
266- values := make([]string, len(enum))
267- for i, e := range enum {
268- values[i] = fmt.Sprint(e)
269- }
270- desc, _ := out["description"].(string)
271- out["description"] = strings.TrimSpace(desc + " One of: " + strings.Join(values, ", ") + ".")
272- }
273- return out
274- case []any:
275- out := make([]any, len(v))
276- for i, child := range v {
277- out[i] = lenient(child)
278- }
279- return out
280- default:
281- return v
282- }
118+// usageHints, by server then tool: how to call the tools models get wrong.
119+var usageHints = map[string]map[string]string{
120+ "context7": {
121+ "resolve-library-id": `Call this first to get a library ID. Example: resolve-library-id(query="React hooks", libraryName="react")`,
122+ "query-docs": `Call resolve-library-id first to get libraryId. Example: query-docs(libraryId="/vercel/next.js", query="useEffect examples")`,
123+ },
283124 }
284125
285126 // mustAsk reports whether a call of an MCP tool with these permissions waits
@@ -288,81 +129,56 @@ func mustAsk(permissions string) bool {
288129 return permissions == config.PermissionsAsk || consent.Required()
289130 }
290131
291-// toolEvented handles the tool call for event-consuming front ends (ACP, window).
292-func toolEvented(
293- ctx context.Context,
294- s ui.Sink,
295- d *detector.LoopDetector,
296- sc *ServerClient,
297- mcpTool Tool,
298- fullName string,
299- in map[string]any,
300- permissions string,
301-) (string, error) {
302- // Determine tool kind - always "execute" for MCP tools (we don't trust server hints)
303- kind := "execute"
304-
305- // Create tool event
132+// evented handles the tool call for event-consuming front ends (ACP, window).
133+// The kind is always "execute" for MCP tools: we don't trust server hints.
134+func (c mcpCall) evented(ctx context.Context, s ui.Sink, in map[string]any) (string, error) {
306135 ev := ui.ToolEvent{
307136 ID: ui.NextCallID(),
308- Tool: fullName,
309- Title: fmt.Sprintf("%s: %s", sc.Server.Name, mcpTool.Name),
310- Kind: kind,
137+ Tool: c.fullName,
138+ Title: fmt.Sprintf("%s: %s", c.sc.Server.Name, c.tool.Name),
139+ Kind: "execute",
311140 Input: in,
312141 Path: "", // MCP tools don't have a file path
313142 }
314-
315143 s.ToolStart(ev)
316144
317145 // "ask" asks whatever yolo says; "auto" asks only when yolo is off.
318- if mustAsk(permissions) && !s.Allow(ctx, ev) {
319- out := fmt.Sprintf("[%s rejected by user]", fullName)
146+ if mustAsk(c.permissions) && !s.Allow(ctx, ev) {
147+ out := fmt.Sprintf("[%s rejected by user]", c.fullName)
320148 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
321- return record(d, fullName, mcpTool.Name, out, true)
149+ return c.record(out, true)
322150 }
323151 s.ToolRunning(ev.ID)
324152
325- // Call the MCP tool
326- out, err := callMCPTool(ctx, sc, mcpTool, in)
327-
328- failed := err != nil
329- if err != nil {
330- out = fmt.Sprintf("[mcp error: %v]", err)
331- }
332-
333- // Truncate and return
334- truncated := Truncate(out)
335- s.ToolEnd(ev.ID, ui.ToolResult{Output: truncated, Failed: failed})
336-
337- return record(d, fullName, mcpTool.Name, truncated, failed)
153+ out, failed := c.run(ctx, in)
154+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed})
155+ return c.record(out, failed)
338156 }
339157
340-// toolTerminal handles the tool call for terminal mode.
341-func toolTerminal(
342- ctx context.Context,
343- d *detector.LoopDetector,
344- sc *ServerClient,
345- mcpTool Tool,
346- fullName string,
347- in map[string]any,
348- permissions string,
349-) (string, error) {
350- // The line mode asks through the REPL's prompt; in -p nobody can answer
351- // and an asking call is refused (consent.Prompt).
352- ev := ui.ToolEvent{Tool: fullName, Title: fmt.Sprintf("%s: %s", sc.Server.Name, mcpTool.Name), Input: in}
353- if mustAsk(permissions) && !consent.Prompt(ctx, ev) {
354- return record(d, fullName, mcpTool.Name, fmt.Sprintf("[%s rejected by user]", fullName), true)
158+// terminal handles the tool call for terminal mode. The line mode asks
159+// through the REPL's prompt; in -p nobody can answer and an asking call is
160+// refused (consent.Prompt).
161+func (c mcpCall) terminal(ctx context.Context, in map[string]any) (string, error) {
162+ ev := ui.ToolEvent{Tool: c.fullName, Title: fmt.Sprintf("%s: %s", c.sc.Server.Name, c.tool.Name), Input: in}
163+ if mustAsk(c.permissions) && !consent.Prompt(ctx, ev) {
164+ return c.record(fmt.Sprintf("[%s rejected by user]", c.fullName), true)
355165 }
166+ return c.record(c.run(ctx, in))
167+}
356168
357- // Call the MCP tool
358- out, err := callMCPTool(ctx, sc, mcpTool, in)
359-
169+// run calls the tool: its output truncated, or the error as the model reads
170+// it.
171+func (c mcpCall) run(ctx context.Context, in map[string]any) (string, bool) {
172+ out, err := callMCPTool(ctx, c.sc, c.tool, in)
360173 if err != nil {
361174 out = fmt.Sprintf("[mcp error: %v]", err)
362175 }
176+ return Truncate(out), err != nil
177+}
363178
364- // Truncate and return
365- return record(d, fullName, mcpTool.Name, Truncate(out), err != nil)
179+// record reports the call to the loop detector (see record).
180+func (c mcpCall) record(output string, failed bool) (string, error) {
181+ return record(c.d, c.fullName, c.tool.Name, output, failed)
366182 }
367183
368184 // callMCPTool calls an MCP tool and returns the result as a string.
@@ -1,6 +1,7 @@
1 package mcp1 package mcp
2 2
3 import (3 import (
4+ "cmp"
4 "context"5 "context"
5 "fmt"6 "fmt"
6 "strings"7 "strings"
@@ -14,95 +15,6 @@ import (
14 "github.com/firebase/genkit/go/genkit"15 "github.com/firebase/genkit/go/genkit"
15 )16 )
16 17
17-// BuiltinTools is the list of mini-me's built-in tool names that must not be collided with.
18-var BuiltinTools = config.BuiltinToolNames
19-
20-// builtinToolSet for fast lookup.
21-var builtinToolSet = func() map[string]bool {
22- set := make(map[string]bool)
23- for _, t := range BuiltinTools {
24- set[t] = true
25- }
26- return set
27-}()
28-
29-// IsBuiltinTool checks if a tool name is a mini-me built-in.
30-func IsBuiltinTool(name string) bool {
31- return builtinToolSet[name]
32-}
33-
34-// SanitizeToolName sanitizes and prefixes a tool name for use in mini-me.
35-// It ensures the name is safe and doesn't collide with built-in tools.
36-func SanitizeToolName(serverName, toolName string) (string, error) {
37- // Sanitize the tool name: replace special characters
38- sanitized := sanitizeName(toolName)
39-
40- // Prefix with server name
41- fullName := serverName + "_" + sanitized
42-
43- // Check for collision with built-in tools
44- if IsBuiltinTool(fullName) {
45- return "", fmt.Errorf("tool name %q collides with built-in tool", fullName)
46- }
47-
48- return fullName, nil
49-}
50-
51-// sanitizeName converts a tool name to a safe identifier.
52-func sanitizeName(name string) string {
53- // Replace non-alphanumeric characters with underscore
54- var result strings.Builder
55- for _, r := range name {
56- if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
57- result.WriteRune(r)
58- } else {
59- result.WriteRune('_')
60- }
61- }
62-
63- // Remove leading/trailing underscores and collapse multiple underscores
64- s := result.String()
65- s = strings.Trim(s, "_")
66- for strings.Contains(s, "__") {
67- s = strings.ReplaceAll(s, "__", "_")
68- }
69-
70- if s == "" {
71- return "tool"
72- }
73-
74- return s
75-}
76-
77-// CheckCollisions checks for name collisions between MCP servers.
78-// Returns a list of collision errors.
79-func CheckCollisions(clients map[string]*ServerClient) []string {
80- var collisions []string
81-
82- // Collect all tool names
83- allNames := make(map[string]string) // toolName -> serverName
84-
85- for serverName, sc := range clients {
86- for _, tool := range sc.ToolList {
87- fullName, err := SanitizeToolName(serverName, tool.Name)
88- if err != nil {
89- collisions = append(collisions, err.Error())
90- continue
91- }
92-
93- if existingServer, exists := allNames[fullName]; exists {
94- collisions = append(collisions,
95- fmt.Sprintf("tool name collision: %q from servers %s and %s",
96- fullName, existingServer, serverName))
97- } else {
98- allNames[fullName] = serverName
99- }
100- }
101- }
102-
103- return collisions
104-}
105-
106 // WrapTools creates wrapped Genkit tools for all MCP tools from the given clients.18 // WrapTools creates wrapped Genkit tools for all MCP tools from the given clients.
107 // Each tool is wrapped to respect mini-me's contracts (permissions, truncation, loop detection).19 // Each tool is wrapped to respect mini-me's contracts (permissions, truncation, loop detection).
108 func WrapTools(20 func WrapTools(
@@ -144,7 +56,7 @@ func WrapToolsWithNames(
144 }56 }
145 57
146 // Create wrapped tool58 // Create wrapped tool
147- wrapped := wrapTool(g, d, sc, mcpTool, fullName, defaultPermissions)59+ wrapped := wrapTool(g, newMCPCall(d, sc, mcpTool, fullName, defaultPermissions))
148 toolRefs = append(toolRefs, wrapped)60 toolRefs = append(toolRefs, wrapped)
149 toolNames = append(toolNames, fullName)61 toolNames = append(toolNames, fullName)
150 }62 }
@@ -153,44 +65,27 @@ func WrapToolsWithNames(
153 return toolRefs, toolNames, warnings, nil65 return toolRefs, toolNames, warnings, nil
154 }66 }
155 67
156-// wrapTool creates a single wrapped Genkit tool for an MCP tool.68+// mcpCall is one MCP tool as mm calls it: the loop detector its calls
157-func wrapTool(69+// report to, the server, the tool, the name the model calls it by, and the
158- g *genkit.Genkit,70+// permissions in force.
159- d *detector.LoopDetector,71+type mcpCall struct {
160- sc *ServerClient,72+ d *detector.LoopDetector
161- mcpTool Tool,73+ sc *ServerClient
162- fullName string,74+ tool Tool
163- defaultPermissions string,75+ fullName string
164-) ai.ToolRef {76+ permissions string
165- // Get the server's permissions, or use default77+}
166- permissions := sc.Server.Permissions
167- if permissions == "" {
168- permissions = defaultPermissions
169- }
170- if permissions == "" {
171- permissions = "ask" // Default for MCP tools
172- }
173-
174- // Create a description that includes the server, original tool info, and required parameters
175- description := fmt.Sprintf("MCP tool from server %s: %s", sc.Server.Name, mcpTool.Description)
176-
177- // Append required parameters info if any
178- if len(mcpTool.InputSchema.Required) > 0 {
179- params := strings.Join(mcpTool.InputSchema.Required, ", ")
180- description += fmt.Sprintf("\nRequired parameters: %s", params)
181- }
182 78
183- // Add usage hints for specific well-known tools79+// newMCPCall is the call of mcpTool on sc, with the server's permissions —
184- if sc.Server.Name == "context7" {80+// else the default ones, else "ask", the default for MCP tools.
185- switch mcpTool.Name {81+func newMCPCall(d *detector.LoopDetector, sc *ServerClient, mcpTool Tool, fullName, defaultPermissions string) mcpCall {
186- case "resolve-library-id":82+ permissions := cmp.Or(sc.Server.Permissions, defaultPermissions, "ask")
187- description += "\n\nUsage: Call this first to get a library ID. Example: resolve-library-id(query=\"React hooks\", libraryName=\"react\")"83+ return mcpCall{d: d, sc: sc, tool: mcpTool, fullName: fullName, permissions: permissions}
188- case "query-docs":84+}
189- description += "\n\nUsage: Call resolve-library-id first to get libraryId. Example: query-docs(libraryId=\"/vercel/next.js\", query=\"useEffect examples\")"
190- }
191- }
192 85
193- return genkit.DefineTool(g, fullName, description,86+// wrapTool creates a single wrapped Genkit tool for an MCP tool.
87+func wrapTool(g *genkit.Genkit, c mcpCall) ai.ToolRef {
88+ return genkit.DefineTool(g, c.fullName, toolDescription(c.sc.Server.Name, c.tool),
194 func(tctx *ai.ToolContext, raw any) (string, error) {89 func(tctx *ai.ToolContext, raw any) (string, error) {
195 in, _ := raw.(map[string]any)90 in, _ := raw.(map[string]any)
196 if in == nil {91 if in == nil {
@@ -198,88 +93,34 @@ func wrapTool(
198 }93 }
199 // Event path for ACP/window94 // Event path for ACP/window
200 if s := ui.ActiveSink(); s != nil {95 if s := ui.ActiveSink(); s != nil {
201- return toolEvented(tctx, s, d, sc, mcpTool, fullName, in, permissions)96+ return c.evented(tctx, s, in)
202 }97 }
203-
204 // Terminal path98 // Terminal path
205- return toolTerminal(tctx, d, sc, mcpTool, fullName, in, permissions)99+ return c.terminal(tctx, in)
206 },100 },
207- ai.WithInputSchema(ModelSchema(mcpTool.RawInputSchema)))101+ ai.WithInputSchema(ModelSchema(c.tool.RawInputSchema)))
208 }102 }
209 103
210-// ModelSchema is the input schema declared to the model: the server's, with104+// toolDescription is the description the model reads: the server, the
211-// the parameter names, types and descriptions the model needs to fill a call,105+// tool's own description, its required parameters, and a usage hint for the
212-// but nothing Genkit would reject a call for. Genkit validates a call against106+// well-known tools that need one.
213-// the declared schema before running the tool, and a rejected call ends the107+func toolDescription(serverName string, mcpTool Tool) string {
214-// turn; mm instead answers a missing parameter with an error the model can108+ description := fmt.Sprintf("MCP tool from server %s: %s", serverName, mcpTool.Description)
215-// read and correct (callMCPTool). So `required` goes (wrapTool lists the109+ if len(mcpTool.InputSchema.Required) > 0 {
216-// required parameters in the description), each `enum` moves into its110+ description += fmt.Sprintf("\nRequired parameters: %s", strings.Join(mcpTool.InputSchema.Required, ", "))
217-// property's description, and `additionalProperties: false` and `$schema` go.
218-// Without a declared schema the model sees no parameter at all: a model whose
219-// tool calls the server parses against the schema (Qwen's XML format on
220-// llama.cpp) then sends every call empty. The ACP client tools (ticket 202)
221-// declare their schemas through it too, for the same reasons.
222-//
223-// schema := mcp.ModelSchema(map[string]any{"type": "object", "required": []any{"q"}})
224-// // schema == {"type": "object", "properties": {}}
225-func ModelSchema(raw map[string]any) map[string]any {
226- s, _ := lenient(raw).(map[string]any)
227- if s == nil {
228- s = map[string]any{}
229 }111 }
230- s["type"] = "object"112+ if hint := usageHints[serverName][mcpTool.Name]; hint != "" {
231- if _, ok := s["properties"].(map[string]any); !ok {113+ description += "\n\nUsage: " + hint
232- s["properties"] = map[string]any{}
233 }114 }
234- return s115+ return description
235 }116 }
236 117
237-// lenient returns a deep copy of a JSON schema node without the constraints118+// usageHints, by server then tool: how to call the tools models get wrong.
238-// ModelSchema drops.119+var usageHints = map[string]map[string]string{
239-func lenient(node any) any {120+ "context7": {
240- switch v := node.(type) {121+ "resolve-library-id": `Call this first to get a library ID. Example: resolve-library-id(query="React hooks", libraryName="react")`,
241- case map[string]any:122+ "query-docs": `Call resolve-library-id first to get libraryId. Example: query-docs(libraryId="/vercel/next.js", query="useEffect examples")`,
242- out := make(map[string]any, len(v))123+ },
243- for k, child := range v {
244- switch k {
245- case "required", "$schema", "enum":
246- continue
247- case "additionalProperties":
248- if b, ok := child.(bool); ok && !b {
249- continue
250- }
251- case "properties", "patternProperties", "$defs", "definitions":
252- // Keys are names here (a parameter may be called "enum"):
253- // keep them all, clean each schema.
254- if named, ok := child.(map[string]any); ok {
255- schemas := make(map[string]any, len(named))
256- for name, schema := range named {
257- schemas[name] = lenient(schema)
258- }
259- out[k] = schemas
260- continue
261- }
262- }
263- out[k] = lenient(child)
264- }
265- if enum, ok := v["enum"].([]any); ok && len(enum) > 0 {
266- values := make([]string, len(enum))
267- for i, e := range enum {
268- values[i] = fmt.Sprint(e)
269- }
270- desc, _ := out["description"].(string)
271- out["description"] = strings.TrimSpace(desc + " One of: " + strings.Join(values, ", ") + ".")
272- }
273- return out
274- case []any:
275- out := make([]any, len(v))
276- for i, child := range v {
277- out[i] = lenient(child)
278- }
279- return out
280- default:
281- return v
282- }
283 }124 }
284 125
285 // mustAsk reports whether a call of an MCP tool with these permissions waits126 // mustAsk reports whether a call of an MCP tool with these permissions waits
@@ -288,81 +129,56 @@ func mustAsk(permissions string) bool {
288 return permissions == config.PermissionsAsk || consent.Required()129 return permissions == config.PermissionsAsk || consent.Required()
289 }130 }
290 131
291-// toolEvented handles the tool call for event-consuming front ends (ACP, window).132+// evented handles the tool call for event-consuming front ends (ACP, window).
292-func toolEvented(133+// The kind is always "execute" for MCP tools: we don't trust server hints.
293- ctx context.Context,134+func (c mcpCall) evented(ctx context.Context, s ui.Sink, in map[string]any) (string, error) {
294- s ui.Sink,
295- d *detector.LoopDetector,
296- sc *ServerClient,
297- mcpTool Tool,
298- fullName string,
299- in map[string]any,
300- permissions string,
301-) (string, error) {
302- // Determine tool kind - always "execute" for MCP tools (we don't trust server hints)
303- kind := "execute"
304-
305- // Create tool event
306 ev := ui.ToolEvent{135 ev := ui.ToolEvent{
307 ID: ui.NextCallID(),136 ID: ui.NextCallID(),
308- Tool: fullName,137+ Tool: c.fullName,
309- Title: fmt.Sprintf("%s: %s", sc.Server.Name, mcpTool.Name),138+ Title: fmt.Sprintf("%s: %s", c.sc.Server.Name, c.tool.Name),
310- Kind: kind,139+ Kind: "execute",
311 Input: in,140 Input: in,
312 Path: "", // MCP tools don't have a file path141 Path: "", // MCP tools don't have a file path
313 }142 }
314-
315 s.ToolStart(ev)143 s.ToolStart(ev)
316 144
317 // "ask" asks whatever yolo says; "auto" asks only when yolo is off.145 // "ask" asks whatever yolo says; "auto" asks only when yolo is off.
318- if mustAsk(permissions) && !s.Allow(ctx, ev) {146+ if mustAsk(c.permissions) && !s.Allow(ctx, ev) {
319- out := fmt.Sprintf("[%s rejected by user]", fullName)147+ out := fmt.Sprintf("[%s rejected by user]", c.fullName)
320 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})148 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
321- return record(d, fullName, mcpTool.Name, out, true)149+ return c.record(out, true)
322 }150 }
323 s.ToolRunning(ev.ID)151 s.ToolRunning(ev.ID)
324 152
325- // Call the MCP tool153+ out, failed := c.run(ctx, in)
326- out, err := callMCPTool(ctx, sc, mcpTool, in)154+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed})
327-155+ return c.record(out, failed)
328- failed := err != nil
329- if err != nil {
330- out = fmt.Sprintf("[mcp error: %v]", err)
331- }
332-
333- // Truncate and return
334- truncated := Truncate(out)
335- s.ToolEnd(ev.ID, ui.ToolResult{Output: truncated, Failed: failed})
336-
337- return record(d, fullName, mcpTool.Name, truncated, failed)
338 }156 }
339 157
340-// toolTerminal handles the tool call for terminal mode.158+// terminal handles the tool call for terminal mode. The line mode asks
341-func toolTerminal(159+// through the REPL's prompt; in -p nobody can answer and an asking call is
342- ctx context.Context,160+// refused (consent.Prompt).
343- d *detector.LoopDetector,161+func (c mcpCall) terminal(ctx context.Context, in map[string]any) (string, error) {
344- sc *ServerClient,162+ ev := ui.ToolEvent{Tool: c.fullName, Title: fmt.Sprintf("%s: %s", c.sc.Server.Name, c.tool.Name), Input: in}
345- mcpTool Tool,163+ if mustAsk(c.permissions) && !consent.Prompt(ctx, ev) {
346- fullName string,164+ return c.record(fmt.Sprintf("[%s rejected by user]", c.fullName), true)
347- in map[string]any,
348- permissions string,
349-) (string, error) {
350- // The line mode asks through the REPL's prompt; in -p nobody can answer
351- // and an asking call is refused (consent.Prompt).
352- ev := ui.ToolEvent{Tool: fullName, Title: fmt.Sprintf("%s: %s", sc.Server.Name, mcpTool.Name), Input: in}
353- if mustAsk(permissions) && !consent.Prompt(ctx, ev) {
354- return record(d, fullName, mcpTool.Name, fmt.Sprintf("[%s rejected by user]", fullName), true)
355 }165 }
166+ return c.record(c.run(ctx, in))
167+}
356 168
357- // Call the MCP tool169+// run calls the tool: its output truncated, or the error as the model reads
358- out, err := callMCPTool(ctx, sc, mcpTool, in)170+// it.
359-171+func (c mcpCall) run(ctx context.Context, in map[string]any) (string, bool) {
172+ out, err := callMCPTool(ctx, c.sc, c.tool, in)
360 if err != nil {173 if err != nil {
361 out = fmt.Sprintf("[mcp error: %v]", err)174 out = fmt.Sprintf("[mcp error: %v]", err)
362 }175 }
176+ return Truncate(out), err != nil
177+}
363 178
364- // Truncate and return179+// record reports the call to the loop detector (see record).
365- return record(d, fullName, mcpTool.Name, Truncate(out), err != nil)180+func (c mcpCall) record(output string, failed bool) (string, error) {
181+ return record(c.d, c.fullName, c.tool.Name, output, failed)
366 }182 }
367 183
368 // callMCPTool calls an MCP tool and returns the result as a string.184 // callMCPTool calls an MCP tool and returns the result as a string.
modified internal/mcp/tool_wrapper_test.go +1 -1
@@ -86,7 +86,7 @@ func TestWrappedToolDeclaresTheServersParameters(t *testing.T) {
8686 }
8787 g := genkit.Init(context.Background())
8888 sc := &ServerClient{Server: config.MCPServer{Name: "ddg"}}
89- wrapTool(g, detector.NewLoopDetector(10, 3), sc, tool, "ddg_search_news", "auto")
89+ wrapTool(g, newMCPCall(detector.NewLoopDetector(10, 3), sc, tool, "ddg_search_news", "auto"))
9090 action := genkit.LookupTool(g, "ddg_search_news")
9191 if action == nil {
9292 t.Fatal("tool not registered")
@@ -86,7 +86,7 @@ func TestWrappedToolDeclaresTheServersParameters(t *testing.T) {
86 }86 }
87 g := genkit.Init(context.Background())87 g := genkit.Init(context.Background())
88 sc := &ServerClient{Server: config.MCPServer{Name: "ddg"}}88 sc := &ServerClient{Server: config.MCPServer{Name: "ddg"}}
89- wrapTool(g, detector.NewLoopDetector(10, 3), sc, tool, "ddg_search_news", "auto")89+ wrapTool(g, newMCPCall(detector.NewLoopDetector(10, 3), sc, tool, "ddg_search_news", "auto"))
90 action := genkit.LookupTool(g, "ddg_search_news")90 action := genkit.LookupTool(g, "ddg_search_news")
91 if action == nil {91 if action == nil {
92 t.Fatal("tool not registered")92 t.Fatal("tool not registered")