High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a wrong-typed selector alias is reported as a missing selector and can silently fall through to another target, closing the census gap the review routed back (PIN-242)
Luigi Agostif747d80ab22b
diff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.goindex 33477ba1..0814e99e 100644--- a/internal/mcp/handlers_helpers.go+++ b/internal/mcp/handlers_helpers.go@@ -168,21 +168,58 @@ func hasASCIIAlpha(v string) bool {return false}+// firstSelectorString is firstNonEmptyString for the selector aliases, except that a key+// which was SENT under a non-string type is reported by name instead of being collapsed+// into not-given. A later alias that yields a usable string still wins — the caller's+// intent is unambiguous there — so wrongKey only survives when NO key produced a selector.+// A supplied empty string keeps collapsing deliberately: empty carries no selector meaning+// on any verb, so it falls through exactly as before.+func firstSelectorString(r mcp.CallToolRequest, keys ...string) (value, wrongKey, wrongType string) {+ args := r.GetArguments()+ for _, key := range keys {+ raw, ok := args[key]+ if !ok {+ continue+ }+ if v, isString := raw.(string); isString {+ if v = strings.TrimSpace(v); v != "" {+ return v, "", ""+ }+ continue+ }+ if wrongKey == "" {+ wrongKey, wrongType = key, jsonTypeName(raw)+ }+ }+ return "", wrongKey, wrongType+}+// actionSelectorArg resolves common selector aliases used by MCP clients.// If only "query" is provided, natural language input is normalized to// semantic selector form (find:...).-func actionSelectorArg(r mcp.CallToolRequest) string {- if sel := firstNonEmptyString(r, "selector", "ref", "element", "target"); sel != "" {- return sel+//+// A wrong-typed alias REFUSES rather than falling through — the fall-through would act on+// a different argument (query) or a different target (nodeId) while the caller's mistyped+// selector is silently ignored, which is worse than refusing. The caller of this function+// turns wrongKey/wrongType into the refusal, naming the key that was actually sent.+func actionSelectorArg(r mcp.CallToolRequest) (sel, wrongKey, wrongType string) {+ sel, wrongKey, wrongType = firstSelectorString(r, "selector", "ref", "element", "target")+ if sel != "" || wrongType != "" {+ return sel, wrongKey, wrongType+ }+ if raw, ok := r.GetArguments()["query"]; ok {+ if _, isString := raw.(string); !isString {+ return "", "query", jsonTypeName(raw)+ }}query := optTrimmedString(r, "query")if query == "" {- return ""+ return "", "", ""}if selector.HasKnownPrefix(query) || selector.IsRef(query) || looksLikeStructuredSelector(query) {- return query+ return query, "", ""}- return "find:" + query+ return "find:" + query, "", ""}func resolveXY(r mcp.CallToolRequest) (float64, float64, bool) {diff --git a/internal/mcp/handlers_helpers_test.go b/internal/mcp/handlers_helpers_test.goindex 924f2979..e11ce4d7 100644--- a/internal/mcp/handlers_helpers_test.go+++ b/internal/mcp/handlers_helpers_test.go@@ -54,12 +54,12 @@ func TestActionSelectorArgUsesTheGrammarsPrefixVocabulary(t *testing.T) {// them, so only the grammar's prefix vocabulary passes them through.for _, in := range []string{"css:#a", "CSS:#a", "Find:submit", "NTH:2:div", " text:hello", "find: login button", "Role: Save"} {want := strings.TrimSpace(in)- if got := actionSelectorArg(queryRequest(in)); got != want {+ if got, _, _ := actionSelectorArg(queryRequest(in)); got != want {t.Errorf("actionSelectorArg(%q) = %q, want %q passed through as a selector", in, got, want)}}for _, in := range []string{"submit", "unknownprefix value"} {- if got := actionSelectorArg(queryRequest(in)); got != "find:"+in {+ if got, _, _ := actionSelectorArg(queryRequest(in)); got != "find:"+in {t.Errorf("actionSelectorArg(%q) = %q, want it wrapped as find:", in, got)}}@@ -90,7 +90,7 @@ func TestActionSelectorArgRoutesSpaceSeparatedProseToFind(t *testing.T) {t.Run(tt.name, func(t *testing.T) {req := mcp.CallToolRequest{}req.Params.Arguments = map[string]any{"query": tt.query}- if got := actionSelectorArg(req); got != tt.want {+ if got, _, _ := actionSelectorArg(req); got != tt.want {t.Errorf("actionSelectorArg(%q) = %q, want %q", tt.query, got, tt.want)}})diff --git a/internal/mcp/handlers_interaction.go b/internal/mcp/handlers_interaction.goindex c0af8acd..b3235fed 100644--- a/internal/mcp/handlers_interaction.go+++ b/internal/mcp/handlers_interaction.go@@ -36,11 +36,7 @@ func suppliedStringArg(r mcp.CallToolRequest, verb, arg, emptyMeans string, keysreturn value, nil}if wrongType != "" {- message := fmt.Sprintf("%s's '%s' must be a string, got %s; quote it", verb, arg, wrongType)- if emptyMeans != "" {- message += ", or " + emptyMeans- }- return "", mcp.NewToolResultError(message)+ return "", wrongTypeRefusal(verb, arg, wrongType, emptyMeans)}message := fmt.Sprintf("%s needs a '%s' argument", verb, arg)if emptyMeans != "" {@@ -49,6 +45,17 @@ func suppliedStringArg(r mcp.CallToolRequest, verb, arg, emptyMeans string, keysreturn "", mcp.NewToolResultError(message)}+// wrongTypeRefusal is the one builder for the supplied-under-the-wrong-type refusal, shared+// by the value/text arguments and the selector aliases so the verbs cannot drift on the+// message or lose the remedy. arg names the key the caller actually sent.+func wrongTypeRefusal(verb, arg, gotType, emptyMeans string) *mcp.CallToolResult {+ message := fmt.Sprintf("%s's '%s' must be a string, got %s; quote it", verb, arg, gotType)+ if emptyMeans != "" {+ message += ", or " + emptyMeans+ }+ return mcp.NewToolResultError(message)+}+func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {payload := map[string]any{"kind": kind}@@ -73,14 +80,20 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequpayload["nodeId"] = nodeID}- resolveSelector := func(required bool) (bool, error) {- sel := actionSelectorArg(r)+ resolveSelector := func(required bool) (bool, *mcp.CallToolResult) {+ sel, wrongKey, wrongType := actionSelectorArg(r)+ if wrongType != "" {+ // Refused even when a selector is not required: acting on nodeId or+ // query while silently discarding a mistyped ref the caller sent is+ // the wrong-target hazard, not a convenience.+ return false, wrongTypeRefusal(kind, wrongKey, wrongType, "")+ }if sel != "" {payload["selector"] = selreturn true, nil}if required {- return false, fmt.Errorf("required parameter 'selector' is missing")+ return false, mcp.NewToolResultError("required parameter 'selector' is missing")}return false, nil}@@ -91,8 +104,8 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequif kind == "click" || kind == "hover" {requiresSelector = requiresSelector && !hasXY}- if _, err := resolveSelector(requiresSelector); err != nil {- return mcp.NewToolResultError(err.Error()), nil+ if _, refusal := resolveSelector(requiresSelector); refusal != nil {+ return refusal, nil}// Forwarded only when the caller actually sent it, so an omitted// humanize inherits the instance default instead of overriding it for@@ -131,8 +144,8 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequ}case "type":- if _, err := resolveSelector(!hasNodeID); err != nil {- return mcp.NewToolResultError(err.Error()), nil+ if _, refusal := resolveSelector(!hasNodeID); refusal != nil {+ return refusal, nil}// Typing nothing is meaningless, so type keeps collapsing empty with absent —// but only after a wrong-typed argument has been named as one, rather than@@ -154,8 +167,8 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequpayload["key"] = keycase "select":- if _, err := resolveSelector(!hasNodeID); err != nil {- return mcp.NewToolResultError(err.Error()), nil+ if _, refusal := resolveSelector(!hasNodeID); refusal != nil {+ return refusal, nil}// `<option value="">` is the standard placeholder, so an empty value is a real// selection — the one that resets a dropdown — and the bridge tells it apart@@ -167,9 +180,9 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequpayload["value"] = valuecase "scroll":- hasSelector, err := resolveSelector(false)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil+ hasSelector, refusal := resolveSelector(false)+ if refusal != nil {+ return refusal, nil}pixels, hasPixels := optInt(r, "pixels")deltaX, hasDeltaX := optInt(r, "deltaX")@@ -243,13 +256,13 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequ}case "scrollintoview":- if _, err := resolveSelector(!hasNodeID); err != nil {- return mcp.NewToolResultError(err.Error()), nil+ if _, refusal := resolveSelector(!hasNodeID); refusal != nil {+ return refusal, nil}case "fill":- if _, err := resolveSelector(!hasNodeID); err != nil {- return mcp.NewToolResultError(err.Error()), nil+ if _, refusal := resolveSelector(!hasNodeID); refusal != nil {+ return refusal, nil}// Presence, not emptiness: an empty value is how a caller clears a field,// so refusing it made the one documented clear idiom inexpressible herediff --git a/internal/mcp/handlers_interaction_test.go b/internal/mcp/handlers_interaction_test.goindex 98efa072..867ec142 100644--- a/internal/mcp/handlers_interaction_test.go+++ b/internal/mcp/handlers_interaction_test.go@@ -1046,3 +1046,90 @@ func TestScrollHandlerCarriesNoOwnDirectionVocabularyOrMagnitude(t *testing.T) {t.Error("the handler no longer reads the owner, so this guard is pinning nothing")}}++// The selector aliases had this card's defect one argument over: a wrong-typed selector,+// ref, element, target or query collapsed into "required parameter 'selector' is missing",+// telling the caller an argument it sent is absent — on the key every action tool requires.+// The refusal must name the KEY the caller actually used, not always "selector".+func TestActionToolsNameAWrongTypedSelectorKeyInsteadOfCallingItMissing(t *testing.T) {+ for _, tc := range []struct {+ name string+ tool string+ args map[string]any+ wantSays string+ }{+ {name: "fill selector number", tool: "pinchtab_fill", args: map[string]any{"selector": float64(123), "value": "x"}, wantSays: "fill's 'selector' must be a string, got number"},+ {name: "fill ref number", tool: "pinchtab_fill", args: map[string]any{"ref": float64(5), "value": "x"}, wantSays: "fill's 'ref' must be a string, got number"},+ {name: "click target boolean", tool: "pinchtab_click", args: map[string]any{"target": true}, wantSays: "click's 'target' must be a string, got boolean"},+ {name: "click element array", tool: "pinchtab_click", args: map[string]any{"element": []any{"e5"}}, wantSays: "click's 'element' must be a string, got array"},+ {name: "click query number", tool: "pinchtab_click", args: map[string]any{"query": float64(5)}, wantSays: "click's 'query' must be a string, got number"},+ {name: "genuinely absent keeps its own message", tool: "pinchtab_click", args: map[string]any{}, wantSays: "required parameter 'selector' is missing"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ t.Error("the tool posted a request for an unusable selector instead of refusing it")+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()++ res := callTool(t, tc.tool, tc.args, srv)++ if !res.IsError {+ t.Fatalf("accepted %v", tc.args)+ }+ text := resultText(t, res)+ if !strings.Contains(text, tc.wantSays) {+ t.Errorf("error = %q, want it to say %q so the caller knows which key to fix", text, tc.wantSays)+ }+ assertNamesTheRemedy(t, text, tc.wantSays)+ })+ }+}++// The contract call, recorded as an assertion: a wrong-typed selector refuses OUTRIGHT+// even when another target could satisfy the action. Acting on nodeId or falling through+// to query while a mistyped ref is silently discarded is the wrong-target hazard — the+// caller meant SOMETHING by the key it sent.+func TestAWrongTypedSelectorRefusesInsteadOfActingOnAnotherTarget(t *testing.T) {+ for _, tc := range []struct {+ name string+ args map[string]any+ }{+ {name: "nodeId would have satisfied click", args: map[string]any{"nodeId": float64(3), "ref": float64(5)}},+ {name: "query would have satisfied click", args: map[string]any{"query": "the save button", "ref": float64(5)}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ t.Error("the tool acted on another target while discarding the mistyped selector")+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()++ res := callTool(t, "pinchtab_click", tc.args, srv)+ if !res.IsError {+ t.Fatalf("accepted %v", tc.args)+ }+ if text := resultText(t, res); !strings.Contains(text, "click's 'ref' must be a string, got number") {+ t.Errorf("error = %q, want the mistyped ref named", text)+ }+ })+ }+}++// A later alias that yields a usable string still wins: the caller's intent is+// unambiguous, so a mistyped earlier key does not veto a valid one.+func TestAValidLaterSelectorAliasStillWinsOverAMistypedEarlierOne(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_fill", map[string]any{"selector": float64(9), "ref": "e5", "value": "x"}, srv)+ if r.IsError {+ t.Fatalf("refused despite a usable ref: %s", resultText(t, r))+ }+ body, _ := resultJSON(t, r)["body"].(map[string]any)+ if got, _ := body["selector"].(string); got != "e5" {+ t.Errorf("posted selector = %q, want the valid alias e5", got)+ }+}