Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(plugins): avoid hook tool name collisions (#8856)
importcppbd7308742c3c
diff --git a/server/internal/daemon/plugin_hook_mcp.go b/server/internal/daemon/plugin_hook_mcp.goindex 2ce519fbaa..4bac869829 100644--- a/server/internal/daemon/plugin_hook_mcp.go+++ b/server/internal/daemon/plugin_hook_mcp.go@@ -77,6 +77,7 @@ func startTaskPluginHookMCP(lifetimeCtx context.Context, taskID string, tools []}byName := make(map[string]PluginHookTool, len(tools))+ acceptedTools := make([]PluginHookTool, 0, len(tools))for _, tool := range tools {// The server namespaces these, but a duplicate arriving anyway must// resolve to exactly one hook rather than whichever came last.@@ -87,6 +88,7 @@ func startTaskPluginHookMCP(lifetimeCtx context.Context, taskID string, tools []continue}byName[tool.Name] = tool+ acceptedTools = append(acceptedTools, tool)}listener, err := net.Listen("tcp", "127.0.0.1:0")@@ -100,7 +102,7 @@ func startTaskPluginHookMCP(lifetimeCtx context.Context, taskID string, tools []}handler := &pluginHookMCPServer{- taskID: taskID, tools: tools, byName: byName,+ taskID: taskID, tools: acceptedTools, byName: byName,invoke: invoke, path: "/" + pathToken, logger: logger,}server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second}diff --git a/server/internal/daemon/plugin_hook_mcp_test.go b/server/internal/daemon/plugin_hook_mcp_test.goindex e26dd71b05..d8c3e1cdf3 100644--- a/server/internal/daemon/plugin_hook_mcp_test.go+++ b/server/internal/daemon/plugin_hook_mcp_test.go@@ -6,6 +6,7 @@ import ("errors""net/http""net/http/httptest"+ "reflect""strings""testing")@@ -103,6 +104,78 @@ func TestPluginHookToolsListIsWhatTheServerSent(t *testing.T) {}}+func TestPluginHookDuplicateNamesKeepTheFirstDescriptorAndRoute(t *testing.T) {+ tools := []PluginHookTool{+ {InstallationID: "inst-first", HookKey: "first", Name: "shared_tool",+ Description: "The first hook.", InputSchema: json.RawMessage(`{"type":"object","properties":{"first":{"type":"string"}}}`)},+ {InstallationID: "inst-duplicate", HookKey: "duplicate", Name: "shared_tool",+ Description: "The duplicate hook.", InputSchema: json.RawMessage(`{"type":"object","properties":{"duplicate":{"type":"integer"}}}`)},+ {InstallationID: "inst-other", HookKey: "other", Name: "other_tool",+ Description: "The independent hook.", InputSchema: json.RawMessage(`{"type":"object","properties":{"other":{"type":"boolean"}}}`)},+ }+ original, err := json.Marshal(tools)+ if err != nil {+ t.Fatal(err)+ }+ var calls []string+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ _, set, err := startTaskPluginHookMCP(ctx, "task-1", tools,+ func(_ context.Context, taskID, installationID, hookKey string, _ json.RawMessage) (json.RawMessage, error) {+ calls = append(calls, taskID+"/"+installationID+"/"+hookKey)+ return json.RawMessage(`{"ok":true}`), nil+ }, nil)+ if err != nil {+ t.Fatalf("start hook MCP: %v", err)+ }+ t.Cleanup(set.Close)+ server := set.server.Handler.(*pluginHookMCPServer)+ unchanged, err := json.Marshal(tools)+ if err != nil {+ t.Fatal(err)+ }+ if string(unchanged) != string(original) {+ t.Fatalf("starting the server mutated the caller's tools: got %s, want %s", unchanged, original)+ }++ response := callMCP(t, server, server.path, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)+ result, ok := response["result"].(map[string]any)+ if !ok {+ t.Fatalf("no result in %v", response)+ }+ listed, ok := result["tools"].([]any)+ if !ok || len(listed) != 2 {+ t.Fatalf("tools = %v, want the first shared tool and the independent tool", result["tools"])+ }+ for i, want := range []PluginHookTool{tools[0], tools[2]} {+ var schema map[string]any+ if err := json.Unmarshal(want.InputSchema, &schema); err != nil {+ t.Fatal(err)+ }+ wantDescriptor := map[string]any{+ "name": want.Name, "description": want.Description, "inputSchema": schema,+ }+ if !reflect.DeepEqual(listed[i], wantDescriptor) {+ t.Fatalf("descriptor %d = %v, want %v", i, listed[i], wantDescriptor)+ }+ request, err := json.Marshal(map[string]any{+ "jsonrpc": "2.0", "id": i + 2, "method": "tools/call",+ "params": map[string]any{"name": want.Name, "arguments": map[string]any{}},+ })+ if err != nil {+ t.Fatal(err)+ }+ response := callMCP(t, server, server.path, string(request))+ result, ok := response["result"].(map[string]any)+ if !ok || result["isError"] == true {+ t.Fatalf("call %q failed: %v", want.Name, response)+ }+ }+ if want := []string{"task-1/inst-first/first", "task-1/inst-other/other"}; !reflect.DeepEqual(calls, want) {+ t.Fatalf("invocations = %v, want %v", calls, want)+ }+}+// A name the server did not send is not callable, however plausible it looks.func TestPluginHookToolRefusesAnUnknownTool(t *testing.T) {called := falsediff --git a/server/internal/service/plugin_agent_tools.go b/server/internal/service/plugin_agent_tools.goindex 02647e2ad5..637bbc1a8d 100644--- a/server/internal/service/plugin_agent_tools.go+++ b/server/internal/service/plugin_agent_tools.go@@ -63,9 +63,10 @@ var toolNameUnsafe = regexp.MustCompile(`[^a-zA-Z0-9_]+`)// lossy transliteration of it. The readable part is the last segment, which is// what a person recognises; the digest is what makes it unique.//-// The `__` separator is safe because a hook key cannot contain one: its pattern-// requires an alphanumeric after every underscore, so a doubled underscore is-// unrepresentable.+// Hook keys allow both hyphens and underscores. Encode a hyphen as `__` rather+// than collapsing both separators to `_`. Valid hook keys cannot contain+// adjacent separators, so this preserves their identity while leaving keys+// without hyphens unchanged.func PluginToolName(pluginKey, hookKey string) string {clean := func(value string) string {return strings.Trim(toolNameUnsafe.ReplaceAllString(value, "_"), "_")@@ -76,7 +77,8 @@ func PluginToolName(pluginKey, hookKey string) string {readable = "plugin"}digest := sha256.Sum256([]byte(pluginKey))- return readable + "_" + hex.EncodeToString(digest[:])[:6] + "__" + clean(hookKey)+ encodedHook := clean(strings.ReplaceAll(hookKey, "-", "__"))+ return readable + "_" + hex.EncodeToString(digest[:])[:6] + "__" + encodedHook}// AgentHookTools lists the hooks an agent running in this workspace may call.diff --git a/server/internal/service/plugin_agent_tools_test.go b/server/internal/service/plugin_agent_tools_test.goindex 68a6937cec..db69e1801e 100644--- a/server/internal/service/plugin_agent_tools_test.go+++ b/server/internal/service/plugin_agent_tools_test.go@@ -5,6 +5,7 @@ import ("testing"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract")// Two plugins may both contribute a hook called "summarize". The agent sees one@@ -25,8 +26,7 @@ func TestPluginToolNameNamespacesByPlugin(t *testing.T) {}}-// The separator has to be one that cannot appear inside either half, or two-// different (plugin, hook) pairs can still land on the same string.+// Raw keys containing separator characters must not forge another namespace.func TestPluginToolNameSeparatorCannotBeForged(t *testing.T) {// `a.b` + `c` vs `a.b_` + `c`: with a single-underscore separator both// become a_b_c.@@ -38,6 +38,53 @@ func TestPluginToolNameSeparatorCannotBeForged(t *testing.T) {}}+func TestPluginToolNameDistinguishesValidHookKeys(t *testing.T) {+ var manifest plugincontract.Manifest+ if err := json.Unmarshal([]byte(`{+ "manifest_version": 1, "key": "com.example.checks", "name": "Checks",+ "description": "Checks", "version": "1.0.0", "author": {"name": "example"},+ "scopes": ["net:example.com"]+ }`), &manifest); err != nil {+ t.Fatal(err)+ }+ for _, key := range []string{+ "check-status", "check_status", "check-status_now", "check_status-now",+ "check-status-now", "check_status_now",+ } {+ manifest.Contributes.Hooks = append(manifest.Contributes.Hooks, plugincontract.Hook{+ Key: key, Name: key, Description: "Run " + key,+ Triggers: []string{plugincontract.TriggerAgent},+ Transport: plugincontract.HookTransport{Type: plugincontract.TransportHTTP, URL: "https://example.com/" + key},+ })+ }+ raw, err := json.Marshal(manifest)+ if err != nil {+ t.Fatal(err)+ }+ parsed, _, err := plugincontract.ParseManifest(raw)+ if err != nil {+ t.Fatalf("the hooks must be valid in the same manifest: %v", err)+ }+ names := make(map[string]string)+ for _, hook := range parsed.Contributes.Hooks {+ name := PluginToolName(parsed.Key, hook.Key)+ if previous, exists := names[name]; exists {+ t.Errorf("valid hooks %q and %q both map to %q", previous, hook.Key, name)+ }+ names[name] = hook.Key+ if toolNameUnsafe.MatchString(name) {+ t.Errorf("tool name %q contains provider-unsafe characters", name)+ }+ if again := PluginToolName(parsed.Key, hook.Key); again != name {+ t.Errorf("tool name changed between calls: %q != %q", again, name)+ }+ }+ // Existing keys without hyphens retain their advertised names.+ if got := PluginToolName(parsed.Key, "check_status"); got != "checks_ae2ab7__check_status" {+ t.Errorf("underscore-only hook name changed: %q", got)+ }+}+// A hook that did not declare the agent trigger is not a tool. The host does// not get to offer a call site the manifest never listed.func TestAgentHookToolsOnlyIncludesDeclaredAgentHooks(t *testing.T) {diff --git a/server/internal/service/plugin_mcp_transport_test.go b/server/internal/service/plugin_mcp_transport_test.goindex db6a5ec25c..e198ba5a8b 100644--- a/server/internal/service/plugin_mcp_transport_test.go+++ b/server/internal/service/plugin_mcp_transport_test.go@@ -5,6 +5,7 @@ import ("testing"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract""github.com/multica-ai/multica/server/pkg/remotemcp")@@ -101,6 +102,49 @@ func TestApprovedMCPHookBecomesABrokerConnection(t *testing.T) {}}+func TestApprovedMCPHooksKeepDistinctContributionKeys(t *testing.T) {+ installation := mcpInstallation(t, "{}")+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ t.Fatal(err)+ }+ first, second := manifest.Contributes.Hooks[0], manifest.Contributes.Hooks[0]+ first.Key, second.Key = "check-status", "check_status"+ first.Transport.URL = "https://tools.example.com/first"+ second.Transport.URL = "https://tools.example.com/second"+ manifest.Contributes.Hooks = []plugincontract.Hook{first, second}+ installation.Manifest, err = json.Marshal(manifest)+ if err != nil {+ t.Fatal(err)+ }+ installation.McpApprovals, err = json.Marshal(PluginMCPApprovals{+ first.Key: {Tools: []remotemcp.Tool{{Name: "search", SchemaDigest: "sha256:aaa"}}},+ second.Key: {Tools: []remotemcp.Tool{{Name: "search", SchemaDigest: "sha256:bbb"}}},+ })+ if err != nil {+ t.Fatal(err)+ }+ connections := mcpConnectionsFor(installation)+ if len(connections) != 2 {+ t.Fatalf("got %d connections, want both approved hooks", len(connections))+ }+ if connections[0].ContributionKey == connections[1].ContributionKey {+ t.Errorf("approved hooks share the broker key %q", connections[0].ContributionKey)+ }+ for i, hook := range manifest.Contributes.Hooks {+ connection := connections[i]+ if want := remotemcp.PluginContributionPrefix + uuidString(installation.ID) + ":" + hook.Key; connection.ContributionID != want {+ t.Errorf("contribution id = %q, want %q", connection.ContributionID, want)+ }+ if connection.Endpoint != hook.Transport.URL {+ t.Errorf("endpoint = %q, want %q", connection.Endpoint, hook.Transport.URL)+ }+ if len(connection.ApprovedTools) != 1 || connection.ApprovedTools[0].SchemaDigest != []string{"sha256:aaa", "sha256:bbb"}[i] {+ t.Errorf("hook %q lost its own approved tools: %v", hook.Key, connection.ApprovedTools)+ }+ }+}+// An approved hook carries its pinned set, and the digest travels with it —// the broker's validatePinnedRemoteMCPTools compares against exactly this.func TestApprovedMCPToolsArePinnedByDigest(t *testing.T) {