High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add MCP back, forward and reload tools (PIN-065)
Luigi Agosti14f4eb15618e
diff --git a/docs/mcp.md b/docs/mcp.mdindex 3305ab08..71269e1a 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -81,12 +81,13 @@ pinchtab --server http://remote:9867 mcp## Available Tools-PinchTab currently exposes 39 tools:+PinchTab currently exposes 46 tools:-- Navigation: 5+- Navigation: 9- Interaction: 9- Keyboard: 4- Content: 3+- Recording: 3- Site: 1- Tab management: 5- Wait utilities: 6@@ -96,9 +97,13 @@ PinchTab currently exposes 39 tools:### Navigation- `pinchtab_navigate`+- `pinchtab_back` — go back one history entry; returns the tab ID and the URL landed on+- `pinchtab_forward` — go forward one history entry; returns the tab ID and the URL landed on+- `pinchtab_reload` — reload the current page; returns the tab ID and the URL landed on- `pinchtab_snapshot`- `pinchtab_frame`- `pinchtab_screenshot`+- `pinchtab_capture` — paired screenshot + snapshot from one DOM epoch- `pinchtab_get_text`### Interaction@@ -126,6 +131,12 @@ PinchTab currently exposes 39 tools:- `pinchtab_pdf`- `pinchtab_find`+### Recording++- `pinchtab_record_start`+- `pinchtab_record_stop`+- `pinchtab_record_status`+### Site- `pinchtab_scrape` — crawl a site to markdown (HTTP-first, browser-enrich thin/JS pages). Use `preview=true` for a cheap outline, then expand chosen URLs with `only`.@@ -179,6 +190,11 @@ The normal MCP browser loop is:2. Call `pinchtab_snapshot` to inspect page structure and collect refs3. Call `pinchtab_click`, `pinchtab_type`, or other action tools with structured arguments4. Call `pinchtab_wait_*` or `pinchtab_network` when needed+5. Call `pinchtab_back` to leave a dead end, or `pinchtab_reload` to retry the page++`pinchtab_back`, `pinchtab_forward` and `pinchtab_reload` take an optional `tabId`+and `snap`, so `snap: true` returns the page after the navigation in one+round-trip.`pinchtab_snapshot` supports MCP-safe output controls:diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.goindex bb35847f..588a77b6 100644--- a/internal/mcp/handlers.go+++ b/internal/mcp/handlers.go@@ -24,6 +24,9 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)func rawHandlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error){"pinchtab_navigate": handleNavigate(c),+ "pinchtab_back": handleHistoryNav(c, "back"),+ "pinchtab_forward": handleHistoryNav(c, "forward"),+ "pinchtab_reload": handleHistoryNav(c, "reload"),"pinchtab_snapshot": handleSnapshot(c),"pinchtab_frame": handleFrame(c),"pinchtab_screenshot": handleScreenshot(c),diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex dbd5e45a..2457b5c7 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -35,23 +35,60 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.return resultFromBytes(body, code)}- if snap, ok := optBool(r, "snap"); ok && snap {- q := url.Values{}- q.Set("filter", "interactive")- q.Set("format", "compact")- if tabID != "" {- q.Set("tabId", tabID)- } else if returnedTabID := responseStringField(body, "tabId"); returnedTabID != "" {- q.Set("tabId", returnedTabID)- }- snapBody, _, snapErr := c.Get(ctx, "/snapshot", q)- if snapErr == nil {- return mcp.NewToolResultText(string(body) + "\n" + string(snapBody)), nil- }- }+ return withOptionalSnapshot(ctx, c, r, tabID, body, code)+ }+}+// withOptionalSnapshot appends the post-navigation snapshot when snap is set, so a+// client can act and see the result in one round-trip. The tab is taken from the+// request when given and otherwise from the tab the response reports, which is what+// makes snap work for a call that did not name a tab. A snapshot failure is not+// fatal: the navigation already happened and its result is the answer.+func withOptionalSnapshot(ctx context.Context, c *Client, r mcp.CallToolRequest, tabID string, body []byte, code int) (*mcp.CallToolResult, error) {+ snap, ok := optBool(r, "snap")+ if !ok || !snap {+ return resultFromBytes(body, code)+ }+ q := url.Values{}+ q.Set("filter", "interactive")+ q.Set("format", "compact")+ if tabID != "" {+ q.Set("tabId", tabID)+ } else if returnedTabID := responseStringField(body, "tabId"); returnedTabID != "" {+ q.Set("tabId", returnedTabID)+ }+ snapBody, _, snapErr := c.Get(ctx, "/snapshot", routedQuery(r, q))+ if snapErr != nil {return resultFromBytes(body, code)}+ return mcp.NewToolResultText(string(body) + "\n" + string(snapBody)), nil+}++// handleHistoryNav serves pinchtab_back, pinchtab_forward and pinchtab_reload. The+// verb is data: the three differ only in the route they post to, so one handler+// takes it as a parameter rather than three near-identical copies drifting apart.+//+// Two things differ from handleNavigate, both forced by the endpoint. /back,+// /forward and /reload never parse a request body — handleHistoryNav reads tabId+// from the query and the tab-scoped route from the path — so no body is sent at+// all, and browser travels in the query via routedPath. Putting browser in a body+// the endpoint does not read would be silently dropped.+func handleHistoryNav(c *Client, verb string) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ tabID := optString(r, "tabId")+ path := "/" + verb+ if tabID != "" {+ path = "/tabs/" + url.PathEscape(tabID) + "/" + verb+ }+ body, code, err := c.Post(ctx, routedPath(r, path), nil)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ if code >= 400 {+ return resultFromBytes(body, code)+ }+ return withOptionalSnapshot(ctx, c, r, tabID, body, code)+ }}func responseStringField(body []byte, field string) string {diff --git a/internal/mcp/handlers_navigation_test.go b/internal/mcp/handlers_navigation_test.goindex 6911cb06..d55cb24b 100644--- a/internal/mcp/handlers_navigation_test.go+++ b/internal/mcp/handlers_navigation_test.go@@ -3,6 +3,7 @@ package mcpimport ("encoding/base64""encoding/json"+ "io""net/http""net/http/httptest""net/url"@@ -649,3 +650,188 @@ func TestBooleanArgumentsAcceptStringForm(t *testing.T) {})}}++// historyRecorder captures what actually went on the wire, because the two things+// these tools must get right are both invisible in a response: /back, /forward and+// /reload never parse a request body, so a body is not merely redundant but a sign+// the handler was copied from pinchtab_navigate, and browser has to travel in the+// query or the router cannot see it.+// Distinct from routing_test.go's recordingPinchTab, which keeps only the last+// request and only its parsed JSON body: snap makes two calls, and "was any body+// sent at all" is the assertion these tools need, so the raw bytes and the+// Content-Type both have to survive.+type historyRequest struct {+ method string+ path string+ query url.Values+ body string+ contentType string+}++func historyRecorder(t *testing.T) (*httptest.Server, *[]historyRequest) {+ t.Helper()+ seen := &[]historyRequest{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ raw, _ := io.ReadAll(r.Body)+ *seen = append(*seen, historyRequest{+ method: r.Method,+ path: r.URL.Path,+ query: r.URL.Query(),+ body: string(raw),+ contentType: r.Header.Get("Content-Type"),+ })+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == "/snapshot" {+ _, _ = w.Write([]byte(`{"nodes":[]}`))+ return+ }+ _, _ = w.Write([]byte(`{"tabId":"ABC123","url":"https://example.com/landed"}`))+ }))+ t.Cleanup(srv.Close)+ return srv, seen+}++func TestHistoryToolsPostToTheirRouteWithNoBody(t *testing.T) {+ for tool, verb := range map[string]string{+ "pinchtab_back": "back",+ "pinchtab_forward": "forward",+ "pinchtab_reload": "reload",+ } {+ t.Run(tool, func(t *testing.T) {+ srv, seen := historyRecorder(t)++ result := callTool(t, tool, map[string]any{}, srv)+ if result.IsError {+ t.Fatalf("%s failed: %s", tool, resultText(t, result))+ }+ if len(*seen) != 1 {+ t.Fatalf("requests = %d, want exactly one", len(*seen))+ }+ got := (*seen)[0]++ if got.method != http.MethodPost {+ t.Errorf("method = %s, want POST", got.method)+ }+ if got.path != "/"+verb {+ t.Errorf("path = %q, want /%s", got.path, verb)+ }+ if got.body != "" {+ t.Errorf("a body was sent to /%s, which never parses one: %q", verb, got.body)+ }+ if got.contentType != "" {+ t.Errorf("Content-Type = %q on a bodyless request", got.contentType)+ }++ // The landed URL and the tab ID both come back from the response.+ text := resultText(t, result)+ for _, want := range []string{"ABC123", "https://example.com/landed"} {+ if !strings.Contains(text, want) {+ t.Errorf("result %q does not carry %q", text, want)+ }+ }+ })+ }+}++func TestHistoryToolsScopeToTheTabPathWhenGivenATabID(t *testing.T) {+ for tool, verb := range map[string]string{+ "pinchtab_back": "back",+ "pinchtab_forward": "forward",+ "pinchtab_reload": "reload",+ } {+ t.Run(tool, func(t *testing.T) {+ srv, seen := historyRecorder(t)++ callTool(t, tool, map[string]any{"tabId": "t1"}, srv)+ if len(*seen) != 1 {+ t.Fatalf("requests = %d, want exactly one", len(*seen))+ }+ got := (*seen)[0]+ if want := "/tabs/t1/" + verb; got.path != want {+ t.Errorf("path = %q, want %q", got.path, want)+ }+ if got.body != "" {+ t.Errorf("a body was sent alongside the tab-scoped path: %q", got.body)+ }+ })+ }+}++// browser decides WHICH instance serves the call and that router reads the query+// only, so a body value — the form pinchtab_navigate uses — would be invisible here.+func TestHistoryToolsForwardBrowserInTheQuery(t *testing.T) {+ for _, tool := range []string{"pinchtab_back", "pinchtab_forward", "pinchtab_reload"} {+ t.Run(tool, func(t *testing.T) {+ srv, seen := historyRecorder(t)++ callTool(t, tool, map[string]any{"browser": "cloak"}, srv)+ got := (*seen)[0]++ if got.query.Get("browser") != "cloak" {+ t.Errorf("query browser = %q, want cloak — the router reads the query only", got.query.Get("browser"))+ }+ if got.body != "" {+ t.Errorf("browser was also put in a body the endpoint never parses: %q", got.body)+ }+ })+ }+}++// snap must behave as it does for pinchtab_navigate, including for a call that named+// no tab: the snapshot is scoped to the tab the navigation reported.+func TestHistoryToolsSnapAppendsTheSnapshot(t *testing.T) {+ for _, tool := range []string{"pinchtab_back", "pinchtab_forward", "pinchtab_reload"} {+ t.Run(tool, func(t *testing.T) {+ srv, seen := historyRecorder(t)++ result := callTool(t, tool, map[string]any{"snap": true}, srv)+ if len(*seen) != 2 {+ t.Fatalf("requests = %d, want the navigation and the snapshot", len(*seen))+ }+ snapshot := (*seen)[1]+ if snapshot.path != "/snapshot" {+ t.Fatalf("second request path = %q, want /snapshot", snapshot.path)+ }+ if got := snapshot.query.Get("tabId"); got != "ABC123" {+ t.Errorf("snapshot tabId = %q, want the tab the navigation reported", got)+ }+ if got := snapshot.query.Get("filter"); got != "interactive" {+ t.Errorf("snapshot filter = %q, want interactive", got)+ }+ if text := resultText(t, result); !strings.Contains(text, `"nodes"`) {+ t.Errorf("snap did not append the snapshot: %q", text)+ }+ })+ }+}++// Without snap there must be exactly one request, so the snapshot is opt-in rather+// than a second round-trip every client pays for.+func TestHistoryToolsMakeNoSnapshotRequestWithoutSnap(t *testing.T) {+ srv, seen := historyRecorder(t)++ callTool(t, "pinchtab_back", map[string]any{}, srv)++ if len(*seen) != 1 {+ t.Fatalf("requests = %d, want only the navigation: %+v", len(*seen), *seen)+ }+}++// The three tools must be registered, or tools/list does not advertise them and no+// client can call them however well the handler works.+func TestHistoryToolsAreRegistered(t *testing.T) {+ declared := map[string]bool{}+ for _, tool := range allTools() {+ declared[tool.Name] = true+ }+ handlers := rawHandlerMap(NewClient("http://example.invalid", ""))++ for _, name := range []string{"pinchtab_back", "pinchtab_forward", "pinchtab_reload"} {+ if !declared[name] {+ t.Errorf("%s is not in allTools(), so tools/list does not advertise it", name)+ }+ if _, ok := handlers[name]; !ok {+ t.Errorf("%s has no handler, so NewServer panics on it", name)+ }+ }+}diff --git a/internal/mcp/routing_test.go b/internal/mcp/routing_test.goindex 47b08451..5e893e99 100644--- a/internal/mcp/routing_test.go+++ b/internal/mcp/routing_test.go@@ -15,6 +15,9 @@ import (// which is what stops the next tool from picking the body form.var browserToolArgs = map[string]map[string]any{"pinchtab_navigate": {"url": "https://example.com"},+ "pinchtab_back": {},+ "pinchtab_forward": {},+ "pinchtab_reload": {},"pinchtab_snapshot": {},"pinchtab_frame": {"target": "#payment"},"pinchtab_screenshot": {},diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.goindex ea84dad8..0d659823 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) != 43 {- t.Errorf("expected 43 tools, got %d", len(tools))+ if len(tools) != 46 {+ t.Errorf("expected 46 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/tools.go b/internal/mcp/tools.goindex 48e261f9..12dc55a2 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -13,6 +13,27 @@ func allTools() []mcp.Tool {mcp.WithString("browser",mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),),+ mcp.NewTool("pinchtab_back",+ mcp.WithDescription("Go back one entry in the tab's session history. Returns the tab ID and the URL the tab landed on, so a redirect or bfcache restore is visible without a snapshot."),+ mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),+ mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after the navigation (saves a round-trip)")),+ mcp.WithString("browser",+ mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),+ ),+ mcp.NewTool("pinchtab_forward",+ mcp.WithDescription("Go forward one entry in the tab's session history. Returns the tab ID and the URL the tab landed on."),+ mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),+ mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after the navigation (saves a round-trip)")),+ mcp.WithString("browser",+ mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),+ ),+ mcp.NewTool("pinchtab_reload",+ mcp.WithDescription("Reload the current page. Returns the tab ID and the URL the tab landed on."),+ mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),+ mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after the navigation (saves a round-trip)")),+ mcp.WithString("browser",+ mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),+ ),mcp.NewTool("pinchtab_snapshot",mcp.WithDescription("Get an accessibility tree snapshot of the current page. Use this sparingly: prefer pinchtab_find + action selectors for faster loops."),mcp.WithString("tabId", mcp.Description("Target tab ID")),