Skip to main content
Glama
README.md
# Playwright AI MCP Agent

[![CI](https://github.com/ManikandanK-QA/playwright-ai-mcp-agent/actions/workflows/ci.yml/badge.svg)](https://github.com/ManikandanK-QA/playwright-ai-mcp-agent/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

A guarded QA agent that combines a deterministic Playwright suite with **opt-in** AI planning
and a narrow Model Context Protocol (MCP) tool surface. The default workflow is fully offline:
no API key, paid provider or network call is needed to clone, test and understand the project.

The interesting part is not "let a model drive the browser". It is the boundary around the model:
every proposed action is validated against an allowlist, written as a dry-run proposal, and can
only be executed or promoted after a human supplies a hash of the exact proposal they reviewed.

## What this repository demonstrates

- A deterministic Playwright suite over a small local OpsBoard demo app (no external target).
- A Pydantic allowlist schema that rejects CSS, XPath, JavaScript, shell commands, absolute URLs,
  traversal paths, extra fields and oversized values.
- A mock planner that produces reproducible plans, plus an opt-in OpenAI-compatible adapter behind
  `AI_ENABLED=true` **and** an environment-supplied key.
- A proposal/approval gate: generation never mutates the approved scenario set.
- Five narrow MCP tools: no raw shell, raw JavaScript, arbitrary pytest arguments or file paths.
- Bounded, redacted JUnit failure analysis using `defusedxml`, rendered as Markdown and a static site.
- CI that runs formatting, linting, type checks, the full suite and publishes the executed report.

## Architecture at a glance

```text
Untrusted input (goal / requirement / page text / provider output)
        |
        v
Provider: mock (default, offline)  ---  opt-in OpenAI-compatible adapter
        |
        v
Pydantic allowlist (Scenario, Step, Action)  -->  rejects unsafe plans
        |
        v
Proposal JSON + SHA-256 approval hash  -->  artifacts/proposals/  (dry run)
        |
        |  human reviews and supplies the exact hash
        v
run-plan / promote  -->  hash gate  -->  approved scenario (promote only)
        |
        v
Validated Playwright executor  -->  JUnit XML
        |
        v
defusedxml parser + redactor  -->  Markdown analysis + static HTML report
        |
        v
MCP tools expose only the bounded operations above
```

See [ARCHITECTURE.md](ARCHITECTURE.md) for the full design and trust boundaries,
[SECURITY.md](SECURITY.md) for the threat model, and
[TEST_STRATEGY.md](TEST_STRATEGY.md) for the verification matrix.

## Quick start

Requires Python 3.12+ and Git. Commands below use PowerShell from the repository root.

```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
.\.venv\Scripts\python.exe -m playwright install chromium

# Deterministic verification — no keys, no network provider
.\.venv\Scripts\python.exe -m ruff format --check src tests
.\.venv\Scripts\python.exe -m ruff check src tests
.\.venv\Scripts\python.exe -m mypy
.\.venv\Scripts\python.exe -m pytest --junitxml=artifacts/reports/latest-junit.xml -q

# Build the report site from the executed JUnit file
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent analyze
```

On macOS/Linux, use `.venv/bin/python` instead of `.venv\Scripts\python.exe`.

The console script `playwright-ai-mcp-agent` is also installed by `pip install -e .`; every example
below works with either `python -m playwright_ai_mcp_agent ...` or the console script.

### Demo target

The demo app is served on loopback only (`127.0.0.1:8765`) and uses synthetic credentials:

| Field | Value |
| --- | --- |
| Username | `demo` |
| Password | `demo-pass` |

Start it manually with `python -m playwright_ai_mcp_agent demo`, or let `run-plan` start and stop it
for you. Tests bind an ephemeral loopback port, so they never depend on port 8765 being free.

## CLI workflows

### 1. Curated requirement to proposal

```powershell
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent requirements
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent generate --requirement LOGIN_001
```

This writes `artifacts/proposals/login_001.json` and prints its `approval_hash`. Nothing is
executed or promoted.

### 2. Mock planner to proposal

```powershell
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent plan `
  --goal "Login and open the order ledger" --save
```

The goal is treated as untrusted data. With the default mock provider the output is deterministic
and no provider key is consulted.

### 3. Execute or promote only with human approval

```powershell
# Missing or wrong hash: exit code 2, nothing changes
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent run-plan --proposal login_001
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent run-plan --proposal login_001 --confirm 000...0

# Correct hash from the generated proposal
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent run-plan --proposal login_001 --confirm <approval_hash>
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent promote    --proposal login_001 --confirm <approval_hash>
```

`run-plan` executes in Chromium against the local demo. `promote` copies the reviewed scenario into
`scenarios/approved/`. A proposal edited after generation fails with a hash mismatch.

### 4. Failure analysis

```powershell
.\.venv\Scripts\python.exe -m pytest --junitxml=artifacts/reports/latest-junit.xml -q
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent analyze
```

`analyze` parses an **executed** JUnit file, redacts token/password patterns and any secrets found
in the environment, bounds each message to 800 characters, and writes:

- `artifacts/reports/failure-analysis.md`
- `site/index.html`

![Executed report](docs/sample-report.png)

The live report is published to GitHub Pages from CI.

### 5. MCP server

```powershell
.\.venv\Scripts\python.exe -m playwright_ai_mcp_agent mcp --transport stdio
```

Example client configuration (use the absolute path to your virtual-environment interpreter):

```json
{
  "mcpServers": {
    "qa-agent": {
      "command": "C:\\dev\\qa-portfolio\\playwright-ai-mcp-agent\\.venv\\Scripts\\python.exe",
      "args": ["-m", "playwright_ai_mcp_agent", "mcp", "--transport", "stdio"]
    }
  }
}
```

| Tool | Input | Behaviour |
| --- | --- | --- |
| `list_scenarios` | none | Lists curated requirement ids and catalogue version. |
| `run_tests` | `marker`: `unit`, `smoke`, `regression`, `security` | Runs one fixed pytest argv with a timeout, no shell. |
| `analyze_failures` | none | Parses the last executed JUnit into bounded Markdown. |
| `get_report` | `kind`: `counts` or `analysis` | Returns redacted counts or bounded analysis text. |
| `generate_proposal` | `requirement_id` from the curated list | Writes a dry-run proposal; promotion still needs a human hash. |

There is deliberately **no** tool for arbitrary shell commands, JavaScript, URLs, pytest flags or
file paths. Invalid values are rejected before any process is spawned.

## Optional real provider

Everything above works with `AI_ENABLED` unset. To try a real OpenAI-compatible endpoint:

```powershell
$env:AI_ENABLED = "true"
$env:LLM_PROVIDER = "openai-compatible"
$env:LLM_API_KEY = "<key from your secret store>"
$env:LLM_BASE_URL = "https://api.openai.com/v1"   # optional override
$env:LLM_MODEL = "gpt-4o-mini"                      # optional override
```

Both `AI_ENABLED=true` **and** a key are required; otherwise configuration fails with exit code 2.
Keys are read only from the environment, never from `.env` by the application, never printed, and
never included in provider error text. `.env.example` is a documentation template only and is safe
to commit. CI never uses a real provider.

Even with a real provider, output goes through the same allowlist and approval gate. A model cannot
execute a step, promote a scenario or change its own instructions.

## Verification summary

| Check | Result |
| --- | --- |
| `ruff format --check src tests` | clean |
| `ruff check src tests` | `All checks passed!` |
| `mypy` (strict) | `Success: no issues found in 21 source files` |
| Full pytest with JUnit | `52 passed`, 0 failures, 0 errors |
| Missing/wrong approval hash | exit 2, no file written or promoted |
| Tampered proposal | rejected with hash mismatch |
| `AI_ENABLED=true` real provider without key | exit 2 with explicit guidance |
| MCP invalid marker / report kind / requirement | rejected before any process starts |
| MCP stdio `tools/list` | five expected tools returned |
| CI | run `45887231155` succeeded; uploaded JUnit shows 52 tests, 0 failures, 0 errors |

The executed report is published at
<https://manikandank-qa.github.io/playwright-ai-mcp-agent/>. Full run history and evidence are
recorded in [TEST_STRATEGY.md](TEST_STRATEGY.md).

## Repository layout

```text
src/playwright_ai_mcp_agent/
  config.py              environment settings and opt-in gates
  approval.py            canonical JSON, SHA-256 approval hash, path allowlist
  proposals.py           dry-run proposal save/load/promote
  planner/schema.py      Pydantic allowlist for plans
  generator.py           curated requirement templates
  providers/             mock provider and opt-in OpenAI-compatible adapter
  demo_app/server.py     zero-dependency loopback OpsBoard demo
  executor/browser.py    validated Playwright step executor
  reporting/             redaction, defusedxml JUnit analysis, static site
  mcp_server.py          five narrow MCP tools
  __main__.py            CLI entry point
scenarios/
  requirements.json      curated requirement catalogue
  approved/              populated only after an approved promotion
tests/                   unit, security and integration layers
docs/sample-report.png   screenshot of an executed report
.github/workflows/ci.yml verification and Pages publication
```

## License and attribution

Source is licensed under the [MIT License](LICENSE). Dependencies keep their own licenses. Reference
repositories were reviewed for ideas only; no source, report or documentation text was copied. See
[NOTICE.md](NOTICE.md) for the full attribution list.