Skip to content

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

fix: the CLI cookies namespace offers only clear-all - setting a cookie has no CLI route, while the analogous storage command has full CRUD (PIN-137)

Luigi Agostifcf2f1d6948c
diff --git a/cmd/pinchtab/cmd_cli_cookies.go b/cmd/pinchtab/cmd_cli_cookies.go
index 1ecd499a..29babb51 100644
--- a/cmd/pinchtab/cmd_cli_cookies.go
+++ b/cmd/pinchtab/cmd_cli_cookies.go
@@ -8,13 +8,42 @@ import (
var cookiesCmd = &cobra.Command{
Use: "cookies",
Short: "Manage browser cookies",
- Long: "Commands for managing browser cookies.",
+ Long: "Read, set and clear browser cookies for the tab you are driving. Requires security.allowCookies.",
+}
+
+var cookiesGetCmd = &cobra.Command{
+ Use: "get",
+ Short: "Get cookies for the current page",
+ Long: "Read the cookies visible to a tab's current URL, with values. Use --name for one cookie, --url to read another origin.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.CookiesGet(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var cookiesSetCmd = &cobra.Command{
+ Use: "set <name> <value>",
+ Short: "Set a cookie on the current page",
+ Long: `Set one cookie on the tab's current URL, which is how a session is reused
+without replaying a whole saved state. The URL defaults to the tab's current page;
+pass --url to target another origin. An empty value is honoured, blanking the
+cookie without deleting it.`,
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.CookiesSet(rt.client, rt.base, rt.token, cmd, args[0], args[1])
+ })
+ },
}
var cookiesClearCmd = &cobra.Command{
Use: "clear",
- Short: "Clear all browser cookies",
- Long: "Clear all browser cookies via CDP. This affects all origins.",
+ Short: "Clear every cookie in the browser (all origins, not just this tab)",
+ Long: `Clear all browser cookies via CDP. This affects all origins and cannot be
+scoped to one tab or one domain — there is no per-cookie removal verb. Nothing in
+the CLI restores them; re-set what you need with cookies set, or reload a saved
+state with state load.`,
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
browseractions.CookiesClear(rt.client, rt.base, rt.token, cmd)
@@ -23,5 +52,17 @@ var cookiesClearCmd = &cobra.Command{
}
func init() {
- cookiesCmd.AddCommand(cookiesClearCmd)
+ cookiesCmd.AddCommand(cookiesGetCmd, cookiesSetCmd, cookiesClearCmd)
+
+ addTabFlag(cookiesGetCmd, cookiesSetCmd)
+
+ cookiesGetCmd.Flags().String("name", "", "Only return the cookie with this name")
+ cookiesGetCmd.Flags().String("url", "", "Read cookies for this URL instead of the tab's current page")
+
+ cookiesSetCmd.Flags().String("url", "", "Target URL (default: the tab's current page)")
+ cookiesSetCmd.Flags().String("domain", "", "Cookie domain")
+ cookiesSetCmd.Flags().String("path", "", "Cookie path")
+ cookiesSetCmd.Flags().String("same-site", "", "SameSite attribute: Strict, Lax or None")
+ cookiesSetCmd.Flags().Bool("secure", false, "Mark the cookie Secure")
+ cookiesSetCmd.Flags().Bool("http-only", false, "Mark the cookie HttpOnly")
}
diff --git a/cmd/pinchtab/cmd_cli_cookies_test.go b/cmd/pinchtab/cmd_cli_cookies_test.go
new file mode 100644
index 00000000..40ac566e
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_cookies_test.go
@@ -0,0 +1,45 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+// `cookies --help` is where a caller looks for a way to read or set a cookie, and it
+// used to answer with delete-everything only. Short is what that listing shows, so the
+// verbs and the breadth of clear have to be readable there.
+func TestCookiesNamespaceOffersReadAndWriteVerbs(t *testing.T) {
+ verbs := map[string]*string{}
+ for _, sub := range cookiesCmd.Commands() {
+ verbs[sub.Name()] = &sub.Short
+ }
+
+ for _, want := range []string{"get", "set", "clear"} {
+ if _, ok := verbs[want]; !ok {
+ t.Errorf("pinchtab cookies has no %q verb; its subcommands are %v", want, cookiesCmd.Commands())
+ }
+ }
+
+ clear, ok := verbs["clear"]
+ if !ok {
+ t.Fatal("no clear verb to check")
+ }
+ if !strings.Contains(strings.ToLower(*clear), "all origins") {
+ t.Errorf("cookies clear Short = %q; --help shows Short only, so the browser-wide effect must be stated there", *clear)
+ }
+}
+
+func TestCookiesSetTakesTheAttributeFlagsAndATab(t *testing.T) {
+ set, _, err := cookiesCmd.Find([]string{"set"})
+ if err != nil || set.Name() != "set" {
+ t.Fatalf("pinchtab cookies has no set verb: %v", err)
+ }
+ if set.Args == nil {
+ t.Error("cookies set declares no argument count, so a missing value is not rejected")
+ }
+ for _, flag := range []string{"tab", "url", "domain", "path", "same-site", "secure", "http-only", "json"} {
+ if set.Flags().Lookup(flag) == nil {
+ t.Errorf("cookies set has no --%s flag", flag)
+ }
+ }
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 3fb20f6c..594d9081 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -320,6 +320,7 @@ func configureBrowserFlags() {
cacheClearCmd,
cacheStatusCmd,
cookiesClearCmd,
+ cookiesSetCmd,
frameCmd,
networkCmd,
setViewportCmd,
diff --git a/docs/architecture/mcp.md b/docs/architecture/mcp.md
index c5282d2f..0527c351 100644
--- a/docs/architecture/mcp.md
+++ b/docs/architecture/mcp.md
@@ -115,7 +115,7 @@ URL validation lives in `handleNavigate` (`handlers_navigation.go`), which calls
## Security Considerations
- **`pinchtab_eval`** calls `/evaluate`, which requires `security.allowEvaluate: true` in the PinchTab config. It returns HTTP 403 by default. This is intentional — arbitrary JS execution is a separate opt-in from browser control.
-- **`pinchtab_cookies`** calls `/cookies`, which requires `security.allowCookies: true`. Cookie values can expose session credentials, so cookie operations are disabled by default.
+- **`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` and `pinchtab_wait_for_selector` enforce a 30-second maximum to prevent agent runaway.
diff --git a/docs/mcp.md b/docs/mcp.md
index 71269e1a..3bccf9fd 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -81,7 +81,7 @@ pinchtab --server http://remote:9867 mcp
## Available Tools
-PinchTab currently exposes 46 tools:
+PinchTab currently exposes 47 tools:
- Navigation: 9
- Interaction: 9
@@ -147,6 +147,7 @@ PinchTab currently exposes 46 tools:
- `pinchtab_close_tab`
- `pinchtab_health`
- `pinchtab_cookies` (requires `security.allowCookies`)
+- `pinchtab_cookies_set` (requires `security.allowCookies`)
- `pinchtab_connect_profile`
### Wait Utilities
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index 3087747a..9a776867 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -79,6 +79,7 @@ All element-action tools accept the unified `selector` and the legacy aliases `r
| `pinchtab_close_tab` | `tabId` optional | Closes the given tab, or the current/default tab when omitted |
| `pinchtab_health` | none | Checks server health |
| `pinchtab_cookies` | `tabId` | Reads cookies for a tab; requires `security.allowCookies` |
+| `pinchtab_cookies_set` | `name`, `value` required; `url`, `domain`, `path`, `sameSite`, `secure`, `httpOnly`, `expires`, `tabId` optional | Sets one cookie for session reuse; `url` defaults to the tab's current page and an empty `value` blanks the cookie; requires `security.allowCookies` |
| `pinchtab_connect_profile` | `profile` required | Returns the connect URL and instance status for a profile |
## Wait Utilities
diff --git a/docs/reference/tabs.md b/docs/reference/tabs.md
index bf78087e..be98971a 100644
--- a/docs/reference/tabs.md
+++ b/docs/reference/tabs.md
@@ -246,12 +246,26 @@ curl -X POST http://localhost:9867/tabs/<tabId>/cookies \
-d '{"cookies":[{"name":"session","value":"abc"}]}'
```
-A `pinchtab cookies` CLI command is available; today it exposes a single subcommand:
+`POST` defaults `url` to the tab's current page, so injecting a session cookie
+needs no URL lookup. A cookie with an empty `value` is set (blanking it without
+deleting it); a cookie with no `name` is rejected with 400 rather than skipped.
+`DELETE /tabs/<tabId>/cookies` is tab-scoped in addressing only — it clears every
+cookie for every origin, exactly like `DELETE /cookies`.
+
+The same operations from the CLI:
```bash
-pinchtab cookies clear # clear all cookies via CDP (affects all origins)
+pinchtab cookies get --tab <tabId> # read cookies, with values
+pinchtab cookies get --tab <tabId> --name session # one cookie
+pinchtab cookies set session abc123 --tab <tabId> # set on the tab's current URL
+pinchtab cookies clear # every cookie, every origin
```
+`cookies set` takes `--url`, `--domain`, `--path`, `--same-site`, `--secure` and
+`--http-only`; it exits non-zero if the server reports the cookie was not set.
+There is no per-cookie removal verb — `clear` is browser-wide, and nothing in the
+CLI restores what it wipes, so re-set what you need or use `state load`.
+
Reading, writing, and clearing cookies requires `security.allowCookies=true`.
## Metrics
diff --git a/internal/cli/actions/actions_cookies.go b/internal/cli/actions/actions_cookies.go
index cdf80a18..fa29e813 100644
--- a/internal/cli/actions/actions_cookies.go
+++ b/internal/cli/actions/actions_cookies.go
@@ -4,12 +4,67 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "net/url"
"os"
"github.com/pinchtab/pinchtab/internal/cli/apiclient"
"github.com/spf13/cobra"
)
+// CookiesGet reads the cookies visible to a tab's current URL.
+func CookiesGet(client *http.Client, base, token string, cmd *cobra.Command) {
+ params := url.Values{}
+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {
+ params.Set("tabId", tab)
+ }
+ if name, _ := cmd.Flags().GetString("name"); name != "" {
+ params.Set("name", name)
+ }
+ if target, _ := cmd.Flags().GetString("url"); target != "" {
+ params.Set("url", target)
+ }
+
+ result := requireBytes(apiclient.DoGetRaw(client, base, token, "/cookies", params), 1, "Failed to get cookies")
+ printIndented(decodeMap(result, 1, "Failed to parse response"))
+}
+
+// CookiesSet sets one cookie on the tab's current URL. The URL is left to the
+// server to default from the tab, so injecting a session cookie is one command
+// and never needs the caller to look the page up first.
+func CookiesSet(client *http.Client, base, token string, cmd *cobra.Command, name, value string) {
+ cookie := map[string]any{"name": name, "value": value}
+ for flag, key := range map[string]string{
+ "domain": "domain",
+ "path": "path",
+ "same-site": "sameSite",
+ } {
+ if v, _ := cmd.Flags().GetString(flag); v != "" {
+ cookie[key] = v
+ }
+ }
+ if secure, _ := cmd.Flags().GetBool("secure"); secure {
+ cookie["secure"] = true
+ }
+ if httpOnly, _ := cmd.Flags().GetBool("http-only"); httpOnly {
+ cookie["httpOnly"] = true
+ }
+
+ body := map[string]any{"cookies": []any{cookie}}
+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {
+ body["tabId"] = tab
+ }
+ if target, _ := cmd.Flags().GetString("url"); target != "" {
+ body["url"] = target
+ }
+
+ result := requireMap(apiclient.DoPost(client, base, token, "/cookies", body), 1, "Failed to set cookie")
+ if set, ok := result["set"].(float64); ok && set < 1 {
+ fmt.Fprintf(os.Stderr, "ERROR: cookies: %q was not set (%v)\n", name, jsonLine(result))
+ os.Exit(2)
+ }
+ printCookiesResult(cmd, result)
+}
+
// CookiesClear clears all browser cookies.
func CookiesClear(client *http.Client, base, token string, cmd *cobra.Command) {
result := apiclient.DoDelete(client, base, token, "/cookies", nil)
@@ -17,12 +72,21 @@ func CookiesClear(client *http.Client, base, token string, cmd *cobra.Command) {
fmt.Fprintln(os.Stderr, "ERROR: cookies: clear failed")
os.Exit(2)
}
+ printCookiesResult(cmd, result)
+}
+
+func printCookiesResult(cmd *cobra.Command, result map[string]any) {
+ if jsonOut, _ := cmd.Flags().GetBool("json"); jsonOut {
+ printIndented(result)
+ return
+ }
+ fmt.Println("OK")
+}
- jsonOut, _ := cmd.Flags().GetBool("json")
- if jsonOut {
- out, _ := json.MarshalIndent(result, "", " ")
- fmt.Println(string(out))
- } else {
- fmt.Println("OK")
+func jsonLine(v any) string {
+ out, err := json.Marshal(v)
+ if err != nil {
+ return fmt.Sprintf("%v", v)
}
+ return string(out)
}
diff --git a/internal/cli/actions/actions_cookies_test.go b/internal/cli/actions/actions_cookies_test.go
new file mode 100644
index 00000000..d277b98c
--- /dev/null
+++ b/internal/cli/actions/actions_cookies_test.go
@@ -0,0 +1,152 @@
+package actions
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func newCookiesTestCmd(args ...string) *cobra.Command {
+ cmd := &cobra.Command{Use: "cookies"}
+ cmd.Flags().String("tab", "", "")
+ cmd.Flags().String("name", "", "")
+ cmd.Flags().String("url", "", "")
+ cmd.Flags().String("domain", "", "")
+ cmd.Flags().String("path", "", "")
+ cmd.Flags().String("same-site", "", "")
+ cmd.Flags().Bool("secure", false, "")
+ cmd.Flags().Bool("http-only", false, "")
+ cmd.Flags().Bool("json", false, "")
+ if err := cmd.Flags().Parse(args); err != nil {
+ panic(err)
+ }
+ return cmd
+}
+
+// cookieJarServer is the pair of routes the two verbs drive, sharing one jar so a
+// read observes what the write stored — the round trip is the point, not each call.
+func cookieJarServer(t *testing.T, jar map[string]string) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/cookies" {
+ http.NotFound(w, r)
+ return
+ }
+ switch r.Method {
+ case http.MethodPost:
+ var body struct {
+ Cookies []struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ } `json:"cookies"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode set body: %v", err)
+ return
+ }
+ for _, c := range body.Cookies {
+ jar[c.Name] = c.Value
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"set": len(body.Cookies), "failed": 0, "total": len(body.Cookies)})
+ case http.MethodGet:
+ cookies := make([]map[string]any, 0, len(jar))
+ for name, value := range jar {
+ if filter := r.URL.Query().Get("name"); filter != "" && filter != name {
+ continue
+ }
+ cookies = append(cookies, map[string]any{"name": name, "value": value})
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"cookies": cookies, "count": len(cookies)})
+ default:
+ http.Error(w, "unexpected method", http.StatusMethodNotAllowed)
+ }
+ }))
+}
+
+// The gap this closes was the CLI wiring only a subset of the routes, so the test is
+// a CLI write read back by a CLI read: neither verb can regress to nothing without
+// this failing.
+func TestCookiesSetThenGetRoundTripsThroughTheCLI(t *testing.T) {
+ jar := map[string]string{}
+ srv := cookieJarServer(t, jar)
+ defer srv.Close()
+
+ CookiesSet(http.DefaultClient, srv.URL, "", newCookiesTestCmd("--tab", "tab1"), "session", "abc123")
+ if jar["session"] != "abc123" {
+ t.Fatalf("jar = %v, want the cookie the CLI set", jar)
+ }
+
+ out := captureStdout(t, func() {
+ CookiesGet(http.DefaultClient, srv.URL, "", newCookiesTestCmd("--tab", "tab1", "--name", "session"))
+ })
+ if !strings.Contains(out, "abc123") || !strings.Contains(out, "session") {
+ t.Fatalf("cookies get printed %q, want the value that was just set", out)
+ }
+}
+
+// An empty value blanks a cookie, and the CLI must send it rather than treat it as an
+// omitted argument.
+// The assertion is on the key's PRESENCE in the wire body: a jar that decodes into a
+// struct cannot tell an omitted "value" from an empty one, so it would pass either way.
+func TestCookiesSetSendsAnEmptyValue(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"set": 1, "failed": 0, "total": 1})
+ }))
+ defer srv.Close()
+
+ CookiesSet(http.DefaultClient, srv.URL, "", newCookiesTestCmd(), "session", "")
+
+ cookies, ok := body["cookies"].([]any)
+ if !ok || len(cookies) != 1 {
+ t.Fatalf("body = %+v, want one cookie", body)
+ }
+ cookie, _ := cookies[0].(map[string]any)
+ value, present := cookie["value"]
+ if !present {
+ t.Fatalf("cookie = %+v carries no value key; blanking a cookie is not the same as omitting the value", cookie)
+ }
+ if value != "" {
+ t.Errorf("value = %v, want the empty string the caller passed", value)
+ }
+}
+
+// The set verb forwards only the attributes the caller gave, so an unset flag does not
+// overwrite a server-side default with an empty string.
+func TestCookiesSetForwardsOnlyTheFlagsGiven(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"set": 1, "failed": 0, "total": 1})
+ }))
+ defer srv.Close()
+
+ cmd := newCookiesTestCmd("--domain", "example.com", "--secure", "--tab", "tab1")
+ CookiesSet(http.DefaultClient, srv.URL, "", cmd, "session", "abc")
+
+ cookies, ok := body["cookies"].([]any)
+ if !ok || len(cookies) != 1 {
+ t.Fatalf("body = %+v, want one cookie", body)
+ }
+ cookie, _ := cookies[0].(map[string]any)
+ if cookie["domain"] != "example.com" || cookie["secure"] != true {
+ t.Errorf("cookie = %+v, want the domain and secure flag forwarded", cookie)
+ }
+ for _, absent := range []string{"path", "sameSite", "httpOnly"} {
+ if _, present := cookie[absent]; present {
+ t.Errorf("cookie carries %q the caller never set: %+v", absent, cookie)
+ }
+ }
+ if _, present := body["url"]; present {
+ t.Errorf("body pins a url the caller never gave (%v); the server defaults it to the tab's page", body["url"])
+ }
+}
diff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.go
index 029fda01..7e2567e8 100644
--- a/internal/handlers/actions_test.go
+++ b/internal/handlers/actions_test.go
@@ -373,7 +373,9 @@ func TestHandleSetCookies_EmptyURL(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
- if resp["error"] != "url is required" {
+ // The mock tab reports no current URL, so there is nothing to default to and the
+ // refusal says which of the two it is.
+ if !strings.HasPrefix(resp["error"], "url is required") {
t.Errorf("expected url required error, got %v", resp["error"])
}
}
diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.go
index c9abe2ff..2fd92dc7 100644
--- a/internal/handlers/cookies.go
+++ b/internal/handlers/cookies.go
@@ -142,7 +142,11 @@ func (h *Handlers) HandleClearCookies(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, http.StatusOK, map[string]any{"status": "cleared"})
}
-// HandleTabClearCookies clears all browser cookies (tab-scoped variant for API consistency).
+// HandleTabClearCookies clears EVERY cookie in the browser, for every origin. The
+// tab id addresses the route and is verified to exist; it does not scope the wipe,
+// and no cookie belonging only to this tab's origin can be cleared on its own. The
+// tab-scoped spelling exists for API consistency with the GET and POST variants,
+// which are genuinely per-tab.
//
// @Endpoint DELETE /tabs/{id}/cookies
func (h *Handlers) HandleTabClearCookies(w http.ResponseWriter, r *http.Request) {
@@ -176,16 +180,23 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
return
}
- if req.URL == "" {
- httpx.Error(w, 400, fmt.Errorf("url is required"))
- return
- }
-
if len(req.Cookies) == 0 {
httpx.Error(w, 400, fmt.Errorf("cookies array is empty"))
return
}
+ // A cookie with no name cannot be set at all, and skipping it silently is how
+ // this endpoint used to report a no-op: an empty value is now honoured, since
+ // blanking a cookie without deleting it is a legitimate operation and CDP
+ // accepts it, so the only unsettable cookie is a nameless one. Refusing here
+ // keeps every counted cookie one the browser was actually asked to store.
+ for i, cookie := range req.Cookies {
+ if cookie.Name == "" {
+ httpx.Error(w, 400, fmt.Errorf("cookies[%d] has no name; a cookie without a name cannot be set", i))
+ return
+ }
+ }
+
ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
WriteTabContextError(w, err, 404)
@@ -195,19 +206,26 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
return
}
- if !h.enforceURLDomainPolicy(w, req.URL) {
+ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer tCancel()
+
+ // The tab's current URL is the default target, the same way HandleGetCookies
+ // reads it: a caller driving one tab already said which page it means, and
+ // making it restate the URL is what kept session injection off the CLI.
+ if req.URL == "" {
+ req.URL, _ = h.Bridge.CurrentURL(tCtx)
+ }
+ if req.URL == "" {
+ httpx.Error(w, 400, fmt.Errorf("url is required: the tab has no current URL to default to"))
return
}
- tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)
- defer tCancel()
+ if !h.enforceURLDomainPolicy(w, req.URL) {
+ return
+ }
successCount := 0
for _, cookie := range req.Cookies {
- if cookie.Name == "" || cookie.Value == "" {
- continue
- }
-
if err := h.Bridge.SetCookie(tCtx, bridge.SetCookieParams{
Name: cookie.Name,
Value: cookie.Value,
diff --git a/internal/handlers/cookies_test.go b/internal/handlers/cookies_test.go
index 12382da1..fdda2b92 100644
--- a/internal/handlers/cookies_test.go
+++ b/internal/handlers/cookies_test.go
@@ -4,10 +4,13 @@ import (
"bytes"
"context"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -282,3 +285,99 @@ func TestHandleClearCookies_RouteRegistration(t *testing.T) {
t.Fatalf("expected DELETE /tabs/{id}/cookies to be registered, got %d: %s", w.Code, w.Body.String())
}
}
+
+// cookieJarBridge records what reached the browser and gives the tab a current URL,
+// which is what the set path defaults to.
+type cookieJarBridge struct {
+ mockBridge
+ currentURL string
+ setErr error
+ set []bridge.SetCookieParams
+}
+
+func (b *cookieJarBridge) CurrentURL(context.Context) (string, error) { return b.currentURL, nil }
+
+func (b *cookieJarBridge) SetCookie(_ context.Context, params bridge.SetCookieParams) error {
+ if b.setErr != nil {
+ return b.setErr
+ }
+ b.set = append(b.set, params)
+ return nil
+}
+
+func postCookies(t *testing.T, b *cookieJarBridge, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ h := New(b, &config.RuntimeConfig{AllowCookies: true}, nil, nil, nil)
+ w := httptest.NewRecorder()
+ h.HandleSetCookies(w, httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(body))))
+ return w
+}
+
+// An empty value blanks a cookie without deleting it, which is a real operation. It
+// used to be skipped by the loop, so the browser was never asked and the caller was
+// told nothing useful.
+func TestHandleSetCookiesHonoursAnEmptyValueAndDefaultsTheURLToTheTab(t *testing.T) {
+ b := &cookieJarBridge{currentURL: "http://example.com/app"}
+ w := postCookies(t, b, `{"cookies":[{"name":"blank","value":""}]}`)
+
+ if w.Code != 200 {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp["set"] != float64(1) || resp["failed"] != float64(0) {
+ t.Errorf("response = %+v, want set 1 failed 0 — a cookie the browser stored must count as set", resp)
+ }
+ if len(b.set) != 1 {
+ t.Fatalf("browser saw %d cookies, want the one with the empty value", len(b.set))
+ }
+ if b.set[0].Value != "" {
+ t.Errorf("value = %q, want it kept empty", b.set[0].Value)
+ }
+ if b.set[0].URL != "http://example.com/app" {
+ t.Errorf("url = %q, want the tab's current URL; a caller driving one tab must not have to restate it", b.set[0].URL)
+ }
+}
+
+// A nameless cookie cannot be set at all, so it is refused rather than skipped: a
+// skipped cookie is the silent no-op this endpoint used to answer with.
+func TestHandleSetCookiesRefusesANamelessCookieInsteadOfSkippingIt(t *testing.T) {
+ b := &cookieJarBridge{currentURL: "http://example.com/app"}
+ w := postCookies(t, b, `{"cookies":[{"name":"","value":"x"}]}`)
+
+ if w.Code != 400 {
+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())
+ }
+ if len(b.set) != 0 {
+ t.Errorf("browser was asked to store %+v; a nameless cookie cannot be set", b.set)
+ }
+}
+
+func TestHandleSetCookiesCountsARejectedCookieAsFailed(t *testing.T) {
+ b := &cookieJarBridge{currentURL: "http://example.com/app", setErr: fmt.Errorf("cdp refused")}
+ w := postCookies(t, b, `{"cookies":[{"name":"a","value":"b"}]}`)
+
+ var resp map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp["set"] != float64(0) || resp["failed"] != float64(1) {
+ t.Errorf("response = %+v, want set 0 failed 1", resp)
+ }
+}
+
+// The default has to come from somewhere: with no current URL the request is refused,
+// rather than sending CDP a cookie with no target.
+func TestHandleSetCookiesRefusesWhenTheTabHasNoURLToDefaultTo(t *testing.T) {
+ b := &cookieJarBridge{}
+ w := postCookies(t, b, `{"cookies":[{"name":"a","value":"b"}]}`)
+
+ if w.Code != 400 || !strings.Contains(w.Body.String(), "url is required") {
+ t.Fatalf("status = %d body = %s, want a 400 naming the missing url", w.Code, w.Body.String())
+ }
+ if len(b.set) != 0 {
+ t.Errorf("browser was asked to store %+v with no URL", b.set)
+ }
+}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 588a77b6..ef46d205 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -56,6 +56,7 @@ func rawHandlerMap(c *Client) map[string]func(context.Context, mcp.CallToolReque
"pinchtab_close_tab": handleCloseTab(c),
"pinchtab_health": handleHealth(c),
"pinchtab_cookies": handleCookies(c),
+ "pinchtab_cookies_set": handleCookiesSet(c),
"pinchtab_connect_profile": handleConnectProfile(c),
"pinchtab_wait": handleWait(),
diff --git a/internal/mcp/handlers_tabs.go b/internal/mcp/handlers_tabs.go
index b36f6b0b..c31263ab 100644
--- a/internal/mcp/handlers_tabs.go
+++ b/internal/mcp/handlers_tabs.go
@@ -57,6 +57,55 @@ func handleCookies(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.C
}
}
+// handleCookiesSet posts one cookie. Every argument the tool declares is read here,
+// and every argument read here is declared: an undeclared argument is invisible to a
+// model and bypasses the schema-derived validator.
+func handleCookiesSet(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ name, err := r.RequireString("name")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ value, err := r.RequireString("value")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+
+ cookie := map[string]any{"name": name, "value": value}
+ for arg, key := range map[string]string{
+ "domain": "domain",
+ "path": "path",
+ "sameSite": "sameSite",
+ } {
+ if v := optString(r, arg); v != "" {
+ cookie[key] = v
+ }
+ }
+ for _, arg := range []string{"secure", "httpOnly"} {
+ if v, ok := optBool(r, arg); ok {
+ cookie[arg] = v
+ }
+ }
+ if expires, ok := optFloat(r, "expires"); ok {
+ cookie["expires"] = expires
+ }
+
+ body := map[string]any{"cookies": []any{cookie}}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ body["tabId"] = tabID
+ }
+ if target := optString(r, "url"); target != "" {
+ body["url"] = target
+ }
+
+ respBody, code, err := c.Post(ctx, "/cookies", body)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(respBody, code)
+ }
+}
+
func handleConnectProfile(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
profile, err := r.RequireString("profile")
diff --git a/internal/mcp/handlers_tabs_test.go b/internal/mcp/handlers_tabs_test.go
index 7c870aac..16e609c9 100644
--- a/internal/mcp/handlers_tabs_test.go
+++ b/internal/mcp/handlers_tabs_test.go
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "slices"
"strings"
"testing"
@@ -208,3 +209,109 @@ func TestHandleContextCancellation(t *testing.T) {
t.Error("expected error result when context is cancelled")
}
}
+
+// The set tool exists because the MCP surface was read-only while the CLI was
+// delete-only, and every argument it declares must actually travel: an argument the
+// schema advertises but the handler drops is worse than an absent one.
+func TestHandleCookiesSetForwardsEveryDeclaredArgument(t *testing.T) {
+ var seen struct {
+ path string
+ body map[string]any
+ }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen.path = r.URL.Path
+ if err := json.NewDecoder(r.Body).Decode(&seen.body); err != nil {
+ t.Errorf("decode: %v", err)
+ }
+ _, _ = w.Write([]byte(`{"set":1,"failed":0,"total":1}`))
+ }))
+ defer srv.Close()
+
+ callTool(t, "pinchtab_cookies_set", map[string]any{
+ "name": "session",
+ "value": "abc123",
+ "url": "https://example.com/app",
+ "domain": "example.com",
+ "path": "/",
+ "sameSite": "Lax",
+ "secure": true,
+ "httpOnly": true,
+ "expires": float64(1893456000),
+ "tabId": "t1",
+ }, srv)
+
+ if seen.path != "/cookies" {
+ t.Fatalf("path = %q, want /cookies", seen.path)
+ }
+ if seen.body["tabId"] != "t1" || seen.body["url"] != "https://example.com/app" {
+ t.Errorf("body = %+v, want the tab and url forwarded", seen.body)
+ }
+ cookies, ok := seen.body["cookies"].([]any)
+ if !ok || len(cookies) != 1 {
+ t.Fatalf("body = %+v, want one cookie", seen.body)
+ }
+ cookie, _ := cookies[0].(map[string]any)
+ for key, want := range map[string]any{
+ "name": "session",
+ "value": "abc123",
+ "domain": "example.com",
+ "path": "/",
+ "sameSite": "Lax",
+ "secure": true,
+ "httpOnly": true,
+ "expires": float64(1893456000),
+ } {
+ if cookie[key] != want {
+ t.Errorf("cookie[%q] = %v, want %v — declared in the tool schema but not forwarded", key, cookie[key], want)
+ }
+ }
+}
+
+// Every argument the handler reads is declared, so the schema-derived validator sees
+// it and a model can discover it.
+func TestCookiesSetToolDeclaresEveryArgumentItReads(t *testing.T) {
+ var tool *mcp.Tool
+ for i, candidate := range allTools() {
+ if candidate.Name == "pinchtab_cookies_set" {
+ tool = &allTools()[i]
+ }
+ }
+ if tool == nil {
+ t.Fatal("pinchtab_cookies_set is not in allTools(), so tools/list never advertises it")
+ }
+ if _, ok := rawHandlerMap(NewClient("http://example.invalid", ""))["pinchtab_cookies_set"]; !ok {
+ t.Fatal("pinchtab_cookies_set has no handler, so NewServer panics on it")
+ }
+
+ for _, arg := range []string{"name", "value", "url", "domain", "path", "sameSite", "secure", "httpOnly", "expires", "tabId"} {
+ if _, ok := tool.InputSchema.Properties[arg]; !ok {
+ t.Errorf("the handler reads %q but the schema does not declare it", arg)
+ }
+ }
+ for _, required := range []string{"name", "value"} {
+ if !slices.Contains(tool.InputSchema.Required, required) {
+ t.Errorf("%q is not required, so a call omitting it reaches the server as an empty cookie", required)
+ }
+ }
+}
+
+// An empty value blanks a cookie; RequireString accepts it, so the tool must not treat
+// it as a missing argument.
+func TestHandleCookiesSetAcceptsAnEmptyValue(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ _, _ = w.Write([]byte(`{"set":1,"failed":0,"total":1}`))
+ }))
+ defer srv.Close()
+
+ callTool(t, "pinchtab_cookies_set", map[string]any{"name": "session", "value": ""}, srv)
+
+ cookies, ok := body["cookies"].([]any)
+ if !ok || len(cookies) != 1 {
+ t.Fatalf("body = %+v, want the cookie to reach the server", body)
+ }
+ if cookie, _ := cookies[0].(map[string]any); cookie["value"] != "" {
+ t.Errorf("cookie = %+v, want an empty value preserved", cookie)
+ }
+}
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index 0d659823..b44566e6 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) != 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))
+ if len(tools) != 47 {
+ t.Errorf("expected 47 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.go
index bf525f62..c91570d4 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -269,6 +269,19 @@ func allTools() []mcp.Tool {
mcp.WithDescription("Get cookies for the current page"),
mcp.WithString("tabId", mcp.Description("Target tab ID")),
),
+ mcp.NewTool("pinchtab_cookies_set",
+ mcp.WithDescription("Set one cookie on the current page, for reusing an authenticated session. An empty value blanks the cookie without deleting it."),
+ mcp.WithString("name", mcp.Required(), mcp.Description("Cookie name")),
+ mcp.WithString("value", mcp.Required(), mcp.Description("Cookie value; an empty string blanks the cookie")),
+ mcp.WithString("url", mcp.Description("Target URL (default: the tab's current page)")),
+ mcp.WithString("domain", mcp.Description("Cookie domain")),
+ mcp.WithString("path", mcp.Description("Cookie path")),
+ mcp.WithString("sameSite", mcp.Description("SameSite attribute: Strict, Lax or None")),
+ mcp.WithBoolean("secure", mcp.Description("Mark the cookie Secure")),
+ mcp.WithBoolean("httpOnly", mcp.Description("Mark the cookie HttpOnly")),
+ mcp.WithNumber("expires", mcp.Description("Expiry as a Unix timestamp in seconds; omit for a session cookie")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
mcp.NewTool("pinchtab_connect_profile",
mcp.WithDescription("Get the user-facing connect URL and instance status for a profile"),
mcp.WithString("profile", mcp.Required(), mcp.Description("Profile name or profile ID")),
diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.md
index 1dd095f0..eea67053 100644
--- a/skills/pinchtab/references/mcp.md
+++ b/skills/pinchtab/references/mcp.md
@@ -91,6 +91,7 @@ All tool names are prefixed with `pinchtab_`.
| `pinchtab_close_tab` | Close a tab. Optional: `tabId` (uses current/default tab when omitted). |
| `pinchtab_health` | Check server health. No params. |
| `pinchtab_cookies` | Get cookies for current page. Optional: `tabId`. Requires `security.allowCookies: true`; values are session credentials and must not be logged or shared. |
+| `pinchtab_cookies_set` | Set one cookie on the current page (session reuse). Required: `name`, `value`. Optional: `url` (defaults to the tab's current page), `domain`, `path`, `sameSite`, `secure`, `httpOnly`, `expires`, `tabId`. An empty `value` blanks the cookie. Requires `security.allowCookies: true`. |
| `pinchtab_connect_profile` | Return connect status for a profile. Required: `profile`. |
### Utility