High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: MCP tools carry the snapshot vocabulary token so a superseded ref is refused not mis-resolved (PIN-084)
Luigi Agosti3ced64b9bafa
diff --git a/internal/mcp/action_payload_contract_test.go b/internal/mcp/action_payload_contract_test.goindex 51d92a4e..809501eb 100644--- a/internal/mcp/action_payload_contract_test.go+++ b/internal/mcp/action_payload_contract_test.go@@ -26,6 +26,7 @@ var consumedElsewhere = map[string]string{"waitNav": "the handler waits for navigation around the action","dialogAction": "the handler arms the dialog watcher around the action","dialogText": "the handler arms the dialog watcher around the action",+ "vocab": "the handler's vocabulary-supersession gate reads it before dispatch; no action reads it",}// A payload key that is a real ActionRequest field but not one the target action READS isdiff --git a/internal/mcp/client.go b/internal/mcp/client.goindex c29823af..7597cdfd 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -10,16 +10,46 @@ import ("net/http""net/url""strings"+ "sync""time""github.com/pinchtab/pinchtab/internal/activity")+const vocabHeader = "X-PinchTab-Vocab"++// vocabStore holds the last snapshot vocabulary token per tab so an interaction+// echoes it back and a ref minted under a superseded snapshot is refused rather+// than resolved against whatever the tab was last renumbered to. Shared by+// pointer so a withTimeout clone reads and writes the same tokens.+type vocabStore struct {+ mu sync.Mutex+ m map[string]string+}++func newVocabStore() *vocabStore { return &vocabStore{m: map[string]string{}} }++func (v *vocabStore) set(tabKey, token string) {+ if token == "" {+ return+ }+ v.mu.Lock()+ defer v.mu.Unlock()+ v.m[tabKey] = token+}++func (v *vocabStore) get(tabKey string) string {+ v.mu.Lock()+ defer v.mu.Unlock()+ return v.m[tabKey]+}+// Client is an HTTP client for PinchTab's REST API.type Client struct {BaseURL stringToken stringHTTPClient *http.Client+ vocab *vocabStore}// NewClient creates a Client for the given PinchTab base URL.@@ -30,6 +60,7 @@ func NewClient(baseURL, token string) *Client {HTTPClient: &http.Client{Timeout: 120 * time.Second,},+ vocab: newVocabStore(),}}@@ -57,6 +88,11 @@ func (c *Client) dashboardProfilesURL() string {}func (c *Client) do(req *http.Request) ([]byte, int, error) {+ body, code, _, err := c.doWithHeaders(req)+ return body, code, err+}++func (c *Client) doWithHeaders(req *http.Request) ([]byte, int, http.Header, error) {if c.Token != "" {req.Header.Set("Authorization", "Bearer "+c.Token)}@@ -64,17 +100,40 @@ func (c *Client) do(req *http.Request) ([]byte, int, error) {req.Header.Set(activity.HeaderPTSource, "mcp")resp, err := c.HTTPClient.Do(req)if err != nil {- return nil, 0, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)+ return nil, 0, nil, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) // 10 MB limitif err != nil {- return nil, resp.StatusCode, fmt.Errorf("read response: %w", err)+ return nil, resp.StatusCode, resp.Header, fmt.Errorf("read response: %w", err)}- return body, resp.StatusCode, nil+ return body, resp.StatusCode, resp.Header, nil}+// GetCapturingVocab performs a GET and records the response's vocabulary token+// under tabKey, so a later interaction on the same tab echoes it. tabKey is the+// tab as the caller addresses it (the tabId argument, possibly empty), which is+// stable across a session's snapshot and action calls.+func (c *Client) GetCapturingVocab(ctx context.Context, path string, query url.Values, tabKey string) ([]byte, int, error) {+ u := c.url(path)+ if len(query) > 0 {+ u += "?" + query.Encode()+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)+ if err != nil {+ return nil, 0, err+ }+ body, code, hdr, err := c.doWithHeaders(req)+ if err == nil && code < 400 {+ c.vocab.set(tabKey, hdr.Get(vocabHeader))+ }+ return body, code, err+}++// VocabToken returns the last vocabulary token captured for tabKey, or "".+func (c *Client) VocabToken(tabKey string) string { return c.vocab.get(tabKey) }+// Get performs a GET request and returns the response body.func (c *Client) Get(ctx context.Context, path string, query url.Values) ([]byte, int, error) {u := c.url(path)diff --git a/internal/mcp/handlers_interaction.go b/internal/mcp/handlers_interaction.goindex 7dc4454c..3ccbcedb 100644--- a/internal/mcp/handlers_interaction.go+++ b/internal/mcp/handlers_interaction.go@@ -285,6 +285,10 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequpayload["text"] = value}+ if tok := c.VocabToken(optString(r, "tabId")); tok != "" {+ payload["vocab"] = tok+ }+body, code, err := c.Post(ctx, routedPathWithBody(r, "/action", payload), payload)if err != nil {return mcp.NewToolResultError(err.Error()), nil@@ -302,7 +306,7 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequif tabID := optString(r, "tabId"); tabID != "" {q.Set("tabId", tabID)}- snapBody, _, snapErr := c.Get(ctx, "/snapshot", q)+ snapBody, _, snapErr := c.GetCapturingVocab(ctx, "/snapshot", q, optString(r, "tabId"))if snapErr == nil {return mcp.NewToolResultText(string(body) + "\n" + string(snapBody)), nil}diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex 2457b5c7..2f3876e3 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -134,7 +134,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.Get(ctx, "/snapshot", routedQuery(r, q))+ body, code, err := c.GetCapturingVocab(ctx, "/snapshot", routedQuery(r, q), optString(r, "tabId"))if err != nil {return mcp.NewToolResultError(err.Error()), nil}diff --git a/internal/mcp/vocab_echo_test.go b/internal/mcp/vocab_echo_test.gonew file mode 100644index 00000000..c2d6381e--- /dev/null+++ b/internal/mcp/vocab_echo_test.go@@ -0,0 +1,111 @@+package mcp++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/mark3labs/mcp-go/mcp"+)++// vocabMockServer returns a server that stamps a vocabulary token on every+// /snapshot response and echoes each /action body, so a test can read back what+// the interaction sent.+func vocabMockServer(token string) *httptest.Server {+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/snapshot" {+ w.Header().Set(vocabHeader, token)+ }+ resp := map[string]any{"path": r.URL.Path}+ if r.Method == http.MethodPost {+ body, _ := io.ReadAll(r.Body)+ var parsed map[string]any+ if json.Unmarshal(body, &parsed) == nil {+ resp["body"] = parsed+ }+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(200)+ _ = json.NewEncoder(w).Encode(resp)+ }))+}++func callSharedTool(t *testing.T, c *Client, name string, args map[string]any) *mcp.CallToolResult {+ t.Helper()+ h, ok := handlerMap(c)[name]+ if !ok {+ t.Fatalf("no handler for %q", name)+ }+ req := mcp.CallToolRequest{}+ req.Params.Name = name+ req.Params.Arguments = args+ result, err := h(context.Background(), req)+ if err != nil {+ t.Fatalf("handler %q error: %v", name, err)+ }+ return result+}++func actionVocabSent(t *testing.T, r *mcp.CallToolResult) (string, bool) {+ t.Helper()+ body, _ := resultJSON(t, r)["body"].(map[string]any)+ v, ok := body["vocab"]+ if !ok {+ return "", false+ }+ s, _ := v.(string)+ return s, true+}++// The point of the whole card at the MCP surface: a snapshot's vocabulary token is+// remembered and echoed on the next interaction, so the server can refuse a ref that+// a later snapshot has renumbered instead of clicking the wrong node. One Client is+// reused across both calls because the stash lives on it, exactly as the long-lived+// MCP server holds it across tool calls.+func TestSnapshotVocabularyTokenIsEchoedOnTheNextAction(t *testing.T) {+ srv := vocabMockServer("vocab-abc")+ defer srv.Close()+ c := NewClient(srv.URL, "")++ callSharedTool(t, c, "pinchtab_snapshot", map[string]any{"tabId": "t1"})+ clickResult := callSharedTool(t, c, "pinchtab_click", map[string]any{"ref": "e5", "tabId": "t1"})++ got, ok := actionVocabSent(t, clickResult)+ if !ok {+ t.Fatal("the click carried no vocab token, so a superseded ref would still be resolved positionally")+ }+ if got != "vocab-abc" {+ t.Errorf("click echoed vocab %q, want the token the snapshot returned", got)+ }+}++// The absence half: without a prior snapshot there is nothing to echo, so the token+// stays optional and the action is unchanged — a guard that always attached something+// would break the permissive contract raw callers rely on.+func TestAnActionWithoutAPriorSnapshotSendsNoToken(t *testing.T) {+ srv := vocabMockServer("vocab-abc")+ defer srv.Close()+ c := NewClient(srv.URL, "")++ clickResult := callSharedTool(t, c, "pinchtab_click", map[string]any{"ref": "e5", "tabId": "t1"})+ if got, ok := actionVocabSent(t, clickResult); ok {+ t.Errorf("an action with no prior snapshot echoed a token %q", got)+ }+}++// The token is remembered per tab, so a snapshot of one tab does not attach its+// vocabulary to an action on another — that would refuse the second tab's valid refs.+func TestTheEchoedTokenIsScopedToItsTab(t *testing.T) {+ srv := vocabMockServer("vocab-abc")+ defer srv.Close()+ c := NewClient(srv.URL, "")++ callSharedTool(t, c, "pinchtab_snapshot", map[string]any{"tabId": "t1"})+ clickResult := callSharedTool(t, c, "pinchtab_click", map[string]any{"ref": "e5", "tabId": "t2"})+ if got, ok := actionVocabSent(t, clickResult); ok {+ t.Errorf("an action on t2 echoed t1's vocabulary token %q", got)+ }+}