High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the MCP funnel treats HTTP status as the only failure signal, so any endpoint reporting failure inside a 200 reaches the agent as success (PIN-229)
Luigi Agosti274af928f38f
diff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.goindex 0814e99e..8d97c39b 100644--- a/internal/mcp/handlers_helpers.go+++ b/internal/mcp/handlers_helpers.go@@ -235,9 +235,69 @@ func resultFromBytes(body []byte, code int) (*mcp.CallToolResult, error) {if code >= 400 {return mcp.NewToolResultError(fmt.Sprintf("HTTP %d: %s", code, string(body))), nil}+ if reason := reportsNoSuccess(body); reason != "" {+ return mcp.NewToolResultError(reason), nil+ }return mcp.NewToolResultText(string(body)), nil}+// reportsNoSuccess is the funnel's body-level failure rule: an endpoint that answers 200+// while reporting it achieved nothing must reach the agent as an error, or the agent+// confirms work the browser never did — the cookie-set path shipped exactly that.+//+// The rule keys on the COUNTING SHAPE, not on failure-flavoured key names: a top-level+// numeric "failed" above zero marks a response that counts the work it was asked to do.+// That is what keeps the exclusions structural rather than a list — the observability+// snapshot, /health/tabs and the console endpoint report failures AS their payload but+// carry no top-level failed count, and /network's per-request "failed" is a nested bool,+// so none of them can match. A key-name rule would break exactly those.+//+// Partial success stays a SUCCESS carrying detail: the succeeded items' effects already+// happened, and the body's own counts and failures list are what the agent needs to retry+// only what missed. Zero success is an error, with the body riding along as the reason.+// Fail closed within the shape: a failed count with no readable success count beside it+// confirms nothing and is refused. A body that does not parse as an object cannot carry+// the shape and keeps the status rule — most funnel responses are not counting anything.+//+// The cookie tool keeps unsetCookieReport ON TOP of this rule deliberately: it confirms a+// single named write with a stricter fail-closed contract (an unreadable body, or one+// missing its counts, refuses) than a funnel serving every tool can impose without+// breaking non-counting responses. Its check runs first, so its more specific message+// wins; this rule is the class-wide net behind it.+func reportsNoSuccess(body []byte) string {+ var top map[string]json.RawMessage+ if err := json.Unmarshal(body, &top); err != nil {+ return ""+ }+ failed, ok := topLevelCount(top, "failed")+ if !ok || failed == 0 {+ return ""+ }+ for _, key := range []string{"set", "successful", "succeeded"} {+ succeeded, ok := topLevelCount(top, key)+ if !ok {+ continue+ }+ if succeeded > 0 {+ return ""+ }+ return fmt.Sprintf("the call reported no successes (%s 0, failed %d): %s", key, failed, strings.TrimSpace(string(body)))+ }+ return fmt.Sprintf("the call reported %d failed and no success count to confirm anything landed: %s", failed, strings.TrimSpace(string(body)))+}++func topLevelCount(top map[string]json.RawMessage, key string) (int, bool) {+ raw, ok := top[key]+ if !ok {+ return 0, false+ }+ var n float64+ if err := json.Unmarshal(raw, &n); err != nil {+ return 0, false+ }+ return int(n), true+}+type profileInstanceStatus struct {Name string `json:"name"`Running bool `json:"running"`diff --git a/internal/mcp/handlers_helpers_test.go b/internal/mcp/handlers_helpers_test.goindex e11ce4d7..da38a3cf 100644--- a/internal/mcp/handlers_helpers_test.go+++ b/internal/mcp/handlers_helpers_test.go@@ -1,10 +1,14 @@package mcpimport (+ "net/http"+ "net/http/httptest"+ "path/filepath""strings""testing""github.com/mark3labs/mcp-go/mcp"+ "github.com/pinchtab/pinchtab/internal/srccensus")// looksLikeStructuredSelector decides whether an MCP client's free-form `query`@@ -96,3 +100,110 @@ func TestActionSelectorArgRoutesSpaceSeparatedProseToFind(t *testing.T) {})}}++// The funnel's whole rule used to be the status code, so any endpoint reporting failure+// inside a 200 reached the agent as success — the cookie-set path shipped exactly that.+// These rows drive the counting-shape rule through resultFromBytes itself, so a NEW+// endpoint emitting the shape is covered without anyone enumerating it.+func TestA200ReportingNoSuccessesIsAnErrorResult(t *testing.T) {+ for _, tc := range []struct {+ name string+ body string+ wantError bool+ wantSays string+ }{+ {name: "zero successes with the body's own reason", body: `{"set":0,"failed":1,"total":1,"failures":[{"name":"sid","error":"invalid domain"}]}`, wantError: true, wantSays: "invalid domain"},+ {name: "zero successes on the batch spelling", body: `{"successful":0,"failed":2,"total":2,"results":[]}`, wantError: true, wantSays: "no successes"},+ {name: "failed count with no success count fails closed", body: `{"failed":2,"total":2}`, wantError: true, wantSays: "no success count"},++ // Partial success is a SUCCESS carrying detail: the landed items' effects already+ // happened, and the body's counts and failures are what the agent needs to retry+ // only what missed. An error frame would report work that succeeded as lost.+ {name: "partial success stays a success carrying detail", body: `{"set":1,"failed":1,"total":2,"failures":[{"error":"x"}]}`, wantError: false},+ {name: "full success with a zero failed count", body: `{"set":2,"failed":0,"total":2}`, wantError: false},++ // The exclusions are structural, not a key-name list — each of these reports+ // failures AS its payload and must stay a successful call.+ {name: "observability snapshot's failures payload", body: `{"layer":"instance","failures":{"recent":[{"reason":"crash"}]}}`, wantError: false},+ {name: "health tabs failures payload", body: `{"status":"degraded","failures":{"recent":[]}}`, wantError: false},+ {name: "console errors payload", body: `{"errors":[{"text":"TypeError"}],"logs":[]}`, wantError: false},+ {name: "network response with a per-request failed bool", body: `{"requests":[{"url":"https://a/x.js","failed":true,"status":0}]}`, wantError: false},++ // Guards on the shape itself.+ {name: "a top-level boolean failed is not a count", body: `{"failed":true}`, wantError: false},+ {name: "a nested failed count is not this call's count", body: `{"detail":{"failed":3}}`, wantError: false},+ {name: "plain text keeps the status rule", body: `all good`, wantError: false},+ {name: "a JSON array keeps the status rule", body: `[1,2,3]`, wantError: false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ res, err := resultFromBytes([]byte(tc.body), 200)+ if err != nil {+ t.Fatal(err)+ }+ if res.IsError != tc.wantError {+ t.Fatalf("IsError = %v, want %v for body %s", res.IsError, tc.wantError, tc.body)+ }+ if tc.wantSays != "" {+ if text := resultText(t, res); !strings.Contains(text, tc.wantSays) {+ t.Errorf("error = %q, want it to carry %q — the body's own reason, not a generic failure", text, tc.wantSays)+ }+ }+ })+ }+}++// The rule holds at the tool surface, not only at the helper: a click whose endpoint+// answers 200 with zero successes must reach the agent as an error.+func TestAToolCallSeesAZeroSuccess200AsAnError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"successful":0,"failed":1,"total":1,"results":[{"kind":"click","error":"node gone"}]}`))+ }))+ defer srv.Close()++ res := callTool(t, "pinchtab_click", map[string]any{"ref": "e5"}, srv)+ if !res.IsError {+ t.Fatalf("a zero-success 200 reached the agent as success: %s", resultText(t, res))+ }+ if text := resultText(t, res); !strings.Contains(text, "node gone") {+ t.Errorf("error = %q, want the body's own reason to ride along", text)+ }+}++// The population the rule serves is DERIVED, not hand-listed: every non-test file in the+// packages the funnel proxies that spells a "failed" JSON key carries a recorded decision.+// A new endpoint counting its work lands in the funnel rule automatically; a new spelling+// of failure lands here and forces a human decision instead of shipping silent.+func TestEveryFailedKeyProducerHasARecordedFunnelDecision(t *testing.T) {+ decisions := map[string]string{+ "internal/handlers/cookies.go": "top-level numeric failed beside set/total: the counting shape, converted by the funnel rule",+ "internal/handlers/actions.go": "batch/macro counting shape (successful/failed/total); not reachable from MCP today, covered by the rule the day a batch tool lands",+ "internal/bridge/observe/network_buffer.go": "per-request failed is a nested BOOL describing the page's own subresources, excluded by the top-level-numeric requirement — an agent must not see a page's 404 as a failed call",+ }++ files := srccensus.Tree(t, filepath.Join("..", ".."), 200)+ found := map[string]bool{}+ for _, file := range files {+ if !strings.HasPrefix(file.Name, "internal/handlers/") && !strings.HasPrefix(file.Name, "internal/bridge/observe/") {+ continue+ }+ if !strings.Contains(file.Text, `"failed"`) {+ continue+ }+ found[file.Name] = true+ if decisions[file.Name] == "" {+ t.Errorf("%s spells a \"failed\" JSON key and has no recorded funnel decision; decide whether it is the counting shape (the funnel converts it) or a payload (say why it is excluded) and record it here", file.Name)+ }+ }+ for name, reason := range decisions {+ if reason == "" {+ t.Errorf("%s is recorded with no reason; every entry is a decision", name)+ }+ if !found[name] {+ t.Errorf("%s is recorded but no longer spells a \"failed\" key; drop or re-point its entry", name)+ }+ }+ if len(found) == 0 {+ t.Fatal("found no \"failed\" key producer at all; if the spelling moved, re-point this census rather than deleting it")+ }+}