High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: auto-start server when mcp detects no running instance (#389)
luigiagenta339822f52d6
diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.goindex 88738b51..b6bfb148 100644--- a/cmd/pinchtab/cmd_mcp.go+++ b/cmd/pinchtab/cmd_mcp.go@@ -2,7 +2,11 @@ package mainimport ("fmt"+ "log/slog"+ "net/http""os"+ "os/exec"+ "time""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/mcp"@@ -26,10 +30,22 @@ func init() {func runMCP(cfg *config.RuntimeConfig) {baseURL := resolveCLIBase(cfg)-- // Token from config, env var overridestoken := resolveCLIToken(cfg)+ if !isServerHealthy(baseURL, token) {+ slog.Info("server not running, starting automatically", "url", baseURL)+ if err := autoStartServer(); err != nil {+ slog.Error("failed to auto-start server", "err", err)+ fmt.Fprintf(os.Stderr, "mcp: server at %s is not running and auto-start failed: %v\n", baseURL, err)+ os.Exit(1)+ }+ if !waitForServer(baseURL, token, 30*time.Second) {+ fmt.Fprintf(os.Stderr, "mcp: server did not become healthy at %s within 30s\n", baseURL)+ os.Exit(1)+ }+ slog.Info("server started successfully")+ }+mcp.Version = versionif err := mcp.Serve(baseURL, token); err != nil {@@ -37,3 +53,63 @@ func runMCP(cfg *config.RuntimeConfig) {os.Exit(1)}}++func isServerHealthy(baseURL, token string) bool {+ client := &http.Client{Timeout: 3 * time.Second}+ req, err := http.NewRequest(http.MethodGet, baseURL+"/health", nil)+ if err != nil {+ return false+ }+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ resp, err := client.Do(req)+ if err != nil {+ return false+ }+ defer func() { _ = resp.Body.Close() }()+ return resp.StatusCode < 500+}++func autoStartServer() error {+ binary, err := os.Executable()+ if err != nil {+ return fmt.Errorf("resolve executable: %w", err)+ }++ // Build args: forward --server flag if set, plus "server" subcommand+ args := []string{"server"}+ if serverURL != "" {+ args = []string{"--server", serverURL, "server"}+ }++ cmd := exec.Command(binary, args...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommands+ cmd.Stdin = nil+ cmd.Stdout = nil+ cmd.Stderr = nil+ // Detach from parent process group so the server survives if the+ // MCP process exits.+ detachProcess(cmd)++ if err := cmd.Start(); err != nil {+ return fmt.Errorf("spawn server: %w", err)+ }++ // Release the child so it's not reaped when we exit.+ if err := cmd.Process.Release(); err != nil {+ slog.Warn("failed to release server process", "err", err)+ }++ return nil+}++func waitForServer(baseURL, token string, timeout time.Duration) bool {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if isServerHealthy(baseURL, token) {+ return true+ }+ time.Sleep(500 * time.Millisecond)+ }+ return false+}diff --git a/cmd/pinchtab/cmd_mcp_test.go b/cmd/pinchtab/cmd_mcp_test.gonew file mode 100644index 00000000..bb0ff8b1--- /dev/null+++ b/cmd/pinchtab/cmd_mcp_test.go@@ -0,0 +1,67 @@+package main++import (+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestIsServerHealthy_ReturnsTrue(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ if !isServerHealthy(ts.URL, "") {+ t.Fatal("expected healthy server to return true")+ }+}++func TestIsServerHealthy_ReturnsFalseForError(t *testing.T) {+ if isServerHealthy("http://127.0.0.1:1", "") {+ t.Fatal("expected unreachable server to return false")+ }+}++func TestIsServerHealthy_ReturnsFalseFor500(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer ts.Close()++ if isServerHealthy(ts.URL, "") {+ t.Fatal("expected 500 to return false")+ }+}++func TestIsServerHealthy_SendsAuthHeader(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer test-token" {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ if !isServerHealthy(ts.URL, "test-token") {+ t.Fatal("expected healthy server with correct token to return true")+ }+ // 401 still means the server is running — isServerHealthy checks+ // reachability, not auth correctness.+ if !isServerHealthy(ts.URL, "wrong-token") {+ t.Fatal("expected running server with wrong token to still return true (401 < 500)")+ }+}++func TestWaitForServer_ImmediatelyHealthy(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ if !waitForServer(ts.URL, "", 5*time.Second) {+ t.Fatal("expected immediately healthy server to return true")+ }+}diff --git a/cmd/pinchtab/cmd_mcp_unix.go b/cmd/pinchtab/cmd_mcp_unix.gonew file mode 100644index 00000000..5a56cbf7--- /dev/null+++ b/cmd/pinchtab/cmd_mcp_unix.go@@ -0,0 +1,14 @@+//go:build !windows++package main++import (+ "os/exec"+ "syscall"+)++func detachProcess(cmd *exec.Cmd) {+ cmd.SysProcAttr = &syscall.SysProcAttr{+ Setsid: true,+ }+}diff --git a/cmd/pinchtab/cmd_mcp_windows.go b/cmd/pinchtab/cmd_mcp_windows.gonew file mode 100644index 00000000..733ce277--- /dev/null+++ b/cmd/pinchtab/cmd_mcp_windows.go@@ -0,0 +1,14 @@+//go:build windows++package main++import (+ "os/exec"+ "syscall"+)++func detachProcess(cmd *exec.Cmd) {+ cmd.SysProcAttr = &syscall.SysProcAttr{+ CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP,+ }+}diff --git a/scripts/docker-mcp-smoke.sh b/scripts/docker-mcp-smoke.shindex f26c76e4..d556cdeb 100755--- a/scripts/docker-mcp-smoke.sh+++ b/scripts/docker-mcp-smoke.sh@@ -95,6 +95,76 @@ elsefifi+# --- Part 2: Auto-start + navigation test ---+# Uses a fresh container where the server is NOT pre-started.+# The MCP command should auto-launch the server and handle tool calls.++echo ""+echo "Testing MCP auto-start + navigation..."++NAME2="pinchtab-mcp-autostart-${RANDOM}${RANDOM}"+cleanup2() {+ if docker ps -a --format '{{.Names}}' | grep -Fxq "$NAME2"; then+ if [ "$FAILED" -ne 0 ]; then+ echo ""+ echo "Auto-start container logs:"+ docker logs "$NAME2" 2>&1 | tail -30 || true+ fi+ docker rm -f "$NAME2" >/dev/null 2>&1 || true+ fi+}+trap 'cleanup; cleanup2' EXIT++# Start container with sleep (no server running)+docker run -d --name "$NAME2" \+ -e PINCHTAB_TOKEN="$SMOKE_TOKEN" \+ --entrypoint /usr/bin/dumb-init \+ "$IMAGE" -- sleep 300 >/dev/null++# Ensure config exists so the server can start+docker exec "$NAME2" pinchtab config init >/dev/null 2>&1 || true+docker exec "$NAME2" pinchtab config set server.token "$SMOKE_TOKEN" >/dev/null 2>&1 || true++# Test 4: MCP auto-starts the server when not running+# Send initialize + a navigate tool call through mcp.+# The mcp command should detect no server, spawn one, wait for health,+# then process the tool calls.+NAV_MSG='{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"pinchtab_navigate","arguments":{"url":"data:text/html,<h1>MCP-AutoStart-Test</h1>"}}}'++AUTOSTART_RESPONSE=$(printf '%s\n%s\n' "$INIT_MSG" "$NAV_MSG" | docker exec -i \+ -e PINCHTAB_TOKEN="$SMOKE_TOKEN" \+ "$NAME2" pinchtab mcp 2>/dev/null | tail -1)++if echo "$AUTOSTART_RESPONSE" | grep -q '"jsonrpc"'; then+ if echo "$AUTOSTART_RESPONSE" | grep -q '"result"'; then+ pass "MCP auto-started server and navigate tool call succeeded"+ elif echo "$AUTOSTART_RESPONSE" | grep -q '"error"'; then+ # An error response is still valid JSON-RPC — server started but tool may have failed+ pass "MCP auto-started server (tool returned error, but server is running)"+ else+ fail "MCP auto-start: unexpected response: $AUTOSTART_RESPONSE"+ fi+else+ fail "MCP auto-start failed: no JSON-RPC response: $AUTOSTART_RESPONSE"+fi++# Test 5: Verify the server is actually running after auto-start+HEALTH_CHECK=$(docker exec -e PINCHTAB_TOKEN="$SMOKE_TOKEN" "$NAME2" \+ pinchtab health 2>&1 || true)++if echo "$HEALTH_CHECK" | grep -qi "ok\|healthy\|running\|version"; then+ pass "Server is running after MCP auto-start"+else+ # health command may have different output format, check if server responds+ HEALTH_HTTP=$(docker exec "$NAME2" sh -c \+ "wget -qO- --header='Authorization: Bearer $SMOKE_TOKEN' http://127.0.0.1:9867/health 2>/dev/null" || true)+ if [ -n "$HEALTH_HTTP" ]; then+ pass "Server is running after MCP auto-start (confirmed via HTTP)"+ else+ fail "Server not running after MCP auto-start: $HEALTH_CHECK"+ fi+fi+echo ""if [ "$FAILED" -eq 0 ]; thenecho -e "${GREEN}${BOLD}Docker MCP smoke test passed.${NC}"