Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix(mcp): tool calls silently drop undeclared arguments (PIN-426)

Luigi Agosti3a28fac01322
diff --git a/docs/architecture/mcp.md b/docs/architecture/mcp.md
index 5c01c910..cca788df 100644
--- a/docs/architecture/mcp.md
+++ b/docs/architecture/mcp.md
@@ -118,7 +118,7 @@ URL validation lives in `handleNavigate` (`handlers_navigation.go`), which calls
- **`pinchtab_cookies`** and **`pinchtab_cookies_set`** call `/cookies`, which requires `security.allowCookies: true`. Cookie values can expose session credentials, and setting one grants a session, so cookie operations are disabled by default.
- **URL validation** — `pinchtab_navigate` rejects non-HTTP/HTTPS URLs to prevent SSRF via `file://`, `javascript:`, or custom schemes.
- **Token forwarding** — the MCP client forwards the configured bearer token to PinchTab, so access control at the PinchTab layer applies to all tool calls.
-- **Wait caps** — `pinchtab_wait` enforces a 30-second maximum on both the fixed `for=ms` sleep and the `timeout` of every browser-backed condition, to prevent agent runaway.
+- **Wait caps** — `pinchtab_wait` enforces a 30-second maximum on both the fixed `for=ms` sleep and the `timeoutMs` of every browser-backed condition, to prevent agent runaway.
## Related Pages
diff --git a/docs/mcp.md b/docs/mcp.md
index d1e06c42..bde82a30 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -168,7 +168,7 @@ PinchTab currently exposes 43 tools:
### 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`.
+- `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`. Its `timeoutSeconds` is a crawl budget and the one seconds-unit argument; every wait elsewhere is `timeoutMs`.
### Tab Management
@@ -187,7 +187,7 @@ PinchTab currently exposes 43 tools:
### Wait Utilities
-- `pinchtab_wait` — `for` is `ms`, `selector`, `text`, `url`, `load` or `function`, and `value` carries the condition
+- `pinchtab_wait` — `for` is `ms`, `selector`, `text`, `url`, `load` or `function`, and `value` carries the condition; `timeoutMs` bounds a browser-backed wait (`timeout` is its deprecated alias)
### Network
@@ -210,7 +210,11 @@ PinchTab currently exposes 43 tools:
## Selector Model
-For selector-based interaction tools, prefer `selector`. `ref` is still accepted as a deprecated fallback on the element-action tools.
+For selector-based interaction tools, prefer `selector`. `ref`, `element` and `target` are still accepted as deprecated aliases on the element-action tools.
+
+## Argument Names
+
+Every tool refuses an argument its schema does not declare. The call returns an error naming the unknown key, the nearest declared name when one is close (`filter: "interactive"` on `pinchtab_snapshot` points at `interactive: true`), and the tool's declared arguments; nothing runs. Deprecated spellings stay declared, with a description naming the canonical one: `ref`/`element`/`target` for `selector`, `timeout` for `timeoutMs` on `pinchtab_wait`, `onDialog`/`promptText` for `dialogAction`/`dialogText` on `pinchtab_click`, `value` for `text` on `pinchtab_type`, `option` for `value` on `pinchtab_select`, and `text` for `value` on `pinchtab_fill`.
Common selector forms:
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index de46bdad..6a90a5d6 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -2,7 +2,9 @@
PinchTab currently exposes 36 MCP tools. All tool names are prefixed with `pinchtab_` and are served over stdio JSON-RPC.
-For selector-based interaction tools, prefer `selector`. `ref` and `query` are still accepted as deprecated/alias fallbacks on the element-action tools (`query` is shorthand for `find:<text>`).
+For selector-based interaction tools, prefer `selector`. `ref`, `element` and `target` are still accepted as deprecated aliases, and `query` as a fallback, on the element-action tools (`query` is shorthand for `find:<text>`).
+
+Every tool refuses an argument its schema does not declare, naming the unknown key, the nearest declared name when one is close, and the declared arguments; nothing runs. Deprecated spellings stay declared with a description naming the canonical one.
If you allow MCP browsing on non-local or non-trusted domains, treat `pinchtab_snapshot` and `pinchtab_get_text` output as untrusted page data. Those tools can surface hostile prompt text from visited pages; operators should keep IDPI/domain restrictions narrow unless wider access is intentional.
@@ -34,7 +36,7 @@ Structured semantic locators are matched by the semantic engine; CSS, XPath, ref
## Interaction
-All element-action tools accept the unified `selector` and the legacy aliases `ref` (deprecated) and `query` (semantic shorthand). Every one of them also accepts `nodeId` (a backend node ID from a snapshot) as an alternative target. Coordinates (`x`/`y`) are accepted only by `pinchtab_click`, `pinchtab_hover` and `pinchtab_scroll` — the other kinds have no coordinate behaviour.
+All element-action tools accept the unified `selector`, its deprecated aliases `ref`, `element` and `target`, and `query` (semantic shorthand). Deprecated value aliases: `onDialog`/`promptText` for `dialogAction`/`dialogText` on click, `value` for `text` on type, `option` for `value` on select, `text` for `value` on fill. Every one of them also accepts `nodeId` (a backend node ID from a snapshot) as an alternative target. Coordinates (`x`/`y`) are accepted only by `pinchtab_click`, `pinchtab_hover` and `pinchtab_scroll` — the other kinds have no coordinate behaviour.
| Tool | Key Parameters | Notes |
| --- | --- | --- |
@@ -65,7 +67,7 @@ All element-action tools accept the unified `selector` and the legacy aliases `r
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_scrape` | `url` required, `preview`, `only`, `maxPages`, `maxPerPattern`, `include`, `exclude`, `concurrency`, `enrichAll`, `noBrowser`, `timeoutSeconds`, `browser` | Crawl a whole site to a page tree of markdown via `/scrape`. HTTP-first extraction; only thin/blocked/failed pages are browser-rendered. `preview=true` returns a cheap outline (sizes + snippets, no bodies, no browser); `only` (comma-separated URLs) expands chosen pages at full fidelity. `include`/`exclude` are comma-separated regexes. Full reports can be large — prefer preview then expand. Runs with an extended timeout (multi-page crawls take minutes) |
+| `pinchtab_scrape` | `url` required, `preview`, `only`, `maxPages`, `maxPerPattern`, `include`, `exclude`, `concurrency`, `enrichAll`, `noBrowser`, `timeoutSeconds`, `browser` | Crawl a whole site to a page tree of markdown via `/scrape`. HTTP-first extraction; only thin/blocked/failed pages are browser-rendered. `preview=true` returns a cheap outline (sizes + snippets, no bodies, no browser); `only` (comma-separated URLs) expands chosen pages at full fidelity. `include`/`exclude` are comma-separated regexes. Full reports can be large — prefer preview then expand. Runs with an extended timeout (multi-page crawls take minutes). `timeoutSeconds` is a crawl budget and the one seconds-unit argument; waits elsewhere use `timeoutMs` |
## Tab Management
@@ -90,7 +92,7 @@ All element-action tools accept the unified `selector` and the legacy aliases `r
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_wait` | `for` required, `value` required, `timeout`, `state`, `tabId` | One wait tool: `for` names the condition and `value` carries it. `for=ms` is a fixed-duration wait capped at 30000 ms; `selector` waits for an element (`state` is `visible` (default) or `hidden`); `text` waits for body text; `url` is a URL glob match; `load` is `ready-state` (`readyState=complete`), `content-loaded` (`readyState` in `{interactive, complete}`), or `network-idle` (0 in-flight requests for 500 ms); `function` waits for a JS expression to become truthy |
+| `pinchtab_wait` | `for` required, `value` required, `timeoutMs`, `state`, `tabId` | One wait tool: `for` names the condition and `value` carries it. `timeoutMs` bounds a browser-backed condition (default 10000, max 30000); `timeout` is its deprecated alias. `for=ms` is a fixed-duration wait capped at 30000 ms; `selector` waits for an element (`state` is `visible` (default) or `hidden`); `text` waits for body text; `url` is a URL glob match; `load` is `ready-state` (`readyState=complete`), `content-loaded` (`readyState` in `{interactive, complete}`), or `network-idle` (0 in-flight requests for 500 ms); `function` waits for a JS expression to become truthy |
## Network
diff --git a/internal/mcp/argcheck.go b/internal/mcp/argcheck.go
index a4d2fc5a..e10d537b 100644
--- a/internal/mcp/argcheck.go
+++ b/internal/mcp/argcheck.go
@@ -12,10 +12,18 @@ import (
"github.com/mark3labs/mcp-go/mcp"
)
+var schemaPropertiesOnce = sync.OnceValue(func() map[string]map[string]string {
+ properties := make(map[string]map[string]string)
+ for _, tool := range allTools() {
+ properties[tool.Name] = propertiesOf(tool)
+ }
+ return properties
+})
+
var schemaArgTypesOnce = sync.OnceValue(func() map[string]map[string]string {
types := make(map[string]map[string]string)
- for _, tool := range allTools() {
- types[tool.Name] = typedArgsOf(tool)
+ for name, properties := range schemaPropertiesOnce() {
+ types[name] = typedOnly(properties)
}
return types
})
@@ -25,6 +33,10 @@ var schemaArgTypesOnce = sync.OnceValue(func() map[string]map[string]string {
// hand-written list of numeric arguments would drift the first time a tool gains
// one.
func typedArgsOf(tool mcp.Tool) map[string]string {
+ return typedOnly(propertiesOf(tool))
+}
+
+func propertiesOf(tool mcp.Tool) map[string]string {
raw, err := json.Marshal(tool.InputSchema)
if err != nil {
return nil
@@ -38,16 +50,123 @@ func typedArgsOf(tool mcp.Tool) map[string]string {
return nil
}
- types := make(map[string]string, len(schema.Properties))
+ properties := make(map[string]string, len(schema.Properties))
for name, property := range schema.Properties {
- switch property.Type {
+ properties[name] = property.Type
+ }
+ return properties
+}
+
+func typedOnly(properties map[string]string) map[string]string {
+ types := make(map[string]string, len(properties))
+ for name, kind := range properties {
+ switch kind {
case "number", "integer", "boolean":
- types[name] = property.Type
+ types[name] = kind
}
}
return types
}
+func validateDeclaredArgs(toolName string, args map[string]any) error {
+ declared, known := schemaPropertiesOnce()[toolName]
+ if !known || len(args) == 0 {
+ return nil
+ }
+
+ unknown := make([]string, 0, len(args))
+ for name, value := range args {
+ if _, ok := declared[name]; ok {
+ continue
+ }
+ unknown = append(unknown, "unknown argument "+strconv.Quote(name)+nearestArgHint(declared, name, value))
+ }
+ if len(unknown) == 0 {
+ return nil
+ }
+
+ sort.Strings(unknown)
+ return fmt.Errorf("%s: %s; declared arguments: %s", toolName, strings.Join(unknown, "; "), declaredArgList(declared))
+}
+
+func declaredArgList(declared map[string]string) string {
+ if len(declared) == 0 {
+ return "none"
+ }
+ names := make([]string, 0, len(declared))
+ for name := range declared {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ return strings.Join(names, ", ")
+}
+
+func nearestArgHint(declared map[string]string, name string, value any) string {
+ if raw, ok := value.(string); ok && declared[raw] == "boolean" {
+ return fmt.Sprintf(" (did you mean %q: true?)", raw)
+ }
+ if match := closestArgName(declared, name); match != "" {
+ return fmt.Sprintf(" (did you mean %q?)", match)
+ }
+ return ""
+}
+
+func closestArgName(declared map[string]string, name string) string {
+ best, bestDistance := "", -1
+ for candidate := range declared {
+ distance, close := argNameDistance(name, candidate)
+ if !close {
+ continue
+ }
+ if bestDistance < 0 || distance < bestDistance || (distance == bestDistance && candidate < best) {
+ best, bestDistance = candidate, distance
+ }
+ }
+ return best
+}
+
+const minRelatedArgNameLength = 3
+
+func argNameDistance(name, candidate string) (int, bool) {
+ a, b := strings.ToLower(name), strings.ToLower(candidate)
+ distance := editDistance(a, b)
+ stem := sharedPrefixLength(a, b)
+ related := stem >= minRelatedArgNameLength && 2*stem >= min(len(a), len(b))
+ return distance, related || distance <= typoTolerance(a)
+}
+
+func sharedPrefixLength(a, b string) int {
+ n := 0
+ for n < len(a) && n < len(b) && a[n] == b[n] {
+ n++
+ }
+ return n
+}
+
+func typoTolerance(name string) int {
+ return min(2, len(name)/3)
+}
+
+func editDistance(a, b string) int {
+ previous := make([]int, len(b)+1)
+ for j := range previous {
+ previous[j] = j
+ }
+ for i := 1; i <= len(a); i++ {
+ current := make([]int, len(b)+1)
+ current[0] = i
+ for j := 1; j <= len(b); j++ {
+ substitution := previous[j-1]
+ if a[i-1] != b[j-1] {
+ substitution++
+ }
+ current[j] = min(previous[j]+1, current[j-1]+1, substitution)
+ }
+ previous = current
+ }
+ return previous[len(b)]
+}
+
// validateTypedArgs rejects an argument the caller did pass in a shape the
// accessors cannot read. Dropping it instead is what let a malformed deltaY
// degrade into a scroll with no magnitude — or, with direction set, into a
@@ -121,6 +240,9 @@ func describeArgValue(value any) string {
// means only "absent" — which is what all of their call sites already assume.
func withTypedArgChecks(name string, h func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error)) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ if err := validateDeclaredArgs(name, r.GetArguments()); err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
if err := validateTypedArgs(name, r.GetArguments()); err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
diff --git a/internal/mcp/argcheck_test.go b/internal/mcp/argcheck_test.go
index 0d1c992a..33fa1be4 100644
--- a/internal/mcp/argcheck_test.go
+++ b/internal/mcp/argcheck_test.go
@@ -3,6 +3,9 @@ package mcp
import (
"encoding/json"
"fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
"io"
"net/http"
"net/http/httptest"
@@ -10,8 +13,11 @@ import (
"reflect"
"regexp"
"sort"
+ "strconv"
"strings"
"testing"
+
+ "github.com/mark3labs/mcp-go/mcp"
)
// upstreamRecorder records every request that reaches PinchTab, so a test can
@@ -220,71 +226,6 @@ func TestEveryHandlerHasASchemaAndEverySchemaAHandler(t *testing.T) {
}
}
-// Every argument the package reads with a TYPED accessor must be declared as
-// number/integer/boolean in some tool's schema. Two things follow from a missing
-// declaration: a model cannot discover the argument, and validateTypedArgs cannot
-// see it either — it derives from the schemas, so an undeclared argument keeps the
-// silent-coercion-drop this package otherwise rejects.
-//
-// A UNION check, not a per-tool one: the declared set is built across ALL tools,
-// so one declaration anywhere licenses the argument for every handler that reads
-// it. Over a shared handler that is structurally blind to the case this package
-// had twice — nodeId and x/y were each read for all nine action tools while only
-// three declared them, and both passed here. TestNoActionToolIsSentATypedArgumentItDoesNotDeclare covers
-// that per-tool half behaviourally, for the action family. The two are not one
-// check: this one spans every handler in the package and catches a name declared
-// nowhere at all; that one is narrower in scope and stricter within it.
-//
-// optString is deliberately NOT scanned. A string argument read without a
-// declaration is undiscoverable but not a correctness hazard: there is no
-// coercion, so nothing is silently dropped. Widening this census to optString
-// would produce false positives on the many string aliases the handlers accept.
-func TestEveryTypedAccessorArgumentIsDeclaredInASchema(t *testing.T) {
- declared := map[string]string{}
- for _, tool := range allTools() {
- for name, kind := range typedArgsOf(tool) {
- declared[name] = kind
- }
- }
- if len(declared) == 0 {
- t.Fatal("no typed arguments found in any schema — this census is checking nothing")
- }
-
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatal(err)
- }
- accessor := regexp.MustCompile(`opt(?:Int|Float|Bool)\(r, "([^"]+)"\)`)
-
- scanned, found := 0, 0
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- raw, err := os.ReadFile(name)
- if err != nil {
- t.Fatal(err)
- }
- scanned++
- for _, match := range accessor.FindAllStringSubmatch(string(raw), -1) {
- found++
- arg := match[1]
- if _, ok := declared[arg]; !ok {
- t.Errorf("%s reads %q with a typed accessor but no tool schema declares it as number/integer/boolean — "+
- "a model cannot discover it and validateTypedArgs cannot validate it, so a malformed value is silently dropped", name, arg)
- }
- }
- }
- if scanned == 0 {
- t.Fatal("no Go source scanned — this census is checking nothing")
- }
- if found == 0 {
- t.Fatal("no typed accessor call found — the pattern no longer matches how arguments are read")
- }
- t.Logf("checked %d typed-accessor call sites against %d declared typed arguments", found, len(declared))
-}
-
// Declaring humanize is only half the fix: it was previously read solely to raise
// the mutual-exclusion error and never forwarded, so humanized input was
// unreachable from MCP even for a caller who guessed the name.
@@ -511,14 +452,11 @@ func describeDifference(baseline, probed callOutcome) string {
// somewhere else does not help the tool being called. handleAction reads its
// arguments before switching on kind, so this is where that goes wrong.
//
-// Behavioural rather than structural: reachability is observed as a BASELINE DIFF —
-// the same call with and without the probe — so the sentinel, a value derived from
-// it, a dropped field and an extra upstream request all count uniformly, and no
-// derivative has to be listed by hand. That needs no tool-to-handler-source mapping
-// and cannot go stale as the handler moves code around.
-//
-// Its blind spot is an undeclared read with no observable effect at all, which by
-// construction changes nothing a caller can see.
+// Behavioural rather than structural: the positive control observes reachability as a
+// BASELINE DIFF on a tool that declares the probe, and the sweep then requires every
+// tool that does NOT declare it to refuse the probe by name before upstream is called.
+// The structural half — which keys each handler reads — is
+// TestEveryArgumentAHandlerReadsIsDeclaredOnItsTool.
func TestNoActionToolIsSentATypedArgumentItDoesNotDeclare(t *testing.T) {
probes := append([]argumentProbe(nil), combinationProbes...)
grouped := map[string]bool{}
@@ -548,9 +486,11 @@ func TestNoActionToolIsSentATypedArgumentItDoesNotDeclare(t *testing.T) {
const sentinel = 424242.0
probeArgs := func(tool string, probe argumentProbe, withProbe bool) map[string]any {
- extra := map[string]any{"selector": "#a"}
+ extra := map[string]any{}
for name, value := range probe.companions {
- extra[name] = value
+ if _, declared := schemaPropertiesOnce()[tool][name]; declared {
+ extra[name] = value
+ }
}
if withProbe {
for _, name := range probe.args {
@@ -561,7 +501,7 @@ func TestNoActionToolIsSentATypedArgumentItDoesNotDeclare(t *testing.T) {
extra[name] = sentinel
}
}
- return actionArgs(tool, extra)
+ return targetedActionArgs(tool, extra)
}
// A diff oracle is only as trustworthy as the calls it compares. If anything in
@@ -628,11 +568,20 @@ func TestNoActionToolIsSentATypedArgumentItDoesNotDeclare(t *testing.T) {
}
checked++
- baseline := observeToolCall(t, tc.tool, probeArgs(tc.tool, probe, false))
- probed := observeToolCall(t, tc.tool, probeArgs(tc.tool, probe, true))
- if diff := describeDifference(baseline, probed); diff != "" {
- t.Errorf("%s: %s is reachable but the tool does not declare it — %s, so it is undiscoverable in tools/list and validateTypedArgs cannot type-check it",
- tc.tool, probe.label(), diff)
+ srv, paths := upstreamRecorder(t)
+ result := callTool(t, tc.tool, probeArgs(tc.tool, probe, true), srv)
+ message := resultText(t, result)
+ if !result.IsError {
+ t.Errorf("%s: %s is undeclared but was accepted (%s); an undeclared argument must be refused, never dropped or acted on", tc.tool, probe.label(), message)
+ continue
+ }
+ for _, name := range probe.args {
+ if !strings.Contains(message, "unknown argument "+strconv.Quote(name)) {
+ t.Errorf("%s: refusal %q does not name the undeclared %q", tc.tool, message, name)
+ }
+ }
+ if len(*paths) != 0 {
+ t.Errorf("%s: a refused %s still reached upstream: %v", tc.tool, probe.label(), *paths)
}
}
}
@@ -679,3 +628,690 @@ func TestSelectorSchemasThatOfferWrappersStateWhatAnIndexMeans(t *testing.T) {
t.Fatal("no schema offers first/last/nth, so this guard checked nothing")
}
}
+
+func TestEveryToolRefusesAnUndeclaredArgumentBeforeCallingUpstream(t *testing.T) {
+ const undeclared = "notAnArgumentOfAnyTool"
+ tools := allTools()
+ if len(tools) == 0 {
+ t.Fatal("allTools() is empty, so this table checks nothing")
+ }
+ for _, tool := range tools {
+ t.Run(tool.Name, func(t *testing.T) {
+ srv, paths := upstreamRecorder(t)
+ result := callTool(t, tool.Name, map[string]any{undeclared: "x"}, srv)
+ if !result.IsError {
+ t.Fatalf("an undeclared argument was accepted: %s", resultText(t, result))
+ }
+ message := resultText(t, result)
+ if !strings.Contains(message, `unknown argument "`+undeclared+`"`) {
+ t.Errorf("refusal %q does not name the undeclared key", message)
+ }
+ if !strings.Contains(message, "declared arguments: "+declaredArgList(schemaPropertiesOnce()[tool.Name])) {
+ t.Errorf("refusal %q does not list the tool's declared arguments", message)
+ }
+ if len(*paths) != 0 {
+ t.Errorf("a refused call still reached upstream: %v", *paths)
+ }
+ })
+ }
+}
+
+func TestUndeclaredArgumentsNameTheNearestDeclaredOne(t *testing.T) {
+ for _, tc := range []struct {
+ tool string
+ args map[string]any
+ wantHint string
+ }{
+ {tool: "pinchtab_snapshot", args: map[string]any{"filter": "interactive"}, wantHint: `unknown argument "filter" (did you mean "interactive": true?)`},
+ {tool: "pinchtab_wait", args: map[string]any{"for": "selector", "value": "#nope", "timeoutSeconds": float64(2)}, wantHint: `unknown argument "timeoutSeconds" (did you mean "timeoutMs"?)`},
+ {tool: "pinchtab_scrape", args: map[string]any{"url": "https://example.com", "timeout": float64(5)}, wantHint: `unknown argument "timeout" (did you mean "timeoutSeconds"?)`},
+ {tool: "pinchtab_click", args: map[string]any{"selecter": "#a"}, wantHint: `unknown argument "selecter" (did you mean "selector"?)`},
+ {tool: "pinchtab_navigate", args: map[string]any{"url": "https://example.com", "tabid": "t1"}, wantHint: `unknown argument "tabid" (did you mean "tabId"?)`},
+ {tool: "pinchtab_eval", args: map[string]any{"expression": "1", "zzz": true}, wantHint: `unknown argument "zzz";`},
+ } {
+ t.Run(tc.tool, func(t *testing.T) {
+ srv, paths := upstreamRecorder(t)
+ result := callTool(t, tc.tool, tc.args, srv)
+ if !result.IsError {
+ t.Fatalf("%v was accepted: %s", tc.args, resultText(t, result))
+ }
+ if message := resultText(t, result); !strings.Contains(message, tc.wantHint) {
+ t.Errorf("refusal %q, want it to contain %q", message, tc.wantHint)
+ }
+ if len(*paths) != 0 {
+ t.Errorf("a refused call still reached upstream: %v", *paths)
+ }
+ })
+ }
+}
+
+func TestWaitSendsTimeoutMsAndItsDeprecatedAliasAsTheWaitBudget(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ args map[string]any
+ want float64
+ }{
+ {name: "timeoutMs", args: map[string]any{"timeoutMs": float64(1500)}, want: 1500},
+ {name: "deprecated timeout", args: map[string]any{"timeout": float64(1200)}, want: 1200},
+ {name: "timeoutMs wins over timeout", args: map[string]any{"timeoutMs": float64(1500), "timeout": float64(9000)}, want: 1500},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv, _ := upstreamRecorder(t)
+ args := map[string]any{"for": "selector", "value": "#nope"}
+ for name, value := range tc.args {
+ args[name] = value
+ }
+ result := callTool(t, "pinchtab_wait", args, srv)
+ if result.IsError {
+ t.Fatalf("%v was refused: %s", tc.args, resultText(t, result))
+ }
+ body, _ := resultJSON(t, result)["body"].(map[string]any)
+ if got := body["timeout"]; got != tc.want {
+ t.Errorf("posted timeout = %v, want %v (body %v)", got, tc.want, body)
+ }
+ })
+ }
+}
+
+func TestWaitDeclaresTimeoutAsADeprecatedAliasOfTimeoutMs(t *testing.T) {
+ var wait mcp.Tool
+ for _, tool := range allTools() {
+ if tool.Name == "pinchtab_wait" {
+ wait = tool
+ }
+ }
+ properties := wait.InputSchema.Properties
+ canonical, _ := properties["timeoutMs"].(map[string]any)
+ if canonical["type"] != "number" {
+ t.Fatalf("pinchtab_wait timeoutMs = %v, want a declared number", properties["timeoutMs"])
+ }
+ alias, _ := properties["timeout"].(map[string]any)
+ description, _ := alias["description"].(string)
+ if !strings.Contains(description, "deprecated") || !strings.Contains(description, "timeoutMs") {
+ t.Errorf("pinchtab_wait timeout description %q must mark it deprecated and point at timeoutMs", description)
+ }
+}
+
+func TestEverySelectorAliasStillTargetsEveryActionTool(t *testing.T) {
+ for _, tc := range actionToolTargets {
+ if _, declared := schemaPropertiesOnce()[tc.tool]["selector"]; !declared {
+ continue
+ }
+ for _, key := range selectorArgKeys {
+ t.Run(tc.tool+"/"+key, func(t *testing.T) {
+ srv, _ := upstreamRecorder(t)
+ result := callTool(t, tc.tool, actionArgs(tc.tool, map[string]any{key: "e5"}), srv)
+ if result.IsError {
+ t.Fatalf("%s {%q: \"e5\"} was refused: %s", tc.tool, key, resultText(t, result))
+ }
+ body, _ := resultJSON(t, result)["body"].(map[string]any)
+ if got := body["selector"]; got != "e5" {
+ t.Errorf("posted selector = %v, want e5 (body %v)", got, body)
+ }
+ })
+ }
+ }
+}
+
+var dynamicArgumentReads = map[string][]string{
+ "handleKeyboard": {"key", "text"},
+}
+
+type argumentRead struct {
+ key string
+ typed bool
+ fn string
+}
+
+type argumentReader struct {
+ keyIndex int
+ variadic bool
+ typed bool
+}
+
+type paramBinding struct {
+ param string
+ value string
+}
+
+type argumentReadCensus struct {
+ funcs map[string]*ast.FuncDecl
+ readers map[string]argumentReader
+ stringLists map[string][]string
+ boolSets map[string]map[string]bool
+ dynamicSites map[string]int
+ memo map[string][]argumentRead
+}
+
+var requestAccessorMethod = regexp.MustCompile(`^(Require|Get)(String|Int|Float|Bool)(Slice)?$`)
+
+func newArgumentReadCensus(t *testing.T) *argumentReadCensus {
+ t.Helper()
+ census := &argumentReadCensus{
+ funcs: map[string]*ast.FuncDecl{},
+ readers: map[string]argumentReader{},
+ stringLists: map[string][]string{},
+ boolSets: map[string]map[string]bool{},
+ dynamicSites: map[string]int{},
+ memo: map[string][]argumentRead{},
+ }
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ file, err := parser.ParseFile(fset, name, nil, 0)
+ if err != nil {
+ t.Fatalf("cannot parse %s: %v", name, err)
+ }
+ for _, decl := range file.Decls {
+ switch d := decl.(type) {
+ case *ast.FuncDecl:
+ if d.Recv != nil || d.Body == nil {
+ continue
+ }
+ census.funcs[d.Name.Name] = d
+ if reader, ok := readerOf(d); ok {
+ census.readers[d.Name.Name] = reader
+ }
+ case *ast.GenDecl:
+ census.recordPackageVars(d)
+ }
+ }
+ }
+ if len(census.funcs) == 0 || len(census.readers) == 0 {
+ t.Fatal("no package functions or argument readers found, so this census checks nothing")
+ }
+ return census
+}
+
+func readerOf(fn *ast.FuncDecl) (argumentReader, bool) {
+ if !takesToolRequest(fn) {
+ return argumentReader{}, false
+ }
+ index := 0
+ for _, field := range fn.Type.Params.List {
+ for _, name := range field.Names {
+ if name.Name == "key" || name.Name == "keys" {
+ _, variadic := field.Type.(*ast.Ellipsis)
+ return argumentReader{keyIndex: index, variadic: variadic, typed: returnsTypedValue(fn)}, true
+ }
+ index++
+ }
+ }
+ return argumentReader{}, false
+}
+
+func takesToolRequest(fn *ast.FuncDecl) bool {
+ for _, field := range fn.Type.Params.List {
+ sel, ok := field.Type.(*ast.SelectorExpr)
+ if ok && sel.Sel.Name == "CallToolRequest" {
+ return true
+ }
+ }
+ return false
+}
+
+func returnsTypedValue(fn *ast.FuncDecl) bool {
+ if fn.Type.Results == nil || len(fn.Type.Results.List) == 0 {
+ return false
+ }
+ ident, ok := fn.Type.Results.List[0].Type.(*ast.Ident)
+ return ok && (ident.Name == "float64" || ident.Name == "int" || ident.Name == "bool")
+}
+
+func (c *argumentReadCensus) recordPackageVars(decl *ast.GenDecl) {
+ for _, spec := range decl.Specs {
+ value, ok := spec.(*ast.ValueSpec)
+ if !ok || len(value.Names) != len(value.Values) {
+ continue
+ }
+ for i, name := range value.Names {
+ literal, ok := value.Values[i].(*ast.CompositeLit)
+ if !ok {
+ continue
+ }
+ switch literal.Type.(type) {
+ case *ast.ArrayType:
+ if list, ok := stringLiterals(literal.Elts); ok {
+ c.stringLists[name.Name] = list
+ }
+ case *ast.MapType:
+ members := map[string]bool{}
+ for _, elt := range literal.Elts {
+ kv, ok := elt.(*ast.KeyValueExpr)
+ if !ok {
+ continue
+ }
+ key, keyOK := stringLiteral(kv.Key)
+ flag, flagOK := kv.Value.(*ast.Ident)
+ if keyOK && flagOK && flag.Name == "true" {
+ members[key] = true
+ }
+ }
+ c.boolSets[name.Name] = members
+ }
+ }
+ }
+}
+
+func stringLiteral(expr ast.Expr) (string, bool) {
+ lit, ok := expr.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ return "", false
+ }
+ value, err := strconv.Unquote(lit.Value)
+ return value, err == nil
+}
+
+func stringLiterals(exprs []ast.Expr) ([]string, bool) {
+ values := make([]string, 0, len(exprs))
+ for _, expr := range exprs {
+ value, ok := stringLiteral(expr)
+ if !ok {
+ return nil, false
+ }
+ values = append(values, value)
+ }
+ return values, true
+}
+
+func (c *argumentReadCensus) keysAt(call *ast.CallExpr, reader argumentReader, rangeKeys map[string][]string) ([]string, bool) {
+ if reader.keyIndex >= len(call.Args) {
+ return nil, true
+ }
+ args := call.Args[reader.keyIndex : reader.keyIndex+1]
+ if reader.variadic {
+ args = call.Args[reader.keyIndex:]
+ }
+ if call.Ellipsis.IsValid() && len(args) == 1 {
+ ident, ok := args[0].(*ast.Ident)
+ if !ok {
+ return nil, false
+ }
+ list, ok := c.stringLists[ident.Name]
+ return list, ok
+ }
+ var keys []string
+ for _, arg := range args {
+ if literal, ok := stringLiteral(arg); ok {
+ keys = append(keys, literal)
+ continue
+ }
+ ident, ok := arg.(*ast.Ident)
+ if !ok || rangeKeys[ident.Name] == nil {
+ return nil, false
+ }
+ keys = append(keys, rangeKeys[ident.Name]...)
+ }
+ return keys, true
+}
+
+func literalRangeKeys(body *ast.BlockStmt) map[string][]string {
+ keys := map[string][]string{}
+ ast.Inspect(body, func(n ast.Node) bool {
+ loop, ok := n.(*ast.RangeStmt)
+ if !ok {
+ return true
+ }
+ literal, ok := loop.X.(*ast.CompositeLit)
+ if !ok {
+ return true
+ }
+ switch literal.Type.(type) {
+ case *ast.ArrayType:
+ ident, isIdent := loop.Value.(*ast.Ident)
+ values, allStrings := stringLiterals(literal.Elts)
+ if isIdent && allStrings {
+ keys[ident.Name] = values
+ }
+ case *ast.MapType:
+ ident, isIdent := loop.Key.(*ast.Ident)
+ if !isIdent {
+ return true
+ }
+ for _, elt := range literal.Elts {
+ if kv, ok := elt.(*ast.KeyValueExpr); ok {
+ if key, ok := stringLiteral(kv.Key); ok {
+ keys[ident.Name] = append(keys[ident.Name], key)
+ }
+ }
+ }
+ }
+ return true
+ })
+ return keys
+}
+
+func (c *argumentReadCensus) readsOf(fn string, binding *paramBinding, visiting map[string]bool) []argumentRead {
+ if binding == nil {
+ if cached, ok := c.memo[fn]; ok {
+ return cached
+ }
+ }
+ decl, ok := c.funcs[fn]
+ if !ok || visiting[fn] {
+ return nil
+ }
+ visiting[fn] = true
+ defer delete(visiting, fn)
+
+ _, isReader := c.readers[fn]
+ requestMaps := argumentMapIdents(decl.Body)
+ rangeKeys := literalRangeKeys(decl.Body)
+ var reads []argumentRead
+ callees := map[string]bool{}
+ record := func(keys []string, resolved, typed bool) {
+ if !resolved {
+ if !isReader {
+ c.dynamicSites[fn]++
+ }
+ return
+ }
+ for _, key := range keys {
+ reads = append(reads, argumentRead{key: key, typed: typed, fn: fn})
+ }
+ }
+
+ var visit func(ast.Node) bool
+ visit = func(n ast.Node) bool {
+ switch node := n.(type) {
+ case *ast.SwitchStmt:
+ if binding == nil || !isIdent(node.Tag, binding.param) {
+ return true
+ }
+ if node.Init != nil {
+ ast.Inspect(node.Init, visit)
+ }
+ for _, clause := range boundCaseClauses(node, binding.value) {
+ for _, stmt := range clause.Body {
+ ast.Inspect(stmt, visit)
+ }
+ }
+ return false
+ case *ast.IfStmt:
+ if binding == nil {
+ return true
+ }
+ if holds, known := c.evalCondition(node.Cond, binding); known && !holds {
+ if node.Init != nil {
+ ast.Inspect(node.Init, visit)
+ }
+ if node.Else != nil {
+ ast.Inspect(node.Else, visit)
+ }
+ return false
+ }
+ case *ast.CallExpr:
+ switch fun := node.Fun.(type) {
+ case *ast.Ident:
+ if reader, ok := c.readers[fun.Name]; ok {
+ keys, resolved := c.keysAt(node, reader, rangeKeys)
+ record(keys, resolved, reader.typed)
+ }
+ if _, ok := c.funcs[fun.Name]; ok {
+ callees[fun.Name] = true
+ }
+ case *ast.SelectorExpr:
+ if match := requestAccessorMethod.FindStringSubmatch(fun.Sel.Name); match != nil && len(node.Args) > 0 {
+ key, resolved := stringLiteral(node.Args[0])
+ record([]string{key}, resolved, match[2] != "String")
+ }
+ }
+ case *ast.IndexExpr:
+ if readsArgumentMap(node.X, requestMaps) {
+ key, resolved := stringLiteral(node.Index)
+ record([]string{key}, resolved, false)
+ }
+ }
+ return true
+ }
+ ast.Inspect(decl.Body, visit)
+
+ for callee := range callees {
+ reads = append(reads, c.readsOf(callee, nil, visiting)...)
+ }
+ for _, key := range dynamicArgumentReads[fn] {
+ reads = append(reads, argumentRead{key: key, fn: fn})
+ }
+ if binding == nil {
+ c.memo[fn] = reads
+ }
+ return reads
+}
+
+func boundCaseClauses(node *ast.SwitchStmt, value string) []*ast.CaseClause {
+ var fallback *ast.CaseClause
+ for _, stmt := range node.Body.List {
+ clause := stmt.(*ast.CaseClause)
+ if clause.List == nil {
+ fallback = clause
+ continue
+ }
+ for _, expr := range clause.List {
+ if literal, ok := stringLiteral(expr); ok && literal == value {
+ return []*ast.CaseClause{clause}
+ }
+ }
+ }
+ if fallback != nil {
+ return []*ast.CaseClause{fallback}
+ }
+ return nil
+}
+
+func (c *argumentReadCensus) evalCondition(expr ast.Expr, binding *paramBinding) (holds, known bool) {
+ switch cond := expr.(type) {
+ case *ast.ParenExpr:
+ return c.evalCondition(cond.X, binding)
+ case *ast.UnaryExpr:
+ if cond.Op == token.NOT {
+ holds, known := c.evalCondition(cond.X, binding)
+ return !holds, known
+ }
+ case *ast.BinaryExpr:
+ left, leftKnown := c.evalCondition(cond.X, binding)
+ right, rightKnown := c.evalCondition(cond.Y, binding)
+ switch cond.Op {
+ case token.LAND:
+ if (leftKnown && !left) || (rightKnown && !right) {
+ return false, true
+ }
+ return true, leftKnown && rightKnown
+ case token.LOR:
+ if (leftKnown && left) || (rightKnown && right) {
+ return true, true
+ }
+ return false, leftKnown && rightKnown
+ case token.EQL, token.NEQ:
+ literal, ok := stringLiteral(cond.Y)
+ if !ok || !isIdent(cond.X, binding.param) {
+ return false, false
+ }
+ return (literal == binding.value) == (cond.Op == token.EQL), true
+ }
+ case *ast.IndexExpr:
+ set, ok := cond.X.(*ast.Ident)
+ if !ok || !isIdent(cond.Index, binding.param) {
+ return false, false
+ }
+ members, ok := c.boolSets[set.Name]
+ if !ok {
+ return false, false
+ }
+ return members[binding.value], true
+ }
+ return false, false
+}
+
+func argumentMapIdents(body *ast.BlockStmt) map[string]bool {
+ idents := map[string]bool{}
+ ast.Inspect(body, func(n ast.Node) bool {
+ assign, ok := n.(*ast.AssignStmt)
+ if !ok || len(assign.Lhs) != len(assign.Rhs) {
+ return true
+ }
+ for i, rhs := range assign.Rhs {
+ if isGetArgumentsCall(rhs) {
+ if ident, ok := assign.Lhs[i].(*ast.Ident); ok {
+ idents[ident.Name] = true
+ }
+ }
+ }
+ return true
+ })
+ return idents
+}
+
+func isGetArgumentsCall(expr ast.Expr) bool {
+ call, ok := expr.(*ast.CallExpr)
+ if !ok {
+ return false
+ }
+ sel, ok := call.Fun.(*ast.SelectorExpr)
+ return ok && sel.Sel.Name == "GetArguments"
+}
+
+func readsArgumentMap(expr ast.Expr, requestMaps map[string]bool) bool {
+ if isGetArgumentsCall(expr) {
+ return true
+ }
+ ident, ok := expr.(*ast.Ident)
+ return ok && requestMaps[ident.Name]
+}
+
+func toolRegistrations(t *testing.T) map[string]*ast.CallExpr {
+ t.Helper()
+ file, err := parser.ParseFile(token.NewFileSet(), "handlers.go", nil, 0)
+ if err != nil {
+ t.Fatalf("cannot parse handlers.go: %v", err)
+ }
+ registrations := map[string]*ast.CallExpr{}
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Name.Name != "rawHandlerMap" {
+ continue
+ }
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ kv, ok := n.(*ast.KeyValueExpr)
+ if !ok {
+ return true
+ }
+ name, nameOK := stringLiteral(kv.Key)
+ call, callOK := kv.Value.(*ast.CallExpr)
+ if nameOK && callOK {
+ registrations[name] = call
+ }
+ return true
+ })
+ }
+ if len(registrations) == 0 {
+ t.Fatal("found no tool registrations in rawHandlerMap, so this census checks nothing")
+ }
+ return registrations
+}
+
+func (c *argumentReadCensus) bindingFor(call *ast.CallExpr) (string, *paramBinding) {
+ handler, ok := call.Fun.(*ast.Ident)
+ if !ok {
+ return "", nil
+ }
+ decl, ok := c.funcs[handler.Name]
+ if !ok {
+ return handler.Name, nil
+ }
+ index := 0
+ for _, field := range decl.Type.Params.List {
+ for _, name := range field.Names {
+ if index < len(call.Args) {
+ if value, ok := stringLiteral(call.Args[index]); ok {
+ return handler.Name, &paramBinding{param: name.Name, value: value}
+ }
+ }
+ index++
+ }
+ }
+ return handler.Name, nil
+}
+
+func TestEveryArgumentAHandlerReadsIsDeclaredOnItsTool(t *testing.T) {
+ census := newArgumentReadCensus(t)
+ registrations := toolRegistrations(t)
+ properties := schemaPropertiesOnce()
+
+ total := 0
+ for tool, call := range registrations {
+ handler, binding := census.bindingFor(call)
+ reads := census.readsOf(handler, binding, map[string]bool{})
+ if len(reads) == 0 && len(properties[tool]) > 0 {
+ t.Errorf("%s declares %d arguments but the census found no read in %s; the walk no longer follows how this handler reads arguments", tool, len(properties[tool]), handler)
+ }
+ for _, read := range reads {
+ total++
+ kind, declared := properties[tool][read.key]
+ if !declared {
+ t.Errorf("%s reads %q (in %s) but the tool does not declare it, so the argument is refused before the handler can see it and is undiscoverable in tools/list", tool, read.key, read.fn)
+ continue
+ }
+ if read.typed && kind != "number" && kind != "integer" && kind != "boolean" {
+ t.Errorf("%s reads %q (in %s) with a typed accessor but declares it as %q, so validateTypedArgs cannot reject a malformed value", tool, read.key, read.fn, kind)
+ }
+ }
+ }
+ if total == 0 {
+ t.Fatal("no argument read found in any handler, so this census checks nothing")
+ }
+
+ for fn, count := range census.dynamicSites {
+ if _, recorded := dynamicArgumentReads[fn]; !recorded {
+ t.Errorf("%s reads %d argument(s) under a name the census cannot resolve; use a literal key or record the names it can take in dynamicArgumentReads", fn, count)
+ }
+ }
+ for fn := range dynamicArgumentReads {
+ if census.dynamicSites[fn] == 0 {
+ t.Errorf("dynamicArgumentReads records %s, which no longer reads an argument under a computed name; drop the entry", fn)
+ }
+ }
+ t.Logf("checked %d argument reads across %d tools", total, len(registrations))
+}
+
+func TestTheReadCensusAttributesSharedHandlerReadsToTheBoundTool(t *testing.T) {
+ census := newArgumentReadCensus(t)
+ registrations := toolRegistrations(t)
+ readsFor := func(tool string) map[string]bool {
+ handler, binding := census.bindingFor(registrations[tool])
+ keys := map[string]bool{}
+ for _, read := range census.readsOf(handler, binding, map[string]bool{}) {
+ keys[read.key] = true
+ }
+ return keys
+ }
+
+ for _, tc := range []struct {
+ tool string
+ reads []string
+ ignores []string
+ }{
+ {tool: "pinchtab_click", reads: []string{"x", "humanize", "onDialog", "element", "target", "snap", "browser"}, ignores: []string{"pixels", "option"}},
+ {tool: "pinchtab_type", reads: []string{"text", "value", "ref"}, ignores: []string{"x", "humanize", "snap"}},
+ {tool: "pinchtab_wait", reads: []string{"timeoutMs", "timeout", "for", "value", "state"}},
+ {tool: "pinchtab_key", reads: []string{"key", "text", "action"}},
+ } {
+ keys := readsFor(tc.tool)
+ for _, key := range tc.reads {
+ if !keys[key] {
+ t.Errorf("census finds no read of %q on %s (found %v); it has lost track of an argument idiom", key, tc.tool, keys)
+ }
+ }
+ for _, key := range tc.ignores {
+ if keys[key] {
+ t.Errorf("census attributes %q to %s, whose kind never reads it; the shared-handler narrowing is broken", key, tc.tool)
+ }
+ }
+ }
+}
diff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.go
index c046c413..82f55ff6 100644
--- a/internal/mcp/handlers_helpers.go
+++ b/internal/mcp/handlers_helpers.go
@@ -34,6 +34,15 @@ func optFloat(r mcp.CallToolRequest, key string) (float64, bool) {
return 0, false
}
+func firstFloat(r mcp.CallToolRequest, keys ...string) (float64, bool) {
+ for _, key := range keys {
+ if v, ok := optFloat(r, key); ok {
+ return v, true
+ }
+ }
+ return 0, false
+}
+
func optInt(r mcp.CallToolRequest, key string) (int, bool) {
v, ok := optFloat(r, key)
return int(v), ok
@@ -187,7 +196,7 @@ func firstSelectorString(r mcp.CallToolRequest, keys ...string) (value, wrongKey
// A wrong-typed selector alias refuses rather than falling through to a different argument.
func actionSelectorArg(r mcp.CallToolRequest) (sel, wrongKey, wrongType string) {
- sel, wrongKey, wrongType = firstSelectorString(r, "selector", "ref", "element", "target")
+ sel, wrongKey, wrongType = firstSelectorString(r, selectorArgKeys...)
if sel != "" || wrongType != "" {
return sel, wrongKey, wrongType
}
diff --git a/internal/mcp/handlers_interaction_test.go b/internal/mcp/handlers_interaction_test.go
index 82274ed4..3e8560c1 100644
--- a/internal/mcp/handlers_interaction_test.go
+++ b/internal/mcp/handlers_interaction_test.go
@@ -575,6 +575,14 @@ func actionArgs(tool string, extra map[string]any) map[string]any {
return args
}
+func targetedActionArgs(tool string, extra map[string]any) map[string]any {
+ args := actionArgs(tool, extra)
+ if _, declared := schemaPropertiesOnce()[tool]["selector"]; declared {
+ args["selector"] = "#a"
+ }
+ return args
+}
+
// nodeId was read before the switch on kind, so all nine tools forwarded it, but
// only click, hover and focus declared it. On the other six that meant no
// discovery and — because validateTypedArgs keys its type map per tool — no
@@ -583,7 +591,7 @@ func TestEveryActionToolAcceptsAndValidatesNodeID(t *testing.T) {
for _, tc := range actionToolTargets {
t.Run(tc.tool, func(t *testing.T) {
srv, _ := upstreamRecorder(t)
- result := callTool(t, tc.tool, actionArgs(tc.tool, map[string]any{"selector": "#a", "nodeId": float64(42)}), srv)
+ result := callTool(t, tc.tool, targetedActionArgs(tc.tool, map[string]any{"nodeId": float64(42)}), srv)
if result.IsError {
t.Fatalf("a valid nodeId was rejected: %s", resultText(t, result))
}
@@ -593,7 +601,7 @@ func TestEveryActionToolAcceptsAndValidatesNodeID(t *testing.T) {
}
srv2, paths := upstreamRecorder(t)
- malformed := callTool(t, tc.tool, actionArgs(tc.tool, map[string]any{"selector": "#a", "nodeId": "abc"}), srv2)
+ malformed := callTool(t, tc.tool, targetedActionArgs(tc.tool, map[string]any{"nodeId": "abc"}), srv2)
if !malformed.IsError {
t.Fatalf("nodeId \"abc\" was accepted and silently dropped; upstream saw %v", *paths)
}
@@ -644,20 +652,29 @@ func TestNodeIDAloneSatisfiesTheTargetRequirement(t *testing.T) {
// x/y had the same shape as nodeId — read before the switch, so forwarded for all
// nine kinds with hasXY set — but the opposite correct answer: the bridge honours
// coordinates only for the pointer kinds, so the fix is to stop reading it
-// elsewhere rather than to declare it everywhere.
+// elsewhere rather than to declare it everywhere. A tool that does not declare
+// them refuses them by name instead of dropping them.
func TestCoordinatesReachTheWireOnlyForTheToolsThatDeclareThem(t *testing.T) {
for _, tc := range actionToolTargets {
t.Run(tc.tool, func(t *testing.T) {
_, declared := schemaArgTypesOnce()[tc.tool]["x"]
- srv, _ := upstreamRecorder(t)
- result := callTool(t, tc.tool, actionArgs(tc.tool, map[string]any{"selector": "#a", "x": float64(11), "y": float64(22)}), srv)
+ srv, paths := upstreamRecorder(t)
+ result := callTool(t, tc.tool, targetedActionArgs(tc.tool, map[string]any{"x": float64(11), "y": float64(22)}), srv)
+ if !declared {
+ if !result.IsError || !strings.Contains(resultText(t, result), `unknown argument "x"`) {
+ t.Fatalf("%s does not declare x/y but did not refuse them by name: %s", tc.tool, resultText(t, result))
+ }
+ if len(*paths) != 0 {
+ t.Errorf("refused coordinates still reached upstream: %v", *paths)
+ }
+ return
+ }
if result.IsError {
t.Fatalf("coordinates were rejected: %s", resultText(t, result))
}
body, _ := resultJSON(t, result)["body"].(map[string]any)
- _, forwarded := body["hasXY"]
- if declared != forwarded {
- t.Errorf("%s declares x/y = %v but forwards them = %v (body %v)", tc.tool, declared, forwarded, body)
+ if _, forwarded := body["hasXY"]; !forwarded {
+ t.Errorf("%s declares x/y but does not forward them (body %v)", tc.tool, body)
}
})
}
diff --git a/internal/mcp/handlers_wait.go b/internal/mcp/handlers_wait.go
index 9fb4127c..1f253435 100644
--- a/internal/mcp/handlers_wait.go
+++ b/internal/mcp/handlers_wait.go
@@ -59,7 +59,7 @@ func sleepFor(ctx context.Context, value string) (*mcp.CallToolResult, error) {
}
func callWaitEndpoint(ctx context.Context, c *Client, r mcp.CallToolRequest, payload map[string]any) (*mcp.CallToolResult, error) {
- if timeout, ok := optFloat(r, "timeout"); ok {
+ if timeout, ok := firstFloat(r, "timeoutMs", "timeout"); ok {
payload["timeout"] = int(timeout)
}
if state := optString(r, "state"); state != "" {
diff --git a/internal/mcp/testdata/preamble_budget.json b/internal/mcp/testdata/preamble_budget.json
index d9feec1e..17dd9f6c 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": 42200,
- "takenOn": "2026-09-12",
- "commit": "cee8a04b"
+ "maxBytes": 44300,
+ "takenOn": "2026-09-13",
+ "commit": "52bcc08d"
},
{
"surface": "skills/pinchtab-mcp/SKILL.md",
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index ba0d8fbe..a4472fc9 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -104,10 +104,12 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_click",
mcp.WithDescription("Click an element. Prefer selector from pinchtab_find.best_ref (e.g. 'e5') to avoid extra snapshots."),
mcp.WithString("selector", mcp.Description("Unified selector: ref (e.g. 'e5'), CSS, XPath, text, find, role, label, placeholder, alt, title, testid, or first/last/nth. Non-ref selectors resolve in the current frame scope."+positionalWrapperGrammar)),
- refParam(),
+ selectorAliasParams(),
mcp.WithString("query", mcp.Description("Alias for semantic targeting when selector is omitted (example: 'login button' -> find:login button)")),
mcp.WithString("dialogAction", mcp.Description("Optional one-shot dialog handling for this click: 'accept' or 'dismiss'")),
mcp.WithString("dialogText", mcp.Description("Optional prompt text used with dialogAction='accept'")),
+ stringAliasParam("onDialog", "dialogAction"),
+ stringAliasParam("promptText", "dialogText"),
mcp.WithNumber("x", mcp.Description("Optional X coordinate for coordinate click")),
mcp.WithNumber("y", mcp.Description("Optional Y coordinate for coordinate click")),
nodeIDParam(),
@@ -121,9 +123,10 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_type",
mcp.WithDescription("Type text into an input element"),
selectorParam(),
- refParam(),
+ selectorAliasParams(),
queryParam(),
textToTypeParam(),
+ stringAliasParam("value", "text"),
nodeIDParam(),
tabIDParam(),
browserParam(),
@@ -131,7 +134,7 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_hover",
mcp.WithDescription("Hover over an element"),
selectorParam(),
- refParam(),
+ selectorAliasParams(),
queryParam(),
mcp.WithNumber("x", mcp.Description("Optional X coordinate for coordinate hover")),
mcp.WithNumber("y", mcp.Description("Optional Y coordinate for coordinate hover")),
@@ -143,7 +146,7 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_focus",
mcp.WithDescription("Focus an element"),
selectorParam(),
- refParam(),
+ selectorAliasParams(),
queryParam(),
nodeIDParam(),
tabIDParam(),
@@ -152,9 +155,10 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_select",
mcp.WithDescription("Select a dropdown option by value or visible text"),
mcp.WithString("selector", mcp.Description("Unified selector for the select element. Non-ref selectors resolve in the current frame scope.")),
- refParam(),
+ selectorAliasParams(),
queryParam(),
mcp.WithString("value", mcp.Required(), mcp.Description("Option value or visible text to select")),
+ stringAliasParam("option", "value"),
nodeIDParam(),
tabIDParam(),
mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after select (saves a round-trip)")),
@@ -163,7 +167,7 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_scroll",
mcp.WithDescription("Scroll the page or an element. For element targeting + pixel deltas, this automatically uses wheel semantics for smoother behavior."),
mcp.WithString("selector", mcp.Description("Unified selector for element to scroll (omit for page scroll). Non-ref selectors resolve in the current frame scope.")),
- refParam(),
+ selectorAliasParams(),
queryParam(),
mcp.WithNumber("pixels", mcp.Description("Number of pixels to scroll (positive=down, negative=up)")),
mcp.WithNumber("deltaX", mcp.Description("Horizontal wheel delta for precise scrolling")),
@@ -183,7 +187,7 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_scroll_into_view",
mcp.WithDescription("Scroll a target element into view and return geometry details for stable follow-up actions."),
selectorParam(),
- refParam(),
+ selectorAliasParams(),
queryParam(),
nodeIDParam(),
tabIDParam(),
@@ -192,9 +196,10 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_fill",
mcp.WithDescription("Fill an input field directly via JavaScript dispatch"),
selectorParam(),
- refParam(),
+ selectorAliasParams(),
queryParam(),
mcp.WithString("value", mcp.Required(), mcp.Description("Value to fill; send an empty string to clear the field")),
+ stringAliasParam("text", "value"),
nodeIDParam(),
tabIDParam(),
mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after fill (saves a round-trip)")),
@@ -281,7 +286,8 @@ func allTools() []mcp.Tool {
mcp.WithDescription("Wait for one condition; 'for' picks which and 'value' carries it. for='ms': wait a specified number of milliseconds (max 30000; needs no browser). for='selector': wait for an element matching a unified selector (CSS, XPath, text, or ref) to appear or disappear on the page — see 'state'. for='text': wait for specific text to appear on the page. for='url': wait for the page URL to match a glob pattern (e.g. '**/dashboard'). for='load': wait for a page load state — 'ready-state' (readyState=complete), 'content-loaded' (readyState in {interactive, complete}), or 'network-idle' (0 in-flight requests for 500ms). for='function': wait for a JavaScript expression to return a truthy value."),
mcp.WithString("for", mcp.Required(), mcp.Enum("ms", "selector", "text", "url", "load", "function"), mcp.Description("What to wait for")),
mcp.WithString("value", mcp.Required(), mcp.Description("What to wait for, read as 'for' says: a millisecond count, a selector, page text, a URL glob pattern, a load state, or a JavaScript expression")),
- timeoutParam(),
+ timeoutMsParam(),
+ numberAliasParam("timeout", "timeoutMs"),
mcp.WithString("state", mcp.Description("Element state to wait for with for='selector': 'visible' (default) or 'hidden'")),
tabIDParam(),
browserParam(),
@@ -368,7 +374,7 @@ func allTools() []mcp.Tool {
mcp.WithNumber("concurrency", mcp.Description("Pages browser-rendered in parallel (default 2, max 8)")),
mcp.WithBoolean("enrichAll", mcp.Description("Browser-render every reachable page, ignoring routing")),
mcp.WithBoolean("noBrowser", mcp.Description("HTTP crawl only; record routing verdicts without browser rendering")),
- mcp.WithNumber("timeoutSeconds", mcp.Description("Overall HTTP crawl timeout in seconds (default 60)")),
+ mcp.WithNumber("timeoutSeconds", mcp.Description("Overall HTTP crawl budget in SECONDS (default 60); unlike the millisecond timeoutMs of pinchtab_wait and pinchtab_handoff")),
browserParam(),
),
a11yAuditTool(),
diff --git a/internal/mcp/tools_params.go b/internal/mcp/tools_params.go
index e7fef8df..7874aa97 100644
--- a/internal/mcp/tools_params.go
+++ b/internal/mcp/tools_params.go
@@ -25,8 +25,26 @@ func selectorParam() mcp.ToolOption {
return mcp.WithString("selector", mcp.Description("Unified selector: ref (e.g. 'e5'), CSS, XPath, text, or semantic. Non-ref selectors resolve in the current frame scope."))
}
-func refParam() mcp.ToolOption {
- return mcp.WithString("ref", mcp.Description("(deprecated) Element ref from snapshot — use 'selector' instead"))
+var selectorArgKeys = []string{"selector", "ref", "element", "target"}
+
+func selectorAliasParams() mcp.ToolOption {
+ return func(tool *mcp.Tool) {
+ for _, alias := range selectorArgKeys[1:] {
+ stringAliasParam(alias, selectorArgKeys[0])(tool)
+ }
+ }
+}
+
+func stringAliasParam(alias, canonical string) mcp.ToolOption {
+ return mcp.WithString(alias, aliasDescription(canonical))
+}
+
+func numberAliasParam(alias, canonical string) mcp.ToolOption {
+ return mcp.WithNumber(alias, aliasDescription(canonical))
+}
+
+func aliasDescription(canonical string) mcp.PropertyOption {
+ return mcp.Description("(deprecated) alias of '" + canonical + "'; send '" + canonical + "' instead")
}
func nodeIDParam() mcp.ToolOption {
@@ -37,8 +55,8 @@ func queryParam() mcp.ToolOption {
return mcp.WithString("query", mcp.Description("Alias for semantic targeting when selector is omitted"))
}
-func timeoutParam() mcp.ToolOption {
- return mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)"))
+func timeoutMsParam() mcp.ToolOption {
+ return mcp.WithNumber("timeoutMs", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)"))
}
func snapParam() mcp.ToolOption {
diff --git a/plugins/grok/skills/pinchtab/references/mcp.md b/plugins/grok/skills/pinchtab/references/mcp.md
index fb35acca..e01e2b2f 100644
--- a/plugins/grok/skills/pinchtab/references/mcp.md
+++ b/plugins/grok/skills/pinchtab/references/mcp.md
@@ -48,14 +48,16 @@ For Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.
All tool names are prefixed with `pinchtab_`.
+A tool refuses any argument it does not declare: the error names the unknown key, the nearest declared name when one is close, and the tool's declared arguments, and nothing runs. Time budgets are milliseconds (`timeoutMs`) everywhere except `pinchtab_scrape`'s crawl budget `timeoutSeconds`.
+
### Navigation
| Tool | Description |
|------|-------------|
-| `pinchtab_navigate` | Navigate to a URL. Required param: `url`. Optional: `tabId`. |
+| `pinchtab_navigate` | Navigate to a URL. Required param: `url`. Optional: `tabId`, `newTab` (open in a new tab instead of reusing the current one; the returned `tabId` targets it), `snap`. |
| `pinchtab_snapshot` | Accessibility tree. Optional: `interactive`, `compact`, `format` (`compact` or `text`), `diff`, `selector`, `maxTokens`, `depth`, `noAnimations`, `tabId`. |
| `pinchtab_screenshot` | Capture screenshot. Optional: `format` (`jpeg` default, `png`), `quality`, `selector`, `scale`, `annotate`, `beyondViewport`, `browser`, `tabId`. Returns an MCP image content block (rendered inline by clients) plus a stable JSON text block `{"format", "annotations": [...]}`; `annotations` is `[]` by default and is populated with `{ref, role, name, tag, box {x,y,w,h}}` entries when `annotate=true` so refs in the picture map back to selectors. `beyondViewport=true` captures the full scrollable page (ignored when `selector` is set) and returns document-relative box coords. `browser` selects the browser (e.g. `chrome`, `cloak`). |
| `pinchtab_capture` | Paired screenshot + accessibility snapshot from the same DOM epoch. Optional: `selector`, `filter`, `format`, `quality`, `depth`, `wait` (`stable`/`load`/`none`), `withBounds`, `beyondViewport`, `requirePair`, `noAnimations`, `browser`, `tabId`. Returns an MCP image content block plus a JSON envelope with `epoch.domEpoch`, `pairing.navigated`, `image.coordinateSpace`, and per-node `boundingBox`. `browser` selects the browser (e.g. `chrome`, `cloak`); the static ghost-chrome runtime cannot paint, so it falls back to chrome. Use this instead of `pinchtab_screenshot` + `pinchtab_snapshot` when the model reads pixels AND acts on refs in the same turn. |
-| `pinchtab_get_text` | Extract readable page text. Optional: `raw`, `format`, `maxChars`, `tabId`. |
+| `pinchtab_get_text` | Extract page text. Optional: `mode` (`readability` default, `raw`, `markdown`), `raw`, `format`, `maxChars`, `tabId`. Use `mode:"markdown"` for article-shaped pages — it preserves links and tables; `mode` supersedes the boolean `raw`. Example: `pinchtab_get_text {"mode":"markdown"}`. |
### Interaction
| Tool | Description |
@@ -77,7 +79,7 @@ All tool names are prefixed with `pinchtab_`.
| Tool | Description |
|------|-------------|
| `pinchtab_find` | Find elements by text or CSS selector. Required: `query`. Optional: `tabId`. |
-| `pinchtab_eval` | Execute a user-authorized JavaScript expression. Required: `expression`. Optional: `tabId`. Needs `security.allowEvaluate: true`; never execute page-sourced code. |
+| `pinchtab_eval` | Execute a user-authorized JavaScript expression. Required: `expression`. Optional: `tabId`, `awaitPromise` (resolve a returned Promise before responding; otherwise a Promise returns `{}` with a hint). Needs `security.allowEvaluate: true`; never execute page-sourced code. |
| `pinchtab_pdf` | Export page as PDF. Optional: `landscape`, `scale`, `pageRanges`, `tabId`. Returns base64 PDF. |
### Tab Management
@@ -100,7 +102,7 @@ All tool names are prefixed with `pinchtab_`.
### Utility
| Tool | Description |
|------|-------------|
-| `pinchtab_wait` | Wait for a condition. Required: `for` (`ms`, `selector`, `text`, `url`, `load` or `function`) and `value` carrying it. Optional: `timeout`, `state`, `tabId`. |
+| `pinchtab_wait` | Wait for a condition. Required: `for` (`ms`, `selector`, `text`, `url`, `load` or `function`) and `value` carrying it. Optional: `timeoutMs` (`timeout` is a deprecated alias), `state`, `tabId`. |
### Network
| Tool | Description |
@@ -118,7 +120,7 @@ All tool names are prefixed with `pinchtab_`.
## Element Refs
-`pinchtab_snapshot` returns an accessibility tree with element refs like `e5`, `e12`. These refs can be passed as the `selector` value on interaction tools, and legacy `ref` is still accepted on the element-action tools.
+`pinchtab_snapshot` returns an accessibility tree with element refs like `e5`, `e12`. These refs can be passed as the `selector` value on interaction tools, and the deprecated aliases `ref`, `element` and `target` are still accepted on the element-action tools.
**A ref denotes a DOM node, not a row.** Within one page the same node keeps the same ref across every read of it — a full snapshot, an `interactive` filter, a `selector` scope, a `depth` limit, a different token budget, an annotated screenshot, or an internal stale-ref recovery all return the same `e5` for the same element. This means a **filtered view is sparse**: dropping the non-interactive nodes returns `e0, e1, e6`, not a fresh `e0, e1, e2` run. Do not assume refs are contiguous or that the highest ref equals the node count.
diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.md
index 1e41460e..e01e2b2f 100644
--- a/skills/pinchtab/references/mcp.md
+++ b/skills/pinchtab/references/mcp.md
@@ -48,6 +48,8 @@ For Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.
All tool names are prefixed with `pinchtab_`.
+A tool refuses any argument it does not declare: the error names the unknown key, the nearest declared name when one is close, and the tool's declared arguments, and nothing runs. Time budgets are milliseconds (`timeoutMs`) everywhere except `pinchtab_scrape`'s crawl budget `timeoutSeconds`.
+
### Navigation
| Tool | Description |
|------|-------------|
@@ -100,7 +102,7 @@ All tool names are prefixed with `pinchtab_`.
### Utility
| Tool | Description |
|------|-------------|
-| `pinchtab_wait` | Wait for a condition. Required: `for` (`ms`, `selector`, `text`, `url`, `load` or `function`) and `value` carrying it. Optional: `timeout`, `state`, `tabId`. |
+| `pinchtab_wait` | Wait for a condition. Required: `for` (`ms`, `selector`, `text`, `url`, `load` or `function`) and `value` carrying it. Optional: `timeoutMs` (`timeout` is a deprecated alias), `state`, `tabId`. |
### Network
| Tool | Description |
@@ -118,7 +120,7 @@ All tool names are prefixed with `pinchtab_`.
## Element Refs
-`pinchtab_snapshot` returns an accessibility tree with element refs like `e5`, `e12`. These refs can be passed as the `selector` value on interaction tools, and legacy `ref` is still accepted on the element-action tools.
+`pinchtab_snapshot` returns an accessibility tree with element refs like `e5`, `e12`. These refs can be passed as the `selector` value on interaction tools, and the deprecated aliases `ref`, `element` and `target` are still accepted on the element-action tools.
**A ref denotes a DOM node, not a row.** Within one page the same node keeps the same ref across every read of it — a full snapshot, an `interactive` filter, a `selector` scope, a `depth` limit, a different token budget, an annotated screenshot, or an internal stale-ref recovery all return the same `e5` for the same element. This means a **filtered view is sparse**: dropping the non-interactive nodes returns `e0, e1, e6`, not a fresh `e0, e1, e2` run. Do not assume refs are contiguous or that the highest ref equals the node count.