High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: use spawnSync for mcp subcommand to avoid event loop stdio interference (#387)
luigiagent06cea93265d4
diff --git a/.github/workflows/ci-docker-smoke.yml b/.github/workflows/ci-docker-smoke.ymlnew file mode 100644index 00000000..4674504e--- /dev/null+++ b/.github/workflows/ci-docker-smoke.yml@@ -0,0 +1,13 @@+name: CI / Docker Smoke++on:+ workflow_dispatch:++permissions:+ contents: read++jobs:+ docker-smoke:+ uses: ./.github/workflows/reusable-docker-smoke.yml+ with:+ ref: ${{ github.sha }}diff --git a/.github/workflows/reusable-docker-smoke.yml b/.github/workflows/reusable-docker-smoke.ymlindex a58c7d8b..73c76972 100644--- a/.github/workflows/reusable-docker-smoke.yml+++ b/.github/workflows/reusable-docker-smoke.yml@@ -28,3 +28,6 @@ jobs:- name: Verify bootstrap path in containerrun: bash scripts/docker-smoke.sh pinchtab-release-smoke:${{ github.run_id }}++ - name: Verify MCP stdio in container+ run: bash scripts/docker-mcp-smoke.sh pinchtab-release-smoke:${{ github.run_id }}diff --git a/.gitignore b/.gitignoreindex 81157de8..6c10d26f 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,10 @@+!dashboard/eslint.config.js+!dashboard/vite.config.ts+!internal/assets/*.js+!npm/bin/pinchtab+!scripts/**/*.js+!tests/e2e/fixtures/stealth-service-worker.js+!tests/e2e/results/.gitkeep# Build artifacts and test output# E2E test results# Go code serves a built-in fallback when these files are absent.@@ -7,13 +14,6 @@# npm package# package-lock.json is committed for reproducible installs via npm ci*.js-!tests/e2e/fixtures/stealth-service-worker.js-!dashboard/eslint.config.js-!dashboard/vite.config.ts-!internal/assets/*.js-!npm/bin/pinchtab-!scripts/**/*.js-!tests/e2e/results/.gitkeep*.pyc*.test.DS_Storediff --git a/npm/bin/pinchtab b/npm/bin/pinchtabindex e367fcd3..94faa749 100755--- a/npm/bin/pinchtab+++ b/npm/bin/pinchtab@@ -1,7 +1,7 @@#!/usr/bin/env nodeconst path = require('path');-const { spawn } = require('child_process');+const { spawn, spawnSync } = require('child_process');const os = require('os');const fs = require('fs');@@ -111,7 +111,41 @@ if (!fs.existsSync(binaryPath)) {process.exit(1);}-const proc = spawn(binaryPath, process.argv.slice(2), {+// MCP stdio JSON-RPC needs the Go binary to own stdin/stdout directly.+// The normal spawn() path plus parent signal handlers can interfere with+// process lifecycle in ways that break some MCP clients (e.g. Claude Code).+// Use spawnSync for the mcp subcommand so Node blocks without an event+// loop or signal handlers sitting between the client and the Go process.+// Note: Node still exists as the parent PID — this is not a true exec —+// but removing the async event loop and signal forwarding is sufficient+// for the known failure modes.+function firstSubcommand(argv) {+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ if (arg === '--server') { i += 1; continue; }+ if (arg.startsWith('--server=')) continue;+ if (!arg.startsWith('-')) return arg;+ }+ return null;+}++if (firstSubcommand(args) === 'mcp') {+ const result = spawnSync(binaryPath, args, {+ stdio: 'inherit',+ shell: false,+ });++ if (result.error) {+ console.error(`Failed to run Pinchtab: ${result.error.message}`);+ process.exit(1);+ }+ if (result.signal) {+ process.kill(process.pid, result.signal);+ }+ process.exit(result.status ?? 0);+}++const proc = spawn(binaryPath, args, {stdio: 'inherit',shell: false,});diff --git a/npm/tests/mcp-wrapper.test.ts b/npm/tests/mcp-wrapper.test.tsnew file mode 100644index 00000000..42d9bd93--- /dev/null+++ b/npm/tests/mcp-wrapper.test.ts@@ -0,0 +1,137 @@+/**+ * MCP Wrapper Tests+ *+ * Verifies that the Node.js wrapper correctly detects the mcp subcommand+ * and that the spawnSync path produces valid JSON-RPC responses.+ */++import { test, describe } from 'node:test';+import * as assert from 'node:assert';+import { spawnSync } from 'node:child_process';+import * as path from 'node:path';+import * as fs from 'node:fs';++/**+ * Extracted firstSubcommand logic from bin/pinchtab for isolated testing.+ */+function firstSubcommand(argv: string[]): string | null {+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ if (arg === '--server') {+ i += 1;+ continue;+ }+ if (arg.startsWith('--server=')) continue;+ if (!arg.startsWith('-')) return arg;+ }+ return null;+}++describe('firstSubcommand', () => {+ test('simple mcp', () => {+ assert.strictEqual(firstSubcommand(['mcp']), 'mcp');+ });++ test('mcp with flags before', () => {+ assert.strictEqual(firstSubcommand(['--server', 'http://localhost:9867', 'mcp']), 'mcp');+ });++ test('mcp with --server= syntax', () => {+ assert.strictEqual(firstSubcommand(['--server=http://localhost:9867', 'mcp']), 'mcp');+ });++ test('non-mcp subcommand', () => {+ assert.strictEqual(firstSubcommand(['nav', 'https://example.com']), 'nav');+ });++ test('only flags returns null', () => {+ assert.strictEqual(firstSubcommand(['--server', 'http://localhost:9867']), null);+ });++ test('empty args returns null', () => {+ assert.strictEqual(firstSubcommand([]), null);+ });+});++describe('MCP wrapper integration', () => {+ function findBinary(): string | null {+ // Prefer explicit override (CI or local dev with `go build -o`)+ if (process.env.PINCHTAB_BINARY_PATH) {+ return process.env.PINCHTAB_BINARY_PATH;+ }+ // Dev build in repo root (go build -o pinchtab-dev ./cmd/pinchtab)+ const devBinary = path.join(__dirname, '..', '..', 'pinchtab-dev');+ if (fs.existsSync(devBinary)) return devBinary;+ return null;+ }++ const binaryPath = findBinary();+ // __dirname is dist/tests/ after tsc, wrapper lives at bin/ (sibling to dist/)+ const wrapperPath = path.join(__dirname, '..', '..', 'bin', 'pinchtab');++ test('wrapper responds to JSON-RPC initialize via stdin', { skip: !binaryPath }, () => {+ const initMsg = JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'test', version: '1.0' },+ },+ });++ const result = spawnSync('node', [wrapperPath, 'mcp'], {+ input: initMsg + '\n',+ timeout: 10000,+ env: {+ ...process.env,+ PINCHTAB_TOKEN: 'test',+ PINCHTAB_BINARY_PATH: binaryPath!,+ },+ });++ const stdout = result.stdout?.toString().trim();+ assert.ok(+ stdout,+ `expected JSON-RPC response on stdout, got nothing (stderr: ${result.stderr?.toString()})`+ );++ const response = JSON.parse(stdout.split('\n')[0]);+ assert.strictEqual(response.jsonrpc, '2.0');+ assert.strictEqual(response.id, 1);+ assert.ok(response.result, 'expected result in response');+ assert.strictEqual(response.result.serverInfo.name, 'PinchTab');+ assert.ok(response.result.capabilities.tools !== undefined, 'expected tools capability');+ });++ test('wrapper with --server flag still detects mcp subcommand', { skip: !binaryPath }, () => {+ const initMsg = JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'test', version: '1.0' },+ },+ });++ const result = spawnSync('node', [wrapperPath, '--server', 'http://localhost:9867', 'mcp'], {+ input: initMsg + '\n',+ timeout: 10000,+ env: {+ ...process.env,+ PINCHTAB_TOKEN: 'test',+ PINCHTAB_BINARY_PATH: binaryPath!,+ },+ });++ const stdout = result.stdout?.toString().trim();+ assert.ok(stdout, 'expected JSON-RPC response with --server flag');++ const response = JSON.parse(stdout.split('\n')[0]);+ assert.strictEqual(response.id, 1);+ assert.ok(response.result?.serverInfo, 'expected serverInfo in response');+ });+});diff --git a/scripts/docker-mcp-smoke.sh b/scripts/docker-mcp-smoke.shnew file mode 100755index 00000000..f26c76e4--- /dev/null+++ b/scripts/docker-mcp-smoke.sh@@ -0,0 +1,104 @@+#!/usr/bin/env bash+set -euo pipefail++# Docker MCP Smoke Test+# Verifies that the MCP stdio server works correctly inside a Docker container.+# Tests both the Go binary directly and the npm wrapper (if Node.js is available).++IMAGE="${1:-pinchtab-local:test}"+SMOKE_TOKEN="pinchtab-mcp-smoke-${RANDOM}${RANDOM}"+NAME="pinchtab-mcp-smoke-${RANDOM}${RANDOM}"+FAILED=0++RED='\033[0;31m'+GREEN='\033[0;32m'+BOLD='\033[1m'+NC='\033[0m'++pass() { echo -e " ${GREEN}✓${NC} $1"; }+fail() { echo -e " ${RED}✗${NC} $1"; FAILED=1; }++cleanup() {+ if docker ps -a --format '{{.Names}}' | grep -Fxq "$NAME"; then+ if [ "$FAILED" -ne 0 ]; then+ echo ""+ echo "Container logs:"+ docker logs "$NAME" 2>&1 | tail -20 || true+ fi+ docker rm -f "$NAME" >/dev/null 2>&1 || true+ fi+}+trap cleanup EXIT++echo -e "${BOLD}Docker MCP Smoke Test${NC}"+echo "Image: $IMAGE"+echo ""++# Start container in background (we only need the binary, not the server)+docker run -d --name "$NAME" \+ -e PINCHTAB_TOKEN="$SMOKE_TOKEN" \+ --entrypoint /usr/bin/dumb-init \+ "$IMAGE" -- sleep 300 >/dev/null++echo "Testing MCP stdio via Go binary..."++# Test 1: JSON-RPC initialize via direct Go binary+INIT_MSG='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"docker-smoke","version":"1.0"}}}'++RESPONSE=$(echo "$INIT_MSG" | docker exec -i -e PINCHTAB_TOKEN="$SMOKE_TOKEN" "$NAME" \+ pinchtab mcp 2>/dev/null | head -1)++if echo "$RESPONSE" | grep -q '"serverInfo"'; then+ pass "JSON-RPC initialize returns valid response"+else+ fail "JSON-RPC initialize failed: $RESPONSE"+fi++# Verify server name+if echo "$RESPONSE" | grep -q '"name":"PinchTab"'; then+ pass "Server identifies as PinchTab"+else+ fail "Unexpected server name in: $RESPONSE"+fi++# Test 2: tools/list returns tools+TOOLS_MSG='{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'++TOOLS_RESPONSE=$(printf '%s\n%s\n' "$INIT_MSG" "$TOOLS_MSG" | docker exec -i -e PINCHTAB_TOKEN="$SMOKE_TOKEN" "$NAME" \+ pinchtab mcp 2>/dev/null | tail -1)++if echo "$TOOLS_RESPONSE" | grep -q '"tools"'; then+ TOOL_COUNT=$(echo "$TOOLS_RESPONSE" | python3 -c "import sys,json; print(len(json.load(sys.stdin)['result']['tools']))" 2>/dev/null || echo "0")+ if [ "$TOOL_COUNT" -gt 0 ]; then+ pass "tools/list returns $TOOL_COUNT tools"+ else+ fail "tools/list returned 0 tools"+ fi+else+ fail "tools/list failed: $TOOLS_RESPONSE"+fi++# Test 3: health tool call+HEALTH_MSG='{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"pinchtab_health","arguments":{}}}'++HEALTH_RESPONSE=$(printf '%s\n%s\n' "$INIT_MSG" "$HEALTH_MSG" | docker exec -i -e PINCHTAB_TOKEN="$SMOKE_TOKEN" "$NAME" \+ pinchtab mcp 2>/dev/null | tail -1)++if echo "$HEALTH_RESPONSE" | grep -q '"result"'; then+ pass "pinchtab_health tool call returns result"+else+ # Health may fail if server isn't running — that's OK, just check for valid JSON-RPC+ if echo "$HEALTH_RESPONSE" | grep -q '"jsonrpc"'; then+ pass "pinchtab_health tool call returns valid JSON-RPC (server not running, expected)"+ else+ fail "pinchtab_health tool call failed: $HEALTH_RESPONSE"+ fi+fi++echo ""+if [ "$FAILED" -eq 0 ]; then+ echo -e "${GREEN}${BOLD}Docker MCP smoke test passed.${NC}"+else+ echo -e "${RED}${BOLD}Docker MCP smoke test FAILED.${NC}"+ exit 1+fi