High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: 27 MCP tool handlers end in the same five-line forward-and-wrap tail; fold it into one toolResult(body, code, err) so each becomes return toolResult(c.Get(...)) (PIN-373)
Luigi Agostib1722ea686d6
diff --git a/internal/mcp/handlers_content.go b/internal/mcp/handlers_content.goindex 6618daf8..3c975a77 100644--- a/internal/mcp/handlers_content.go+++ b/internal/mcp/handlers_content.go@@ -20,11 +20,7 @@ func handleEval(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Callif tabID := optString(r, "tabId"); tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/evaluate", payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, "/evaluate", payload))}}@@ -43,11 +39,7 @@ func handlePDF(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallTif pr := optString(r, "pageRanges"); pr != "" {q.Set("pageRanges", pr)}- body, code, err := c.Get(ctx, "/pdf", q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/pdf", q))}}diff --git a/internal/mcp/handlers_diagnostics.go b/internal/mcp/handlers_diagnostics.goindex 665b7a78..9c20270e 100644--- a/internal/mcp/handlers_diagnostics.go+++ b/internal/mcp/handlers_diagnostics.go@@ -28,16 +28,8 @@ func diagnosticsHandler(c *Client, path string) func(context.Context, mcp.CallToq.Set("tabId", tabID)}if clear, ok := optBool(r, "clear"); ok && clear {- body, code, err := c.Post(ctx, path+"/clear?"+q.Encode(), nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, path+"/clear?"+q.Encode(), nil))}- body, code, err := c.Get(ctx, path, q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, path, q))}}diff --git a/internal/mcp/handlers_dialog.go b/internal/mcp/handlers_dialog.goindex 9bcc7787..2544457d 100644--- a/internal/mcp/handlers_dialog.go+++ b/internal/mcp/handlers_dialog.go@@ -22,10 +22,6 @@ func handleDialog(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Caif tabID := optString(r, "tabId"); tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/dialog", payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, "/dialog", payload))}}diff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.goindex b659cca9..3fd1df61 100644--- a/internal/mcp/handlers_helpers.go+++ b/internal/mcp/handlers_helpers.go@@ -246,6 +246,13 @@ func resolveXY(r mcp.CallToolRequest) (float64, float64, bool) {return 0, 0, false}+func toolResult(body []byte, code int, err error) (*mcp.CallToolResult, error) {+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(body, code)+}+func resultFromBytes(body []byte, code int) (*mcp.CallToolResult, error) {if code >= 400 {return mcp.NewToolResultError(fmt.Sprintf("HTTP %d: %s", code, string(body))), nildiff --git a/internal/mcp/handlers_interaction.go b/internal/mcp/handlers_interaction.goindex 244754c7..69228491 100644--- a/internal/mcp/handlers_interaction.go+++ b/internal/mcp/handlers_interaction.go@@ -326,11 +326,7 @@ func handleKeyboard(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.if nodeID, ok := optInt(r, "nodeId"); ok && nodeID > 0 {payload["nodeId"] = nodeID}- body, code, err := c.Post(ctx, routedPathWithBody(r, "/action", payload), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, routedPathWithBody(r, "/action", payload), payload))}}diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex d367350f..24ba3b04 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -129,11 +129,7 @@ func handleSnapshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.if v, ok := optBool(r, "noAnimations"); ok && v {q.Set("noAnimations", "true")}- body, code, err := c.GetCapturingVocab(ctx, "/snapshot", routedQuery(r, q), optString(r, "tabId"))- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.GetCapturingVocab(ctx, "/snapshot", routedQuery(r, q), optString(r, "tabId")))}}@@ -156,22 +152,14 @@ func handleFrame(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Calif tabID != "" {q.Set("tabId", tabID)}- body, code, err := c.Get(ctx, "/frame", routedQuery(r, q))- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/frame", routedQuery(r, q)))}payload := map[string]any{"target": target}if tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, routedPath(r, "/frame"), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, routedPath(r, "/frame"), payload))}}@@ -416,10 +404,6 @@ func handleGetText(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Cif v, ok := optInt(r, "maxChars"); ok && v > 0 {q.Set("maxChars", strconv.Itoa(v))}- body, code, err := c.Get(ctx, "/text", routedQuery(r, q))- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/text", routedQuery(r, q)))}}diff --git a/internal/mcp/handlers_network.go b/internal/mcp/handlers_network.goindex 2a01cb16..a0cb4907 100644--- a/internal/mcp/handlers_network.go+++ b/internal/mcp/handlers_network.go@@ -32,11 +32,7 @@ func handleNetwork(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Cif bufSize, ok := optFloat(r, "bufferSize"); ok {q.Set("bufferSize", fmt.Sprintf("%d", int(bufSize)))}- body, code, err := c.Get(ctx, "/network", q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/network", q))}}@@ -54,11 +50,7 @@ func handleNetworkDetail(c *Client) func(context.Context, mcp.CallToolRequest) (q.Set("body", "true")}path := "/network/" + url.PathEscape(requestID)- body, code, err := c.Get(ctx, path, q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, path, q))}}@@ -68,11 +60,7 @@ func handleNetworkClear(c *Client) func(context.Context, mcp.CallToolRequest) (*if tabID := optString(r, "tabId"); tabID != "" {q.Set("tabId", tabID)}- body, code, err := c.Post(ctx, "/network/clear?"+q.Encode(), nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, "/network/clear?"+q.Encode(), nil))}}@@ -110,11 +98,7 @@ func handleNetworkRoute(c *Client) func(context.Context, mcp.CallToolRequest) (*}path := tabNetworkRoutePath(tabID)- respBody, code, err := c.Post(ctx, path, payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(respBody, code)+ return toolResult(c.Post(ctx, path, payload))}}@@ -129,11 +113,7 @@ func handleNetworkUnroute(c *Client) func(context.Context, mcp.CallToolRequest)q.Set("pattern", pattern)}path := tabNetworkRoutePath(tabID)- respBody, code, err := c.Delete(ctx, path, q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(respBody, code)+ return toolResult(c.Delete(ctx, path, q))}}@@ -144,11 +124,7 @@ func handleNetworkRules(c *Client) func(context.Context, mcp.CallToolRequest) (*return mcp.NewToolResultError(err.Error()), nil}path := tabNetworkRoutePath(tabID)- respBody, code, err := c.Get(ctx, path, nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(respBody, code)+ return toolResult(c.Get(ctx, path, nil))}}diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.goindex cd5d7ce4..6563a086 100644--- a/internal/mcp/handlers_record.go+++ b/internal/mcp/handlers_record.go@@ -65,11 +65,7 @@ func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*mpayload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/record/start", payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, "/record/start", payload))}}@@ -200,10 +196,6 @@ func safeRecordPath(file string) (string, error) {func handleRecordStatus(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {- body, code, err := c.Get(ctx, "/record/status", nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/record/status", nil))}}diff --git a/internal/mcp/handlers_scrape.go b/internal/mcp/handlers_scrape.goindex 6055319b..2532f6a5 100644--- a/internal/mcp/handlers_scrape.go+++ b/internal/mcp/handlers_scrape.go@@ -52,11 +52,7 @@ func handleScrape(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Ca}// A multi-page scrape legitimately runs for minutes; the default MCP// client timeout is far too short for it.- body, code, err := c.withTimeout(scrapeMCPTimeout).Post(ctx, routedPathWithBody(r, "/scrape", payload), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.withTimeout(scrapeMCPTimeout).Post(ctx, routedPathWithBody(r, "/scrape", payload), payload))}}diff --git a/internal/mcp/handlers_tabs.go b/internal/mcp/handlers_tabs.goindex 33707578..0e910ec1 100644--- a/internal/mcp/handlers_tabs.go+++ b/internal/mcp/handlers_tabs.go@@ -12,11 +12,7 @@ import (func handleListTabs(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return func(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {- body, code, err := c.Get(ctx, "/tabs", nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/tabs", nil))}}@@ -26,11 +22,7 @@ func handleCloseTab(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.if tabID := optTrimmedString(r, "tabId"); tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/close", payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, "/close", payload))}}@@ -51,11 +43,7 @@ func handleHandoff(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Cif timeoutMs, ok := optInt(r, "timeoutMs"); ok {payload["timeoutMs"] = timeoutMs}- body, code, err := c.Post(ctx, tabRoutePath(tabID, "handoff"), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, tabRoutePath(tabID, "handoff"), payload))}}@@ -69,11 +57,7 @@ func handleResume(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Caif status := optTrimmedString(r, "status"); status != "" {payload["status"] = status}- body, code, err := c.Post(ctx, tabRoutePath(tabID, "resume"), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, tabRoutePath(tabID, "resume"), payload))}}@@ -83,21 +67,13 @@ func handleHandoffStatus(c *Client) func(context.Context, mcp.CallToolRequest) (if err != nil {return mcp.NewToolResultError(err.Error()), nil}- body, code, err := c.Get(ctx, tabRoutePath(tabID, "handoff"), nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, tabRoutePath(tabID, "handoff"), nil))}}func handleHealth(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return func(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {- body, code, err := c.Get(ctx, "/health", nil)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/health", nil))}}@@ -107,11 +83,7 @@ func handleCookies(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Cif tabID := optString(r, "tabId"); tabID != "" {q.Set("tabId", tabID)}- body, code, err := c.Get(ctx, "/cookies", q)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Get(ctx, "/cookies", q))}}diff --git a/internal/mcp/handlers_wait.go b/internal/mcp/handlers_wait.goindex 948e8eb0..9fb4127c 100644--- a/internal/mcp/handlers_wait.go+++ b/internal/mcp/handlers_wait.go@@ -68,9 +68,5 @@ func callWaitEndpoint(ctx context.Context, c *Client, r mcp.CallToolRequest, payif tabID := optString(r, "tabId"); tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, routedPath(r, "/wait"), payload)- if err != nil {- return mcp.NewToolResultError(err.Error()), nil- }- return resultFromBytes(body, code)+ return toolResult(c.Post(ctx, routedPath(r, "/wait"), payload))}diff --git a/internal/mcp/tool_result_test.go b/internal/mcp/tool_result_test.gonew file mode 100644index 00000000..f32964b8--- /dev/null+++ b/internal/mcp/tool_result_test.go@@ -0,0 +1,234 @@+package mcp++import (+ "errors"+ "go/ast"+ "go/parser"+ "go/token"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/mark3labs/mcp-go/mcp"+)++func inlineTail(body []byte, code int, err error) (*mcp.CallToolResult, error) {+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(body, code)+}++func TestToolResultMatchesTheInlineTailItReplaced(t *testing.T) {+ rows := []struct {+ name string+ body []byte+ code int+ err error+ isError bool+ }{+ {"transport error", nil, 0, errors.New("dial tcp 127.0.0.1:9867: connection refused"), true},+ {"2xx body", []byte(`{"ok":true}`), 200, nil, false},+ {"4xx body", []byte(`{"error":"tab not found"}`), 404, nil, true},+ {"2xx body reporting no success", []byte(`{"set":0,"failed":2}`), 200, nil, true},+ }+ for _, row := range rows {+ t.Run(row.name, func(t *testing.T) {+ got, gotErr := toolResult(row.body, row.code, row.err)+ want, wantErr := inlineTail(row.body, row.code, row.err)++ if !reflect.DeepEqual(got, want) || !reflect.DeepEqual(gotErr, wantErr) {+ t.Fatalf("toolResult = %#v, %v; inline tail = %#v, %v", got, gotErr, want, wantErr)+ }+ if got.IsError != row.isError {+ t.Fatalf("IsError = %v, want %v", got.IsError, row.isError)+ }+ })+ }+}++func clientMethods(files []*ast.File) map[string]bool {+ methods := map[string]bool{}+ for _, file := range files {+ for _, decl := range file.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Recv == nil || len(fn.Recv.List) != 1 {+ continue+ }+ recv := fn.Recv.List[0].Type+ if star, ok := recv.(*ast.StarExpr); ok {+ recv = star.X+ }+ if ident, ok := recv.(*ast.Ident); ok && ident.Name == "Client" {+ methods[fn.Name.Name] = true+ }+ }+ }+ return methods+}++func inlineTailSites(fset *token.FileSet, files []*ast.File, methods map[string]bool) []string {+ var sites []string+ for _, file := range files {+ ast.Inspect(file, func(n ast.Node) bool {+ block, ok := n.(*ast.BlockStmt)+ if !ok {+ return true+ }+ for i := 0; i+2 < len(block.List); i++ {+ body, code, ok := clientCallTriple(block.List[i], methods)+ if ok && returnsErrorResult(block.List[i+1]) && returnsResultFromBytes(block.List[i+2], body, code) {+ sites = append(sites, fset.Position(block.List[i].Pos()).String())+ }+ }+ return true+ })+ }+ return sites+}++func clientCallTriple(stmt ast.Stmt, methods map[string]bool) (string, string, bool) {+ assign, ok := stmt.(*ast.AssignStmt)+ if !ok || len(assign.Lhs) != 3 || len(assign.Rhs) != 1 {+ return "", "", false+ }+ call, ok := assign.Rhs[0].(*ast.CallExpr)+ if !ok {+ return "", "", false+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok || !methods[sel.Sel.Name] {+ return "", "", false+ }+ names := make([]string, 3)+ for i, lhs := range assign.Lhs {+ ident, ok := lhs.(*ast.Ident)+ if !ok {+ return "", "", false+ }+ names[i] = ident.Name+ }+ return names[0], names[1], names[2] == "err"+}++func returnsErrorResult(stmt ast.Stmt) bool {+ ifStmt, ok := stmt.(*ast.IfStmt)+ if !ok || ifStmt.Init != nil || ifStmt.Else != nil || exprString(ifStmt.Cond) != "err != nil" || len(ifStmt.Body.List) != 1 {+ return false+ }+ ret, ok := ifStmt.Body.List[0].(*ast.ReturnStmt)+ return ok && len(ret.Results) == 2 &&+ exprString(ret.Results[0]) == "mcp.NewToolResultError(err.Error())" &&+ exprString(ret.Results[1]) == "nil"+}++func returnsResultFromBytes(stmt ast.Stmt, body, code string) bool {+ ret, ok := stmt.(*ast.ReturnStmt)+ return ok && len(ret.Results) == 1 && exprString(ret.Results[0]) == "resultFromBytes("+body+", "+code+")"+}++func exprString(e ast.Expr) string {+ switch v := e.(type) {+ case *ast.Ident:+ return v.Name+ case *ast.SelectorExpr:+ return exprString(v.X) + "." + v.Sel.Name+ case *ast.BinaryExpr:+ return exprString(v.X) + " " + v.Op.String() + " " + exprString(v.Y)+ case *ast.CallExpr:+ args := make([]string, len(v.Args))+ for i, arg := range v.Args {+ args[i] = exprString(arg)+ }+ return exprString(v.Fun) + "(" + strings.Join(args, ", ") + ")"+ }+ return "?"+}++func parsePackageSources(t *testing.T) (*token.FileSet, []*ast.File) {+ t.Helper()+ paths, err := filepath.Glob("*.go")+ if err != nil {+ t.Fatal(err)+ }+ fset := token.NewFileSet()+ var files []*ast.File+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.go") {+ continue+ }+ file, err := parser.ParseFile(fset, path, nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", path, err)+ }+ files = append(files, file)+ }+ if len(files) < 15 {+ t.Fatalf("parsed %d mcp sources; the census would pass vacuously", len(files))+ }+ return fset, files+}++func TestNoHandlerSpellsOutTheToolResultTail(t *testing.T) {+ fset, files := parsePackageSources(t)+ methods := clientMethods(files)+ for _, want := range []string{"Get", "Post", "Delete", "GetCapturingVocab", "withTimeout"} {+ if !methods[want] {+ t.Fatalf("Client method %s not found; the census would miss its tails", want)+ }+ }++ for _, site := range inlineTailSites(fset, files, methods) {+ t.Errorf("%s spells out the call/error/resultFromBytes tail; return toolResult(<call>) instead", site)+ }+}++func TestTheToolResultTailCensusSeesPlantedCopiesAndNotNearMisses(t *testing.T) {+ _, files := parsePackageSources(t)+ methods := clientMethods(files)+ const planted = `package mcp+func plain(c *Client) (*mcp.CallToolResult, error) {+ body, code, err := c.Get(ctx, "/text", nil)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(body, code)+}+func chained(c *Client) (*mcp.CallToolResult, error) {+ out, status, err := c.withTimeout(d).Post(ctx, "/scrape", p)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(out, status)+}+func vocab(c *Client) (*mcp.CallToolResult, error) {+ body, code, err := c.GetCapturingVocab(ctx, "/snapshot", q, tab)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(body, code)+}+func nearMiss(c *Client) (*mcp.CallToolResult, error) {+ body, code, err := c.Get(ctx, "/cookies", nil)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ if code >= 400 {+ return resultFromBytes(body, code)+ }+ return inspect(body)+}+`+ fset := token.NewFileSet()+ file, err := parser.ParseFile(fset, "planted.go", planted, 0)+ if err != nil {+ t.Fatal(err)+ }++ sites := inlineTailSites(fset, []*ast.File{file}, methods)++ if len(sites) != 3 {+ t.Fatalf("census found %v in the planted source, want the three tails and not the near miss", sites)+ }+}