feat: add playwright

This commit is contained in:
2026-09-12 18:56:00 +02:00
parent a6cb0beade
commit dfe9926c7c
4 changed files with 313 additions and 1 deletions
+6
View File
@@ -67,6 +67,12 @@ This relative path assumes the configuration file is in the selected global conf
The plugin supplies session-local `todoread` and `todowrite` tools when no other plugin provides them. In OpenCode V2 2.0.2, custom tools cannot open permission prompts: an `ask` or `deny` rule blocks these todo tools rather than bypassing the rule. Explicitly allow them if you want to use them.
The plugin also adds an MCP server named `playwright` unless one with that exact name is already configured; existing configurations are preserved, including disabled servers. It first looks from the current project directory through its ancestors for an executable declared as `playwright-mcp` by an installed `@playwright/mcp` package, then checks `PATH` for an executable whose resolved package is genuinely `@playwright/mcp`. This direct MCP installation is preferred and is launched without a package runner.
If the MCP package is absent but an installed `playwright` package, an `@playwright/test` package with its `playwright` dependency available, or a genuine `playwright` package CLI on `PATH` is found, the plugin configures `npx -y @playwright/mcp@latest`. The ordinary CLI is only evidence that Playwright is local; it is never run as an MCP server. Detection performs no network access and launches nothing, but the first MCP connection requires `npx`, registry access to download/update `@playwright/mcp@latest`, Node.js supported by that package, and browser binaries and system dependencies.
Only when neither Playwright MCP nor ordinary Playwright is verified locally does OpenCode start the official Microsoft image over stdio with `docker run -i --rm --init --pull=always mcr.microsoft.com/playwright/mcp`. Setup does not start the container. The fallback requires Docker when OpenCode first connects, may pull the image then, and currently supports only headless Chromium. If `npx`, Docker, registry access, or other runtime prerequisites for the selected path are unavailable, the Playwright MCP connection fails without preventing the rest of the plugin from loading. Configure your own server named `playwright` (it may be disabled) to override automatic selection.
When an MCP server named `codegraph` is already configured, its tools are exposed directly to `coordinate` and retain the built-in `build` agent's matching allow, ask, and deny rules. The plugin does not configure or start a missing server, and no other MCP server is exposed this way.
## ChatGPT subscription quota
+4
View File
@@ -7,6 +7,7 @@ import { discover } from "./provider.js";
import { descriptions, routingGuide } from "./routing.js";
import { QuotaTracker } from "./quota.js";
import { QuotaRpc } from "./quota-rpc.js";
import { playwrightMcpCommand } from "./playwright.js";
// Permission actions use wildcards, not filesystem globs.
function matches(value: string, pattern: string) {
@@ -113,8 +114,11 @@ export default Plugin.define({
const assignments = selected.mode === "gpt" ? gptAgents : selected.agents;
let workers: (typeof workerNames)[number][] = [];
const active = new Set<string>();
const playwrightCommand = await playwrightMcpCommand(context.location.directory);
await context.mcp.transform((editor) => {
if (!editor.get("playwright"))
editor.set("playwright", { type: "local", command: playwrightCommand });
hasCodegraph = editor.get("codegraph") !== undefined;
if (hasCodegraph)
editor.update("codegraph", (server) => {
+145
View File
@@ -0,0 +1,145 @@
import { access, readFile, realpath } from "node:fs/promises";
import { constants } from "node:fs";
import { dirname, join, parse, resolve } from "node:path";
import { z } from "zod";
const dockerCommand = [
"docker",
"run",
"-i",
"--rm",
"--init",
"--pull=always",
"mcr.microsoft.com/playwright/mcp",
];
const directPackageManifest = z.object({
name: z.literal("@playwright/mcp"),
bin: z.string(),
});
const namedPackageManifest = z.object({
name: z.literal("@playwright/mcp"),
bin: z.object({ "playwright-mcp": z.string() }),
});
const playwrightPackageManifest = z.object({
name: z.literal("playwright"),
bin: z.object({ playwright: z.string() }),
});
const playwrightTestPackageManifest = z.object({
name: z.literal("@playwright/test"),
bin: z.object({ playwright: z.string() }),
dependencies: z.object({ playwright: z.string() }),
});
async function packageExecutable(packageRoot: string) {
try {
const input = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
const direct = directPackageManifest.safeParse(input);
const bin = direct.success
? direct.data.bin
: namedPackageManifest.parse(input).bin["playwright-mcp"];
const executable = resolve(packageRoot, bin);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function ordinaryPackageExecutable(packageRoot: string) {
try {
const manifest = playwrightPackageManifest.parse(
JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")),
);
const executable = resolve(packageRoot, manifest.bin.playwright);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function playwrightDependency(packageRoot: string) {
let current = await realpath(packageRoot);
const root = parse(current).root;
while (true) {
const executable = await ordinaryPackageExecutable(
join(current, "node_modules/playwright"),
);
if (executable) return executable;
if (current === root) return;
current = dirname(current);
}
}
async function testPackageExecutable(packageRoot: string) {
try {
const manifest = playwrightTestPackageManifest.parse(
JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")),
);
if (!(await playwrightDependency(packageRoot))) return;
const executable = resolve(packageRoot, manifest.bin.playwright);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function verifiedPathExecutable(candidate: string, kind: "mcp" | "playwright") {
try {
await access(candidate, constants.X_OK);
const target = await realpath(candidate);
let directory = dirname(target);
const root = parse(directory).root;
while (true) {
const executable =
kind === "mcp"
? await packageExecutable(directory)
: ((await ordinaryPackageExecutable(directory)) ??
(await testPackageExecutable(directory)));
if (executable && (await realpath(executable)) === target) return candidate;
if (directory === root) return;
directory = dirname(directory);
}
} catch {
return;
}
}
export async function playwrightMcpCommand(
directory: string,
path = process.env.PATH ?? "",
): Promise<string[]> {
let current = resolve(directory);
const root = parse(current).root;
while (true) {
const executable = await packageExecutable(join(current, "node_modules/@playwright/mcp"));
if (executable) return [executable];
if (current === root) break;
current = dirname(current);
}
for (const entry of path.split(process.platform === "win32" ? ";" : ":")) {
if (!entry) continue;
const executable = await verifiedPathExecutable(join(entry, "playwright-mcp"), "mcp");
if (executable) return [executable];
}
current = resolve(directory);
while (true) {
const playwright = await ordinaryPackageExecutable(
join(current, "node_modules/playwright"),
);
const test = await testPackageExecutable(join(current, "node_modules/@playwright/test"));
if (playwright || test) return ["npx", "-y", "@playwright/mcp@latest"];
if (current === root) break;
current = dirname(current);
}
for (const entry of path.split(process.platform === "win32" ? ";" : ":")) {
if (!entry) continue;
const executable = await verifiedPathExecutable(join(entry, "playwright"), "playwright");
if (executable) return ["npx", "-y", "@playwright/mcp@latest"];
}
return [...dockerCommand];
}
+158 -1
View File
@@ -1,4 +1,6 @@
import { afterEach, expect, test } from "bun:test";
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Agent, Model, Plugin, Provider } from "@opencode/plugin";
import type { AgentEditor } from "@opencode/plugin/promise/agent";
import type { DeepMutable } from "@opencode/plugin/promise/types";
@@ -8,6 +10,7 @@ import type { SessionContext } from "@opencode/plugin/promise/session";
import { z } from "zod";
import { gptAgents } from "../src/config.js";
import plugin from "../src/index.js";
import { playwrightMcpCommand } from "../src/playwright.js";
const providerID = Provider.ID.make("test");
function model(id: string): ModelInfo {
@@ -32,6 +35,7 @@ async function host(
{ type: "local"; command: string[]; codemode?: boolean; disabled?: boolean }
> = {},
configuredMcpTools: string[] = [],
directory = "/test",
) {
const agents = new Map<string, DeepMutable<Agent.Info>>();
const build: DeepMutable<Agent.Info> = Agent.Info.default(Agent.ID.make("build"));
@@ -64,11 +68,15 @@ async function host(
const mcpServers = new Map(Object.entries(structuredClone(configuredMcp)));
let mcpTransform!: (editor: {
get(name: string): (typeof configuredMcp)[string] | undefined;
set(name: string, server: (typeof configuredMcp)[string]): void;
update(name: string, update: (server: (typeof configuredMcp)[string]) => void): void;
}) => void;
const toolTransforms: ((editor: ToolEditor) => void)[] = [];
const editMcp = () => ({
get: (name: string) => mcpServers.get(name),
set(name: string, server: (typeof configuredMcp)[string]) {
mcpServers.set(name, structuredClone(server));
},
update(name: string, update: (server: (typeof configuredMcp)[string]) => void) {
const server = mcpServers.get(name);
if (server) update(server);
@@ -107,7 +115,7 @@ async function host(
// SAFETY: This test host implements the native APIs used by setup; unrelated context
// services are deliberately absent so unexpected new dependencies fail the test.
const context = {
location: { directory: "/test" },
location: { directory },
options,
catalog: {
model: {
@@ -408,6 +416,155 @@ test("coordinator inherits only codegraph MCP permissions when that server exist
});
});
test("playwright MCP prefers direct MCP, uses npx for Playwright, and preserves fallback behavior", async () => {
const originalPath = process.env.PATH;
process.env.PATH = "";
const root = await mkdtemp("/tmp/opencode/stanp-playwright-");
try {
const packageRoot = join(root, "local", "node_modules", "@playwright", "mcp");
const executable = join(packageRoot, "cli.js");
const localProject = join(root, "local", "project");
const globalProject = join(root, "global-project");
await mkdir(localProject, { recursive: true });
await mkdir(globalProject);
await mkdir(packageRoot, { recursive: true });
await writeFile(
join(packageRoot, "package.json"),
JSON.stringify({ name: "@playwright/mcp", bin: { "playwright-mcp": "cli.js" } }),
);
await writeFile(executable, "#!/usr/bin/env node\n");
await chmod(executable, 0o755);
const local = await host(allModels, { provider: "test" }, {}, [], localProject);
expect(local.mcpServers.get("playwright")).toEqual({
type: "local",
command: [executable],
});
const globalPackage = join(root, "global", "@playwright", "mcp");
const globalExecutable = join(globalPackage, "cli.js");
const globalBin = join(root, "bin");
const pathExecutable = join(globalBin, "playwright-mcp");
await mkdir(globalPackage, { recursive: true });
await mkdir(globalBin, { recursive: true });
await writeFile(
join(globalPackage, "package.json"),
JSON.stringify({ name: "@playwright/mcp", bin: { "playwright-mcp": "cli.js" } }),
);
await writeFile(globalExecutable, "#!/usr/bin/env node\n");
await chmod(globalExecutable, 0o755);
await symlink(globalExecutable, pathExecutable);
expect(await playwrightMcpCommand(globalProject, globalBin)).toEqual([pathExecutable]);
const ordinaryPackage = join(root, "ordinary-project", "node_modules", "playwright");
const ordinaryProject = join(root, "ordinary-project", "project");
const ordinaryExecutable = join(ordinaryPackage, "cli.js");
await mkdir(ordinaryPackage, { recursive: true });
await mkdir(ordinaryProject);
await writeFile(
join(ordinaryPackage, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(ordinaryExecutable, "#!/usr/bin/env node\n");
await chmod(ordinaryExecutable, 0o755);
const ordinary = await host(allModels, { provider: "test" }, {}, [], ordinaryProject);
expect(ordinary.mcpServers.get("playwright")?.command).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const testPackage = join(root, "test-project", "node_modules", "@playwright", "test");
const testDependency = join(testPackage, "node_modules", "playwright");
const testProject = join(root, "test-project", "project");
await mkdir(testDependency, { recursive: true });
await mkdir(testProject);
await writeFile(
join(testPackage, "package.json"),
JSON.stringify({
name: "@playwright/test",
bin: { playwright: "cli.js" },
dependencies: { playwright: "1.0.0" },
}),
);
await writeFile(join(testPackage, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(testPackage, "cli.js"), 0o755);
await writeFile(
join(testDependency, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(join(testDependency, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(testDependency, "cli.js"), 0o755);
expect(await playwrightMcpCommand(testProject, "")).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const pathPackage = join(root, "path-playwright", "playwright");
const pathBin = join(root, "playwright-bin");
const pathPlaywright = join(pathBin, "playwright");
await mkdir(pathPackage, { recursive: true });
await mkdir(pathBin);
await writeFile(
join(pathPackage, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(join(pathPackage, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(pathPackage, "cli.js"), 0o755);
await symlink(join(pathPackage, "cli.js"), pathPlaywright);
expect(await playwrightMcpCommand(globalProject, pathBin)).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const ordinaryBin = join(root, "ordinary-bin");
const fakePlaywright = join(ordinaryBin, "playwright");
await mkdir(ordinaryBin);
await writeFile(fakePlaywright, "#!/usr/bin/env node\n");
await chmod(fakePlaywright, 0o755);
expect((await playwrightMcpCommand(globalProject, ordinaryBin))[0]).toBe("docker");
const fallback = await host();
expect(fallback.mcpServers.get("playwright")).toEqual({
type: "local",
command: [
"docker",
"run",
"-i",
"--rm",
"--init",
"--pull=always",
"mcr.microsoft.com/playwright/mcp",
],
});
const existing = await host(
allModels,
{ provider: "test" },
{
playwright: {
type: "local",
command: ["custom-playwright-mcp"],
disabled: true,
},
docs: { type: "local", command: ["docs"], codemode: true },
},
);
expect(existing.mcpServers.get("playwright")).toEqual({
type: "local",
command: ["custom-playwright-mcp"],
disabled: true,
});
expect(existing.mcpServers.get("docs")?.codemode).toBe(true);
} finally {
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
await rm(root, { recursive: true, force: true });
}
});
test("manual calls and command-created child sessions cannot bypass delegation restrictions", async () => {
const result = await host(allModels.slice(0, 2));
for (const invoke of [result.delegate, result.command]) {