Skip to content

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

feat: server restart, config change hints, recording MCP tools, and timeout fixes

Marioc0fdafc5dc92
diff --git a/cmd/pinchtab/cmd_cli_browser_record.go b/cmd/pinchtab/cmd_cli_browser_record.go
index 60f947a0..7d353ebc 100644
--- a/cmd/pinchtab/cmd_cli_browser_record.go
+++ b/cmd/pinchtab/cmd_cli_browser_record.go
@@ -1,6 +1,9 @@
package main
import (
+ "net/http"
+ "time"
+
browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
"github.com/spf13/cobra"
)
@@ -26,7 +29,12 @@ var recordStopCmd = &cobra.Command{
Short: "Stop recording and save",
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
- browseractions.RecordStop(rt.client, rt.base, rt.token)
+ // Encoding can take minutes; use a dedicated long-timeout client.
+ longClient := &http.Client{
+ Timeout: 3 * time.Minute,
+ Transport: rt.client.Transport,
+ }
+ browseractions.RecordStop(longClient, rt.base, rt.token)
})
},
}
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
index 1c8b5913..7d9672e4 100644
--- a/cmd/pinchtab/cmd_config.go
+++ b/cmd/pinchtab/cmd_config.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/output"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/config/workflow"
configschema "github.com/pinchtab/pinchtab/internal/schema"
@@ -286,6 +287,7 @@ func handleConfigSet(path, value string) error {
}
fmt.Printf("Set %s = %s\n", path, displayConfigValue(path, value))
+ hintRestartIfRunning()
return nil
}
@@ -329,6 +331,7 @@ func handleConfigPatch(jsonPatch string) error {
}
fmt.Println("Config patched successfully")
+ hintRestartIfRunning()
return nil
}
@@ -350,6 +353,13 @@ func handleConfigValidate() {
fmt.Printf("Config file is valid: %s\n", configPath)
}
+func hintRestartIfRunning() {
+ cfg := loadLocalConfig()
+ if server.CheckPinchTabRunning(cfg.Port, cfg.Token) {
+ output.Hint("Server is running — restart it to apply changes: pinchtab server restart")
+ }
+}
+
func handleConfigSchema(printSchema bool) {
schemaURL := config.CurrentConfigSchemaURL()
if printSchema {
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
index 4fa527bf..c4ae306f 100644
--- a/cmd/pinchtab/cmd_config_test.go
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -2,6 +2,8 @@ package main
import (
"encoding/json"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
@@ -296,6 +298,47 @@ func resetConfigSchemaPrintFlag(t *testing.T) {
}
}
+func TestConfigSetHintsRestartWhenServerRunning(t *testing.T) {
+ // Spin up a fake health endpoint so hintRestartIfRunning detects a running server.
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(`{"status":"ok"}`))
+ }))
+ defer srv.Close()
+
+ port := srv.URL[strings.LastIndex(srv.URL, ":")+1:]
+
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ // Write a minimal valid config pointing at the fake server port.
+ configJSON := []byte(`{"configVersion":"0.8.0","server":{"port":"` + port + `","token":"test-token-for-restart-hint-00000"}}`)
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ t.Fatalf("MkdirAll() error = %v", err)
+ }
+ if err := os.WriteFile(configPath, configJSON, 0o600); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
+ }
+
+ t.Cleanup(func() { rootCmd.SetArgs(nil) })
+
+ stderr := captureStderr(t, func() {
+ _ = captureStdout(t, func() {
+ rootCmd.SetArgs([]string{"config", "set", "security.allowScreencast", "true"})
+ if err := rootCmd.Execute(); err != nil {
+ t.Fatalf("Execute() error = %v", err)
+ }
+ })
+ })
+
+ if !strings.Contains(stderr, "restart") {
+ t.Fatalf("expected restart hint on stderr, got %q", stderr)
+ }
+ if !strings.Contains(stderr, "pinchtab server restart") {
+ t.Fatalf("expected 'pinchtab server restart' in hint, got %q", stderr)
+ }
+}
+
func TestConfigSetMasksServerTokenInOutput(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
t.Setenv("PINCHTAB_CONFIG", configPath)
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
index bd94ec81..1c62c741 100644
--- a/cmd/pinchtab/cmd_server.go
+++ b/cmd/pinchtab/cmd_server.go
@@ -74,5 +74,6 @@ func init() {
serverCmd.Flags().String("background-child", "", "Internal marker for background server ownership")
_ = serverCmd.Flags().MarkHidden("background-child")
serverCmd.AddCommand(serverStopCmd)
+ serverCmd.AddCommand(serverRestartCmd)
rootCmd.AddCommand(serverCmd)
}
diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.go
index 5048fcb3..7e3a71d3 100644
--- a/cmd/pinchtab/cmd_server_background.go
+++ b/cmd/pinchtab/cmd_server_background.go
@@ -15,6 +15,7 @@ import (
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -42,7 +43,7 @@ var readProcessCommand = defaultReadProcessCommand
var serverStopCmd = &cobra.Command{
Use: "stop",
- Short: "Stop a background server started with `pinchtab server --background`",
+ Short: "Stop the running server",
Run: func(cmd *cobra.Command, args []string) {
if err := runServerStop(); err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
@@ -51,6 +52,27 @@ var serverStopCmd = &cobra.Command{
},
}
+var serverRestartCmd = &cobra.Command{
+ Use: "restart",
+ Short: "Restart the running server (stop + start in background)",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := loadConfig()
+
+ if server.CheckPinchTabRunning(cfg.Port, cfg.Token) {
+ fmt.Println("Stopping server...")
+ if err := runServerStop(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, fmt.Sprintf("stop: %v", err)))
+ }
+ }
+
+ fmt.Println("Starting server...")
+ if err := runServerBackground(cfg, serverBackgroundOptions{}); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+ },
+}
+
func runtimeStateDir() string {
return filepath.Dir(config.DefaultConfigPath())
}
@@ -210,15 +232,27 @@ func isPinchTabHealthReady(url, marker string) bool {
return marker == "" || health.Marker == marker
}
+func stopViaAPI() error {
+ cfg := loadConfig()
+ if !server.CheckPinchTabRunning(cfg.Port, cfg.Token) {
+ return fmt.Errorf("no server running on port %s", cfg.Port)
+ }
+ if err := server.ShutdownServer(cfg.Port, cfg.Token); err != nil {
+ return fmt.Errorf("shutdown: %w", err)
+ }
+ fmt.Printf("Stopped server on port %s\n", cfg.Port)
+ return nil
+}
+
func runServerStop() error {
info, ok := readServerPID()
if !ok {
- return fmt.Errorf("no background server PID file at %s", serverPIDFilePath())
+ return stopViaAPI()
}
pid := info.PID
if !processAlive(pid) {
_ = os.Remove(serverPIDFilePath())
- return fmt.Errorf("background server (pid %d) is not running; cleaned up stale pid file", pid)
+ return stopViaAPI()
}
if err := verifyServerPIDInfo(info); err != nil {
return err
diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.go
index 3edd2977..7c46728a 100644
--- a/cmd/pinchtab/cmd_server_background_test.go
+++ b/cmd/pinchtab/cmd_server_background_test.go
@@ -7,6 +7,8 @@ import (
"reflect"
"strings"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/server"
)
func TestIsBackgroundServerReadyRequiresValidPinchTabHealth(t *testing.T) {
@@ -140,6 +142,45 @@ func TestVerifyServerPIDInfoRefusesLegacyPID(t *testing.T) {
}
}
+func TestStopViaAPIShutdownEndpoint(t *testing.T) {
+ shutdownCalled := false
+ healthAlive := true
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/health":
+ if healthAlive {
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(`{"status":"ok","mode":"dashboard","version":"dev"}`))
+ } else {
+ w.WriteHeader(503)
+ }
+ case "/shutdown":
+ if r.Method != http.MethodPost {
+ w.WriteHeader(405)
+ return
+ }
+ shutdownCalled = true
+ healthAlive = false
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(`{"status":"shutting down"}`))
+ default:
+ w.WriteHeader(404)
+ }
+ }))
+ defer srv.Close()
+
+ // Extract port from test server URL.
+ port := strings.TrimPrefix(srv.URL, "http://127.0.0.1:")
+
+ err := server.ShutdownServer(port, "")
+ if err != nil {
+ t.Fatalf("ShutdownServer() error = %v", err)
+ }
+ if !shutdownCalled {
+ t.Fatal("POST /shutdown was not called")
+ }
+}
+
func TestVerifyServerPIDInfoChecksProcessCommand(t *testing.T) {
orig := readProcessCommand
readProcessCommand = func(pid int) (string, error) {
diff --git a/docs/commands.md b/docs/commands.md
index 6cbfb266..f24c6280 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -4,6 +4,8 @@
```bash
pinchtab server # Start the full server (dashboard + API)
+pinchtab server stop # Stop the running server (foreground or background)
+pinchtab server restart # Stop + restart in background (applies config changes)
pinchtab bridge # Start the bridge-only runtime
pinchtab mcp # Start the MCP stdio server
pinchtab daemon # Show daemon status
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 218e6bf0..7adafdb3 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -92,6 +92,8 @@ pinchtab network # GET 200 https://...
| Command | Purpose |
| --- | --- |
| `pinchtab server` | Start the full server and dashboard |
+| `pinchtab server stop` | Stop the running server (foreground or background) |
+| `pinchtab server restart` | Stop + restart in background (applies config changes) |
| `pinchtab bridge` | Start the single-instance bridge runtime |
| `pinchtab mcp` | Start the stdio MCP server |
| `pinchtab daemon` | Show daemon status and manage the background service |
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index 7dca6e6f..8518ad55 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -1,6 +1,6 @@
# MCP Tool Reference
-PinchTab currently exposes 38 MCP tools. All tool names are prefixed with `pinchtab_` and are served over stdio JSON-RPC.
+PinchTab currently exposes 41 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>`).
@@ -93,6 +93,14 @@ All element-action tools accept the unified `selector` and the legacy aliases `r
| `pinchtab_network_route` | `tabId` required, `pattern` required, `action`, `body`, `contentType`, `status`, `resourceType`, `method` | Install a request-interception rule on a tab. `action` is `continue` (default), `abort`, or `fulfill`. `fulfill` is blocked on hosts in `security.allowedDomains` and falls through to a real fetch on those hosts |
| `pinchtab_network_unroute` | `tabId` required, `pattern` | Remove a tab's interception rule by pattern, or all rules when `pattern` is omitted |
+## Recording
+
+| Tool | Key Parameters | Notes |
+| --- | --- | --- |
+| `pinchtab_record_start` | `file` required, `fps`, `quality`, `scale`, `tabId` | Start recording; format inferred from extension (`.gif`, `.webm`, `.mp4`). Requires `security.allowScreencast`. GIF works without ffmpeg |
+| `pinchtab_record_stop` | `file` required | Stop recording, encode, and save to `file`. Encoding may take a while for long recordings |
+| `pinchtab_record_status` | — | Returns active recording status (format, fps, duration, frame count) |
+
## Dialog
| Tool | Key Parameters | Notes |
diff --git a/docs/reference/record.md b/docs/reference/record.md
index 3a1cc8b1..47ea4a74 100644
--- a/docs/reference/record.md
+++ b/docs/reference/record.md
@@ -58,11 +58,21 @@ curl -X POST http://localhost:9867/record/stop > recording.gif
- `--scale <f>`: Resolution scale (default 1.0).
- `--tab <id>`: Target a specific tab.
+## Format Dependencies
+
+| Format | Dependency | Encoding | Notes |
+| --- | --- | --- | --- |
+| `.gif` | None | Pure Go (Floyd-Steinberg dithering) | Always available; CPU-intensive for long recordings |
+| `.webm` | `ffmpeg` | VP8 via ffmpeg pipe | Requires ffmpeg on `$PATH` |
+| `.mp4` | `ffmpeg` | H.264 via ffmpeg pipe | Requires ffmpeg on `$PATH` |
+
+GIF encoding runs entirely in-process — no external binary needed. Dithering is CPU-bound; recordings over ~2 minutes at 10 fps can take 30-60 seconds to encode. Frames are capped at 600 (max ~2 minutes at 5 fps) and downscaled if they exceed 1280x720 pixels to limit memory usage.
+
+WebM and MP4 stream frames to ffmpeg during `record stop`. If ffmpeg is not installed, `record start` returns a 400 error with a message indicating the dependency. Install ffmpeg via your package manager (`brew install ffmpeg`, `apt install ffmpeg`, etc.) or use `.gif` as a zero-dependency alternative.
+
## Notes
-- Gated by `security.allowScreencast`.
-- `.webm` and `.mp4` require `ffmpeg` installed on the server.
-- `.gif` always available (pure Go encoding).
+- Gated by `security.allowScreencast` (disabled by default). Enable with `pinchtab config set security.allowScreencast true` and restart the server.
- One active recording per bridge instance.
## Related Pages
diff --git a/internal/handlers/record.go b/internal/handlers/record.go
index f317c3b5..b5cf7a41 100644
--- a/internal/handlers/record.go
+++ b/internal/handlers/record.go
@@ -440,7 +440,11 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
httpx.ErrorCode(w, 403, "recording_disabled",
httpx.DisabledEndpointMessage("recording", "security.allowScreencast"), false,
- map[string]any{"setting": "security.allowScreencast"})
+ map[string]any{
+ "setting": "security.allowScreencast",
+ "hint": "Recording requires screen capture to be enabled.",
+ "remedy": "pinchtab config set security.allowScreencast true",
+ })
return
}
@@ -522,6 +526,10 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {
// HandleRecordStop stops the active recording and returns the encoded file.
func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
+ // Encoding can exceed the default WriteTimeout; extend the deadline.
+ rc := http.NewResponseController(w)
+ _ = rc.SetWriteDeadline(time.Now().Add(encodeTimeout + 30*time.Second))
+
owner := authenticatedOwner(r)
data, format, err := h.recorder.stop(owner)
if err != nil {
diff --git a/internal/httpx/endpointlock.go b/internal/httpx/endpointlock.go
index 1d639f54..08519662 100644
--- a/internal/httpx/endpointlock.go
+++ b/internal/httpx/endpointlock.go
@@ -15,6 +15,8 @@ func DisabledEndpointHandler(feature, setting, code string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
ErrorCode(w, http.StatusForbidden, code, DisabledEndpointMessage(feature, setting), false, map[string]any{
"setting": setting,
+ "hint": fmt.Sprintf("Enable %s to use this feature.", setting),
+ "remedy": fmt.Sprintf("pinchtab config set %s true", setting),
})
}
}
diff --git a/internal/httpx/endpointlock_test.go b/internal/httpx/endpointlock_test.go
new file mode 100644
index 00000000..a846376d
--- /dev/null
+++ b/internal/httpx/endpointlock_test.go
@@ -0,0 +1,46 @@
+package httpx
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestDisabledEndpointHandlerIncludesHintAndRemedy(t *testing.T) {
+ handler := DisabledEndpointHandler("recording", "security.allowScreencast", "recording_disabled")
+
+ w := httptest.NewRecorder()
+ r, _ := http.NewRequest("POST", "/record/start", nil)
+ handler(w, r)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
+ }
+
+ var resp struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ Details map[string]any `json:"details"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+
+ if resp.Code != "recording_disabled" {
+ t.Fatalf("code = %q, want recording_disabled", resp.Code)
+ }
+
+ hint, _ := resp.Details["hint"].(string)
+ remedy, _ := resp.Details["remedy"].(string)
+
+ if hint == "" {
+ t.Fatal("expected non-empty hint in details")
+ }
+ if remedy == "" {
+ t.Fatal("expected non-empty remedy in details")
+ }
+ if remedy != "pinchtab config set security.allowScreencast true" {
+ t.Fatalf("remedy = %q, want config set command", remedy)
+ }
+}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index dbabdd4e..a90c2538 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -63,6 +63,11 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)
"pinchtab_network_route": handleNetworkRoute(c),
"pinchtab_network_unroute": handleNetworkUnroute(c),
+ // Recording
+ "pinchtab_record_start": handleRecordStart(c),
+ "pinchtab_record_stop": handleRecordStop(c),
+ "pinchtab_record_status": handleRecordStatus(c),
+
// Dialog
"pinchtab_dialog": handleDialog(c),
}
diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.go
new file mode 100644
index 00000000..decf069e
--- /dev/null
+++ b/internal/mcp/handlers_record.go
@@ -0,0 +1,89 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ file, err := r.RequireString("file")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+
+ ext := filepath.Ext(file)
+ var format string
+ switch ext {
+ case ".gif":
+ format = "gif"
+ case ".webm":
+ format = "webm"
+ case ".mp4":
+ format = "mp4"
+ default:
+ return mcp.NewToolResultError(fmt.Sprintf("unsupported format %q — use .gif, .webm, or .mp4", ext)), nil
+ }
+
+ payload := map[string]any{"format": format}
+ if fps, ok := optInt(r, "fps"); ok {
+ payload["fps"] = fps
+ }
+ if quality, ok := optInt(r, "quality"); ok {
+ payload["quality"] = quality
+ }
+ if scale, ok := optFloat(r, "scale"); ok {
+ payload["scale"] = scale
+ }
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+
+ body, code, err := c.Post(ctx, "/record/start", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ file := optString(r, "file")
+ if file == "" {
+ return mcp.NewToolResultError("file parameter is required"), nil
+ }
+
+ body, code, err := c.Post(ctx, "/record/stop", map[string]any{})
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ if code >= 400 {
+ return resultFromBytes(body, code)
+ }
+
+ if err := os.WriteFile(file, body, 0600); err != nil {
+ return mcp.NewToolResultError(fmt.Sprintf("write file: %v", err)), nil
+ }
+
+ return jsonResult(map[string]any{
+ "status": "saved",
+ "file": file,
+ "bytes": len(body),
+ })
+ }
+}
+
+func handleRecordStatus(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ body, code, err := c.Get(ctx, "/record/status", nil)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index d7ed5fa2..0702bc5a 100644
--- a/internal/mcp/server_test.go
+++ b/internal/mcp/server_test.go
@@ -18,8 +18,8 @@ func TestNewServerRegistersAllTools(t *testing.T) {
// The server should have registered all tools.
// We verify by checking that NewServer doesn't panic — the panic
// in NewServer fires if any tool lacks a handler.
- if len(tools) != 38 {
- t.Errorf("expected 38 tools, got %d", len(tools))
+ if len(tools) != 41 {
+ t.Errorf("expected 41 tools, got %d", len(tools))
}
}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 243266e2..83eec314 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -268,6 +268,23 @@ func allTools() []mcp.Tool {
mcp.WithString("pattern", mcp.Description("Pattern to remove (omit to clear all rules)")),
),
+ // ── Recording ───────────────────────────────────────────────
+ mcp.NewTool("pinchtab_record_start",
+ mcp.WithDescription("Start recording browser activity. Requires security.allowScreencast. GIF works without ffmpeg; WebM/MP4 need ffmpeg."),
+ mcp.WithString("file", mcp.Required(), mcp.Description("Output file path (.gif, .webm, or .mp4)")),
+ mcp.WithNumber("fps", mcp.Description("Frames per second 1-30 (default: 5)")),
+ mcp.WithNumber("quality", mcp.Description("JPEG capture quality 1-100 (default: 80)")),
+ mcp.WithNumber("scale", mcp.Description("Resolution scale 0-1.0 (default: 1.0)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_record_stop",
+ mcp.WithDescription("Stop recording and save the encoded file. Encoding may take a while for long recordings."),
+ mcp.WithString("file", mcp.Required(), mcp.Description("Output file path (must match the format from record_start)")),
+ ),
+ mcp.NewTool("pinchtab_record_status",
+ mcp.WithDescription("Check active recording status (format, fps, duration, frame count)"),
+ ),
+
// ── Dialog ──────────────────────────────────────────────────
mcp.NewTool("pinchtab_dialog",
mcp.WithDescription("Handle a JavaScript dialog (alert, confirm, prompt). Accept or dismiss the currently open dialog."),
diff --git a/internal/server/helpers.go b/internal/server/helpers.go
index a2094d5d..ce427c97 100644
--- a/internal/server/helpers.go
+++ b/internal/server/helpers.go
@@ -61,6 +61,36 @@ func RegisterDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
}
}
+// ShutdownServer sends POST /shutdown to a running server and waits for it to exit.
+func ShutdownServer(port, token string) error {
+ client := &http.Client{Timeout: 5 * time.Second}
+ url := fmt.Sprintf("http://127.0.0.1:%s/shutdown", port)
+ req, err := http.NewRequest("POST", url, nil)
+ if err != nil {
+ return fmt.Errorf("build request: %w", err)
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("shutdown request: %w", err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != 200 {
+ return fmt.Errorf("shutdown returned HTTP %d", resp.StatusCode)
+ }
+
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ time.Sleep(300 * time.Millisecond)
+ if !CheckPinchTabRunning(port, token) {
+ return nil
+ }
+ }
+ return fmt.Errorf("server did not exit within 10s")
+}
+
func MetricFloat(value any) float64 {
switch v := value.(type) {
case float64:
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index 8c53baec..4df9dbca 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -102,15 +102,20 @@ pinchtab security # review security posture
Key settings agents may need to change:
- `security.allowEvaluate`: enable `eval` command (`true`/`false`)
+- `security.allowScreencast`: enable `record` commands (`true`/`false`)
- `security.allowedDomains`: list of allowed hostnames (e.g. `["localhost", "127.0.0.1"]`)
- `instanceDefaults.headless`: run Chrome headless (`true`) or headed (`false`)
+After changing config with the server running, restart to apply: `pinchtab server restart`.
+
## Essential Commands
### Server and targeting
```bash
pinchtab server | daemon install | health
+pinchtab server stop # stop any running server (foreground or background)
+pinchtab server restart # stop + restart in background (applies config changes)
pinchtab instances | profiles
pinchtab --server http://localhost:9868 snap -i -c # target a specific instance
```
@@ -209,8 +214,8 @@ Timeout 10s default, 30s max via `--timeout <ms>`. Prefer `--not-text`/`--state
```bash
pinchtab screenshot [-o path.png] [-q <jpeg-quality>] # format by extension
pinchtab pdf [-o path.pdf] [--landscape]
-pinchtab record start out.gif [--fps 5] [--scale 1.0] # .gif/.webm/.mp4; requires security.allowScreencast
-pinchtab record stop # stop and save to path given at start
+pinchtab record start out.gif [--fps 5] [--scale 1.0] # .gif/.webm/.mp4; requires security.allowScreencast; .gif works without ffmpeg, .webm/.mp4 need ffmpeg
+pinchtab record stop # stop, encode, and save to path given at start
pinchtab record status # check active recording
```