Shell
#!/usr/bin/env node
/**
* Playwright Coordinator MCP Server
*
* Provides coordination tools for multi-agent Playwright access.
* Works with PreToolUse hooks to auto-reserve contexts.
*/
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import * as fs from 'fs/promises';
import * as path from 'path';
// Path to coordinator state
const COORDINATOR_DIR = path.join(__dirname, '..', '..');
const STATE_FILE = path.join(COORDINATOR_DIR, 'state.json');
const LOCK_FILE = path.join(COORDINATOR_DIR, 'state.lock');
const LOG_FILE = path.join(COORDINATOR_DIR, 'events.log');
// Types (inline to avoid import issues)
interface BrowserContext {
id: string;
status: 'available' | 'reserved' | 'shared';
agentId: string | null;
reservedAt: string | null;
purpose: string | null;
lastActivity: string | null;
}
interface CoordinatorState {
version: number;
updatedAt: string;
config: {
maxContexts: number;
reservationTimeoutMs: number;
};
contexts: Record<string, BrowserContext>;
sharedSessions: Record<string, unknown>;
waitingAgents: Array<{
agentId: string;
requestedAt: string;
purpose: string;
}>;
}
// ============================================
// File Locking
// ============================================
async function acquireLock(): Promise<boolean> {
const maxRetries = 50;
let retries = 0;
while (retries < maxRetries) {
try {
await fs.writeFile(LOCK_FILE, JSON.stringify({
pid: process.pid,
timestamp: new Date().toISOString(),
}), { flag: 'wx' });
return true;
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
try {
const lockData = await fs.readFile(LOCK_FILE, 'utf-8');
const lock = JSON.parse(lockData);
const lockAge = Date.now() - new Date(lock.timestamp).getTime();
if (lockAge > 30000) {
await fs.unlink(LOCK_FILE);
continue;
}
} catch {
try { await fs.unlink(LOCK_FILE); } catch { /* ignore */ }
}
await new Promise(r => setTimeout(r, 100 + Math.random() * 50));
retries++;
} else {
throw err;
}
}
}
return false;
}
async function releaseLock(): Promise<void> {
try { await fs.unlink(LOCK_FILE); } catch { /* ignore */ }
}
// ============================================
// State Management
// ============================================
async function loadState(): Promise<CoordinatorState> {
try {
const data = await fs.readFile(STATE_FILE, 'utf-8');
return JSON.parse(data);
} catch {
// Return default state if file doesn't exist
const defaultState: CoordinatorState = {
version: 1,
updatedAt: new Date().toISOString(),
config: { maxContexts: 6, reservationTimeoutMs: 300000 },
contexts: {},
sharedSessions: {},
waitingAgents: [],
};
for (let i = 1; i <= 6; i++) {
defaultState.contexts[`context_${i}`] = {
id: `context_${i}`,
status: 'available',
agentId: null,
reservedAt: null,
purpose: null,
lastActivity: null,
};
}
return defaultState;
}
}
async function saveState(state: CoordinatorState): Promise<void> {
state.updatedAt = new Date().toISOString();
state.version++;
await fs.writeFile(STATE_FILE, JSON.stringify(state, null, 2));
}
async function logEvent(event: unknown): Promise<void> {
const entry = { timestamp: new Date().toISOString(), event };
await fs.appendFile(LOG_FILE, JSON.stringify(entry) + '\n');
}
// ============================================
// Coordination Functions
// ============================================
async function reserveContext(agentId: string, purpose: string) {
const locked = await acquireLock();
if (!locked) return { success: false, error: 'Could not acquire lock' };
try {
const state = await loadState();
// Check if agent already has context
const existing = Object.values(state.contexts).find(
c => c.agentId === agentId && c.status !== 'available'
);
if (existing) {
existing.lastActivity = new Date().toISOString();
await saveState(state);
return { success: true, contextId: existing.id, alreadyHeld: true };
}
// Find available
const available = Object.values(state.contexts).find(c => c.status === 'available');
if (!available) {
// Queue
if (!state.waitingAgents.some(w => w.agentId === agentId)) {
state.waitingAgents.push({ agentId, requestedAt: new Date().toISOString(), purpose });
await saveState(state);
}
const pos = state.waitingAgents.findIndex(w => w.agentId === agentId) + 1;
return { success: false, error: 'No contexts available', waitPosition: pos };
}
// Reserve
available.status = 'reserved';
available.agentId = agentId;
available.reservedAt = new Date().toISOString();
available.purpose = purpose;
available.lastActivity = new Date().toISOString();
state.waitingAgents = state.waitingAgents.filter(w => w.agentId !== agentId);
await saveState(state);
await logEvent({ type: 'reserved', agentId, contextId: available.id, purpose });
return { success: true, contextId: available.id };
} finally {
await releaseLock();
}
}
async function releaseContext(agentId: string) {
const locked = await acquireLock();
if (!locked) return { success: false, error: 'Could not acquire lock' };
try {
const state = await loadState();
const context = Object.values(state.contexts).find(c => c.agentId === agentId);
if (!context) {
return { success: false, error: 'No context found for agent' };
}
const contextId = context.id;
context.status = 'available';
context.agentId = null;
context.reservedAt = null;
context.purpose = null;
context.lastActivity = null;
await saveState(state);
await logEvent({ type: 'released', agentId, contextId });
return { success: true, contextId };
} finally {
await releaseLock();
}
}
async function heartbeat(agentId: string) {
const locked = await acquireLock();
if (!locked) return false;
try {
const state = await loadState();
const context = Object.values(state.contexts).find(c => c.agentId === agentId);
if (context) {
context.lastActivity = new Date().toISOString();
await saveState(state);
return true;
}
return false;
} finally {
await releaseLock();
}
}
async function getPoolStatus() {
const state = await loadState();
const contexts = Object.values(state.contexts);
return {
available: contexts.filter(c => c.status === 'available').length,
reserved: contexts.filter(c => c.status === 'reserved').length,
shared: contexts.filter(c => c.status === 'shared').length,
waiting: state.waitingAgents.length,
contexts: contexts.map(c => ({
id: c.id,
status: c.status,
agentId: c.agentId,
purpose: c.purpose,
lastActivity: c.lastActivity,
})),
waitingAgents: state.waitingAgents,
};
}
async function forceCleanup(agentId: string) {
const locked = await acquireLock();
if (!locked) return { released: 0 };
try {
const state = await loadState();
let released = 0;
for (const context of Object.values(state.contexts)) {
if (context.agentId === agentId) {
context.status = 'available';
context.agentId = null;
context.reservedAt = null;
context.purpose = null;
context.lastActivity = null;
released++;
}
}
state.waitingAgents = state.waitingAgents.filter(w => w.agentId !== agentId);
await saveState(state);
return { released };
} finally {
await releaseLock();
}
}
// ============================================
// MCP Server
// ============================================
const server = new Server(
{
name: 'playwright-coordinator',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'playwright_reserve',
description: 'Reserve a browser context for Playwright use. Call this before using any Playwright tools.',
inputSchema: {
type: 'object',
properties: {
agent_id: {
type: 'string',
description: 'Unique identifier for this agent/session',
},
purpose: {
type: 'string',
description: 'Brief description of what you will use Playwright for',
},
},
required: ['agent_id', 'purpose'],
},
},
{
name: 'playwright_release',
description: 'Release your browser context back to the pool. Call this when done with Playwright.',
inputSchema: {
type: 'object',
properties: {
agent_id: {
type: 'string',
description: 'Your agent/session identifier',
},
},
required: ['agent_id'],
},
},
{
name: 'playwright_heartbeat',
description: 'Send a heartbeat to indicate you are still using Playwright. Call during long operations.',
inputSchema: {
type: 'object',
properties: {
agent_id: {
type: 'string',
description: 'Your agent/session identifier',
},
},
required: ['agent_id'],
},
},
{
name: 'playwright_pool_status',
description: 'Check the current status of the Playwright browser pool.',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'playwright_force_cleanup',
description: 'Force release all contexts held by an agent (emergency cleanup).',
inputSchema: {
type: 'object',
properties: {
agent_id: {
type: 'string',
description: 'Agent ID to clean up',
},
},
required: ['agent_id'],
},
},
],
};
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case 'playwright_reserve': {
const { agent_id, purpose } = args as { agent_id: string; purpose: string };
const result = await reserveContext(agent_id, purpose);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'playwright_release': {
const { agent_id } = args as { agent_id: string };
const result = await releaseContext(agent_id);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'playwright_heartbeat': {
const { agent_id } = args as { agent_id: string };
const success = await heartbeat(agent_id);
return {
content: [{ type: 'text', text: success ? 'Heartbeat OK' : 'No context found' }],
};
}
case 'playwright_pool_status': {
const status = await getPoolStatus();
const lines = [
'=== Playwright Pool Status ===',
`Available: ${status.available}`,
`Reserved: ${status.reserved}`,
`Shared: ${status.shared}`,
`Waiting: ${status.waiting}`,
'',
'--- Contexts ---',
...status.contexts.map(c => {
const icon = c.status === 'available' ? '🟢' : c.status === 'reserved' ? '🟡' : '🔵';
return `${icon} ${c.id}: ${c.status}${c.agentId ? ` (${c.agentId})` : ''}${c.purpose ? ` - ${c.purpose}` : ''}`;
}),
];
if (status.waitingAgents.length > 0) {
lines.push('', '--- Waiting ---');
status.waitingAgents.forEach((w, i) => {
lines.push(`${i + 1}. ${w.agentId} - ${w.purpose}`);
});
}
return {
content: [{ type: 'text', text: lines.join('\n') }],
};
}
case 'playwright_force_cleanup': {
const { agent_id } = args as { agent_id: string };
const result = await forceCleanup(agent_id);
return {
content: [{ type: 'text', text: `Released ${result.released} context(s)` }],
};
}
default:
return {
content: [{ type: 'text', text: `Unknown tool: ${name}` }],
isError: true,
};
}
} catch (error) {
return {
content: [{ type: 'text', text: `Error: ${error instanceof Error ? error.message : error}` }],
isError: true,
};
}
});
// Start server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('Playwright Coordinator MCP server running');
}
main().catch(console.error);