High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(network): list a tab's interception rules from the CLI and MCP (PIN-354)
Luigi Agosti5ba60f09a6f8
diff --git a/cmd/pinchtab/cmd_cli_network_route.go b/cmd/pinchtab/cmd_cli_network_route.goindex 1d156a17..b036a4fe 100644--- a/cmd/pinchtab/cmd_cli_network_route.go+++ b/cmd/pinchtab/cmd_cli_network_route.go@@ -38,3 +38,18 @@ var networkUnrouteCmd = &cobra.Command{})},}++var networkRulesCmd = &cobra.Command{+ Use: "rules",+ Short: "List the interception rules installed on the active tab",+ Long: `List every interception rule on the active tab, one per line as pattern (action):+continue passes the request through, abort blocks it, fulfill answers it with the+rule's body instead of the real server. Rules survive navigation, so a tab you did not+set up can be mocking or blocking traffic; an empty list means it does neither.`,+ Args: cobra.NoArgs,+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.NetworkRules(rt.client, rt.base, rt.token, cmd)+ })+ },+}diff --git a/cmd/pinchtab/cmd_cli_network_route_test.go b/cmd/pinchtab/cmd_cli_network_route_test.gonew file mode 100644index 00000000..d564bca6--- /dev/null+++ b/cmd/pinchtab/cmd_cli_network_route_test.go@@ -0,0 +1,17 @@+package main++import (+ "slices"+ "testing"+)++func TestNetworkRulesIsRegisteredBesideRouteAndUnroute(t *testing.T) {+ if !slices.Contains(networkCmd.Commands(), networkRulesCmd) {+ t.Fatal("network rules is not registered under network")+ }+ for _, flag := range []string{"tab", "json"} {+ if networkRulesCmd.Flags().Lookup(flag) == nil {+ t.Errorf("network rules lacks --%s, which route and unroute take", flag)+ }+ }+}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex 0505dfae..c962e2ec 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -43,7 +43,7 @@ func registerBrowserCommands() {keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)mouseCmd.AddCommand(mouseMoveCmd, mouseDownCmd, mouseUpCmd, mouseWheelCmd)- networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd)+ networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd, networkRulesCmd)recordCmd.AddCommand(recordStartCmd, recordStopCmd, recordStatusCmd)configureBrowserFlags()@@ -343,8 +343,8 @@ func configureBrowserFlags() {networkRouteCmd.Flags().String("content-type", "", "(With --body) Response Content-Type (default application/json)")networkRouteCmd.Flags().Int("status", 0, "(With --body) Response status code (default 200)")networkRouteCmd.Flags().String("method", "", "Limit to an HTTP method (GET, POST, ...). Fulfill rules without --method skip OPTIONS preflights to avoid breaking CORS.")- addTabFlag(networkRouteCmd, networkUnrouteCmd)- addJSONFlag(networkRouteCmd, networkUnrouteCmd)+ addTabFlag(networkRouteCmd, networkUnrouteCmd, networkRulesCmd)+ addJSONFlag(networkRouteCmd, networkUnrouteCmd, networkRulesCmd)networkCmd.Flags().String("filter", "", "URL pattern filter")networkCmd.Flags().String("method", "", "HTTP method filter (GET, POST, etc)")diff --git a/docs/mcp.md b/docs/mcp.mdindex 858299d1..905f91d4 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -114,7 +114,7 @@ PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://remote:9867 mcp## Available Tools-PinchTab currently exposes 38 tools:+PinchTab currently exposes 39 tools:- Navigation: 9- Interaction: 8@@ -189,6 +189,7 @@ PinchTab currently exposes 38 tools:- `pinchtab_network_clear`- `pinchtab_network_route`- `pinchtab_network_unroute`+- `pinchtab_network_rules`### Diagnosticsdiff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.mdindex ace09d84..c3577e01 100644--- a/docs/reference/mcp-tools.md+++ b/docs/reference/mcp-tools.md@@ -93,6 +93,7 @@ All element-action tools accept the unified `selector` and the legacy aliases `r| `pinchtab_network_clear` | `tabId` | Clears one tab or all tabs when omitted || `pinchtab_network_route` | `tabId` required, `pattern` required, `action`, `body`, `contentType`, `status`, `resourceType`, `method` | Install a request-interception rule on a tab. `action` is `continue` (default), `abort`, or `fulfill`. `fulfill` is blocked on hosts in `security.allowedDomains` and falls through to a real fetch on those hosts || `pinchtab_network_unroute` | `tabId` required, `pattern` | Remove a tab's interception rule by pattern, or all rules when `pattern` is omitted |+| `pinchtab_network_rules` | `tabId` required | List a tab's interception rules as `{tabId, rules}`, each rule naming its `pattern` and `action` (`continue`, `abort`, `fulfill`). Rules survive navigation; an empty `rules` list means the tab mocks and blocks nothing |## Recordingdiff --git a/internal/cli/actions/actions_network_route.go b/internal/cli/actions/actions_network_route.goindex 1bb686e7..75247e68 100644--- a/internal/cli/actions/actions_network_route.go+++ b/internal/cli/actions/actions_network_route.go@@ -98,3 +98,39 @@ func NetworkUnroute(client *http.Client, base, token string, cmd *cobra.Command,fmt.Println("routes cleared")}}++func NetworkRules(client *http.Client, base, token string, cmd *cobra.Command) {+ path := "/network/route"+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {+ path = fmt.Sprintf("/tabs/%s/network/route", url.PathEscape(tab))+ }+ result := requireMap(apiclient.DoGet(client, base, token, path, nil), 1, "Failed to list routes")++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ printIndented(result)+ return+ }+ rules, _ := result["rules"].([]any)+ if len(rules) == 0 {+ fmt.Println("no interception rules: this tab mocks and blocks nothing")+ return+ }+ for _, entry := range rules {+ rule, _ := entry.(map[string]any)+ fmt.Println(describeRouteRule(rule))+ }+}++func describeRouteRule(rule map[string]any) string {+ line := fmt.Sprintf("%v (%v)", rule["pattern"], rule["action"])+ for _, key := range []string{"method", "resourceType", "status", "contentType"} {+ if v, ok := rule[key]; ok && v != nil && v != "" && v != float64(0) {+ line += fmt.Sprintf(" %s=%v", key, v)+ }+ }+ if body, ok := rule["body"].(string); ok && body != "" {+ line += fmt.Sprintf(" body=%d bytes", len(body))+ }+ return line+}diff --git a/internal/cli/actions/actions_network_route_test.go b/internal/cli/actions/actions_network_route_test.gonew file mode 100644index 00000000..ba0403a3--- /dev/null+++ b/internal/cli/actions/actions_network_route_test.go@@ -0,0 +1,49 @@+package actions++import (+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++const routeRulesPayload = `{"tabId":"t1","rules":[{"pattern":"api/users","action":"fulfill","body":"{\"ok\":true}","contentType":"application/json","status":200},{"pattern":"*.png","action":"abort"}]}`++func networkRulesCommand(tab string) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("tab", "", "")+ cmd.Flags().Bool("json", false, "")+ _ = cmd.Flags().Set("tab", tab)+ return cmd+}++func TestNetworkRulesListsEveryRuleWithItsAction(t *testing.T) {+ m := newMockServer()+ defer m.close()+ m.responses["GET /tabs/t1/network/route"] = mockResponse{statusCode: 200, body: routeRulesPayload}++ out := captureStdout(t, func() {+ NetworkRules(m.server.Client(), m.base(), "", networkRulesCommand("t1"))+ })+ if m.lastMethod != "GET" || m.lastPath != "/tabs/t1/network/route" {+ t.Fatalf("listed via %s %s, want GET /tabs/t1/network/route", m.lastMethod, m.lastPath)+ }+ for _, want := range []string{"api/users (fulfill)", "*.png (abort)"} {+ if !strings.Contains(out, want) {+ t.Errorf("listing %q does not carry %q; a reader must tell a fulfill from an abort", out, want)+ }+ }+}++func TestNetworkRulesOnATabWithNoRulesAnswersNone(t *testing.T) {+ m := newMockServer()+ defer m.close()+ m.responses["GET /tabs/t1/network/route"] = mockResponse{statusCode: 200, body: `{"tabId":"t1","rules":[]}`}++ out := captureStdout(t, func() {+ NetworkRules(m.server.Client(), m.base(), "", networkRulesCommand("t1"))+ })+ if !strings.Contains(out, "no interception rules") {+ t.Fatalf("an empty listing must say none, got %q", out)+ }+}diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.goindex a06c3c68..84819106 100644--- a/internal/mcp/handlers.go+++ b/internal/mcp/handlers.go@@ -62,6 +62,7 @@ func rawHandlerMap(c *Client) map[string]func(context.Context, mcp.CallToolReque"pinchtab_network_clear": handleNetworkClear(c),"pinchtab_network_route": handleNetworkRoute(c),"pinchtab_network_unroute": handleNetworkUnroute(c),+ "pinchtab_network_rules": handleNetworkRules(c),"pinchtab_console": handleConsole(c),"pinchtab_errors": handleErrors(c),diff --git a/internal/mcp/handlers_network.go b/internal/mcp/handlers_network.goindex 6f7a5bda..868f1365 100644--- a/internal/mcp/handlers_network.go+++ b/internal/mcp/handlers_network.go@@ -136,3 +136,18 @@ func handleNetworkUnroute(c *Client) func(context.Context, mcp.CallToolRequest)return resultFromBytes(respBody, code)}}++func handleNetworkRules(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ tabID, err := r.RequireString("tabId")+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ path := "/tabs/" + url.PathEscape(tabID) + "/network/route"+ respBody, code, err := c.Get(ctx, path, nil)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(respBody, code)+ }+}diff --git a/internal/mcp/handlers_network_test.go b/internal/mcp/handlers_network_test.goindex edf59daf..17e2207b 100644--- a/internal/mcp/handlers_network_test.go+++ b/internal/mcp/handlers_network_test.go@@ -1,6 +1,8 @@package mcpimport (+ "net/http"+ "net/http/httptest""strings""testing")@@ -174,3 +176,47 @@ func TestHandleNetworkUnroute_All(t *testing.T) {t.Errorf("expected /tabs/t1/network/route path, got %s", text)}}++func TestHandleNetworkRulesReportsWhatTheRouteReports(t *testing.T) {+ const payload = `{"tabId":"t1","rules":[{"pattern":"api/users","action":"fulfill","body":"{\"ok\":true}"},{"pattern":"*.png","action":"abort"}]}`+ var gotMethod, gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(payload))+ }))+ defer srv.Close()++ r := callTool(t, "pinchtab_network_rules", map[string]any{"tabId": "t1"}, srv)+ if r.IsError {+ t.Fatalf("listing rules answered an error: %s", resultText(t, r))+ }+ if gotMethod != http.MethodGet || gotPath != "/tabs/t1/network/route" {+ t.Fatalf("listed via %s %s, want GET /tabs/t1/network/route", gotMethod, gotPath)+ }+ text := resultText(t, r)+ for _, want := range []string{`"pattern":"api/users"`, `"action":"fulfill"`, `"pattern":"*.png"`, `"action":"abort"`} {+ if !strings.Contains(text, want) {+ t.Errorf("tool result %s does not carry %s", text, want)+ }+ }+}++func TestHandleNetworkRulesOnATabWithNoRulesIsASuccessAnsweringNone(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"tabId":"t1","rules":[]}`))+ }))+ defer srv.Close()++ r := callTool(t, "pinchtab_network_rules", map[string]any{"tabId": "t1"}, srv)+ if r.IsError {+ t.Fatalf("an empty listing is a success, got error: %s", resultText(t, r))+ }+ if text := resultText(t, r); !strings.Contains(text, `"rules":[]`) {+ t.Fatalf("an empty listing must say none explicitly, got %s", text)+ }+ if r := callTool(t, "pinchtab_network_rules", map[string]any{}, srv); !r.IsError {+ t.Fatal("the tab is required, as it is on route and unroute")+ }+}diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.goindex 36ff1e9f..74ece2ec 100644--- a/internal/mcp/server_test.go+++ b/internal/mcp/server_test.go@@ -18,8 +18,8 @@ func TestNewServerRegistersAllTools(t *testing.T) {// The server should have registered all tools.// We verify by checking that NewServer doesn't panic — the panic// in NewServer fires if any tool lacks a handler.- if len(tools) != 38 {- t.Errorf("expected 38 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))+ if len(tools) != 39 {+ t.Errorf("expected 39 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))}}diff --git a/internal/mcp/testdata/preamble_budget.json b/internal/mcp/testdata/preamble_budget.jsonindex 7ffb44f7..4cb2c7f3 100644--- a/internal/mcp/testdata/preamble_budget.json+++ b/internal/mcp/testdata/preamble_budget.json@@ -2,9 +2,9 @@{"surface": "mcp:allTools","minBytes": 18092,- "maxBytes": 37504,- "takenOn": "2026-09-03",- "commit": "8a12cd4a"+ "maxBytes": 38200,+ "takenOn": "2026-09-11",+ "commit": "d866267e"},{"surface": "skills/pinchtab-mcp/SKILL.md",diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex e4b35190..e2cb5b31 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -305,6 +305,10 @@ func allTools() []mcp.Tool {requiredTabIDParam(),mcp.WithString("pattern", mcp.Description("Pattern to remove (omit to clear all rules)")),),+ mcp.NewTool("pinchtab_network_rules",+ mcp.WithDescription("List the interception rules installed on a tab: returns {tabId, rules:[{pattern, action, ...}]} where action is continue, abort or fulfill (with body, contentType, status, resourceType or method when set). Rules survive navigation, so check this on a tab you did not set up; an empty rules list means the tab mocks and blocks nothing."),+ requiredTabIDParam(),+ ),mcp.NewTool("pinchtab_console",mcp.WithDescription("Read the tab's captured browser console logs (console.log/warn/error and friends). Check this when a page looks healthy in the snapshot but does not respond to actions — the log often says why. A payload full of error-level logs is still a successful call."),