Version 1.0 • Enterprise AutomationProduction Proven
Prompt-Driven AI Architecture · Playwright Python · MCP Orchestration · ChatGPT API

Prompt Driven AI based Automation Framework using Playwright MCP in Python

Bridging Natural Language Intent and Sandboxed Browser Execution

A modern automation framework where QA engineers and non-technical stakeholders define end-to-end browser workflows in natural language prompts. ChatGPT compiles prompts into structured Model Context Protocol (MCP) action sequences, which are executed securely and deterministically through Playwright in Python.

Prompt EngineChatGPT API (gpt-4.1-mini)
Execution DispatcherMCP Action Handlers (Python)
Browser AutomationPlaywright for Python
Test Runner & TriagePytest + AI Failure Triage
CORE ARCHITECTURE WORKFLOW

Prompt Engine ➔ MCP Dispatcher ➔ Playwright Browser Engine

Testers write in natural language. ChatGPT interprets intent and returns structured action JSON. Predefined MCP Python handlers safely execute browser steps without arbitrary code execution.

100%
Code-Free QA
Safe
MCP Sandboxed
Section 01

1. Executive Summary

This case study presents the design and implementation of an enterprise prompt-driven automation framework built using Playwright for Python, Model Context Protocol (MCP) based orchestration, and the ChatGPT API.

The foundational premise of the solution is that QA engineers and business analysts author test scenarios in natural language prompts rather than writing traditional, brittle Playwright scripts. ChatGPT interprets the prompt, extracts domain parameters, and generates a strictly validated JSON execution sequence. The MCP execution layer subsequently maps each approved step to sandboxed Python Playwright functions that perform the browser interactions, state assertions, and telemetry captures.

Primary Problem
High script maintenance, locator brittleness & code barrier for non-devs.
Engineered Solution
Prompt-to-MCP translation engine with sandboxed browser execution.
Key Impact
Significant drop in test creation time & near-zero test debt.
Section 02

2. Core Concept of the Project

The framework is architected around a streamlined three-phase pipeline that decouples test intent from low-level DOM selectors and browser execution protocols:

1

Natural Language Prompt

The tester or business analyst provides a scenario prompt describing the user journey, actions to take, and expected end-state validations in plain English.

2

ChatGPT Plan Generation

The prompt engine sends the scenario to ChatGPT with strict context and approved action schemas, returning a deterministic JSON plan of safe MCP steps.

3

MCP Execution Engine

The Python dispatcher runs the corresponding Playwright actions, handles authentication and assertions, and produces comprehensive test telemetry.

Section 03

3. Example Prompt & Structured Execution Plan

ChatGPT does not directly manipulate or control the browser. Instead, it parses natural language into an approved, strongly-typed execution plan that the local engine can safely evaluate.

Input Scenario Prompt
Open the application, log in with the QA user, navigate to the Connector page, create a new connector, enter the account ID and access key, validate the connection, and verify that the connector becomes active.
Passed with system context, registered MCP actions & validation rules.
Structured Plan Returned by ChatGPT
[
  { "action": "login", "user": "qa_user" },
  { "action": "open_connector_page" },
  { "action": "create_connector" },
  { "action": "fill_credentials" },
  { "action": "validate_connection" },
  { "action": "verify_connector_active" }
]
Strict schema: Only predefined MCP action keys are permitted.
Section 04

4. Execution Architecture & Technology Stack

The execution layer maintains predefined MCP actions implemented in Python. ChatGPT can exclusively select from these approved operations, preventing arbitrary code execution while keeping the framework maintainable, resilient, and enterprise-secure.

Technology Stack MatrixEnterprise Tested
Prompt EngineChatGPT API (gpt-4.1-mini)
Execution LayerModel Context Protocol (MCP) Dispatcher
Browser AutomationPlaywright for Python (Chromium / WebKit / Firefox)
Test RunnerPytest & pytest-xdist (Parallel test execution)
Reporting & TelemetryHTML, JSON summaries, screenshots & zip traces
CI/CD AutomationJenkins Pipelines / GitHub Actions Workflows
Configuration & Secretspython-dotenv & OS Environment Variables
Section 05

5. Suggested Project Structure & Dependency Setup

A modular layout separating prompts, AI connectors, MCP action registries, and test execution harnesses:

prompt_automation_framework/
├── prompts/ # Plain English scenario files
├── tests/ # Pytest test cases
├── workflows/ # Composite business journeys
├── mcp_actions/ # Playwright browser action handlers
├── ai_services/ # ChatGPT planner & failure triage
├── fixtures/ # Environment & browser hooks
├── reports/ # HTML and JSON execution output
├── traces/ # Playwright interactive trace files
├── screenshots/ # Failure captures
├── conftest.py # Pytest fixtures & setup
├── pytest.ini # Runner configuration
├── requirements.txt
└── .env # Encrypted API keys & credentials
Installing Core Dependencies

Set up the virtual environment and install Playwright, OpenAI client SDK, Pytest parallel runner, and headless browser binaries:

terminal commands
$ pip install playwright pytest pytest-xdist python-dotenv openai
$ playwright install
Ensure your OPENAI_API_KEY is configured in .env before launching tests.
Section 06 & 07

6. Predefined MCP Actions & Execution Dispatcher

Explore the modular Python components that power the prompt-to-browser execution pipeline:

from playwright.sync_api import Page, expect

def login(page: Page, username: str, password: str):
    page.get_by_role('textbox', name='Username').fill(username)
    page.get_by_role('textbox', name='Password').fill(password)
    page.get_by_role('button', name='Sign in').click()

def open_connector_page(page: Page):
    page.get_by_role('link', name='Connectors').click()

def create_connector(page: Page):
    page.get_by_role('button', name='Add Connector').click()

def fill_credentials(page: Page, account_id: str, access_key: str):
    page.get_by_role('textbox', name='Account ID').fill(account_id)
    page.get_by_role('textbox', name='Access Key').fill(access_key)

def validate_connection(page: Page):
    page.get_by_role('button', name='Validate').click()

def verify_connector_active(page: Page):
    expect(page.get_by_text('Connector is active')).to_be_visible()
Section 08 & 09

8. Writing Tests with Prompts & Enterprise Value

The test case is no longer an imperative script bound to brittle XPath/CSS locators—it is a clear, reusable business intention:

Zero Playwright Code for QA Engineers

QA engineers focus entirely on test coverage, boundary conditions, and acceptance criteria without writing browser plumbing.

Cross-Functional Collaboration

Product Managers and Business Analysts can author and review executable specifications directly in plain English.

Reusable Across Environments

The same prompt runs across local, staging, and production environments by swapping parameter bindings and target URLs.

Strict MCP Security & Predictability

Execution remains deterministic and guarded. The AI cannot execute arbitrary code or bypass security boundaries.

Section 10

10. AI-Assisted Failure Analysis & Triage

When a step fails, the framework immediately captures the error stack, screenshot path, trace summary, and DOM snapshot. These details are packaged and analyzed via ChatGPT to generate instant root-cause diagnostics and locator remediation:

analyze_failure() Implementation
def analyze_failure(error_message: str, dom_summary: str) -> str:
    response = client.responses.create(
        model='gpt-4.1-mini',
        input=f'''
        Error: {error_message}
        DOM summary: {dom_summary}

        Explain the likely cause and suggest a stable locator strategy.
        '''
    )

    return response.output_text
Example Triage Output Generated in Reports

[Root Cause]: Button 'Add Connector' was renamed in v2.4 build to 'Create New Connector'. Accessible role changed to role='button', name='Create New Connector'.
[Suggested Fix]: Update MCP action create_connector to check for both locator variants or adopt page.get_by_test_id('connector-add-btn').

Section 11

11. Enterprise Security Considerations

Approved Action Whitelisting

ChatGPT generates only registered MCP actions. It has zero capability to generate raw shell instructions, evaluate arbitrary scripts, or introduce unauthorized browser hooks.

Strict Secrets Isolation

Passwords, tokens, and access keys are resolved via environment variables and encrypted key stores—never fed into model training or third-party prompts.

Pre-Execution Schema Validation

Generated plans undergo JSON schema validation before dispatcher handoff. Unrecognized action names or missing required parameters trigger immediate test aborts.

Sanitized Trace Artifacts

Screenshots and network traces are scrubbed for sensitive customer data and stored within secure access-controlled CI/CD artifact storage.

Section 12

12. CI/CD Integration (Jenkins & GitHub Actions)

Automated parallel execution and test artifact archiving seamlessly fit into enterprise delivery pipelines:

pipeline {
  agent any
  stages {
    stage('Setup') {
      steps {
        sh 'python -m venv venv'
        sh '. venv/bin/activate && pip install -r requirements.txt'
        sh '. venv/bin/activate && playwright install --with-deps'
      }
    }
    stage('Run Prompt Tests') {
      steps {
        sh '. venv/bin/activate && pytest -n auto'
      }
    }
    stage('Archive') {
      steps {
        archiveArtifacts artifacts: 'reports/**, traces/**, screenshots/**'
      }
    }
  }
}
Section 13

13. End-to-End Execution Flow

01
Read PromptRead natural language test scenario from YAML or test case function.
02
Query ChatGPTSend prompt with application domain rules and approved MCP tools.
03
Receive PlanObtain structured, strongly-typed JSON list of approved actions.
04
Validate SchemaVerify that all actions and parameters match approved signatures.
05
Execute Playwright ActionsExecute browser operations deterministically through Python.
06
Capture TelemetryCapture real-time screenshots, network logs, and execution traces.
07
Analyze Failures with AITriage errors via DOM snapshots and receive instant remediation.
08
Generate ReportsProduce interactive HTML, JSON summaries, and CI/CD dashboards.
09
Publish Results in CI/CDArchive artifacts and trigger automated notifications.
Section 14

14. Observed Results & Engineering Impact

Metric Comparison BenchmarkVerified Outcomes
Time to create a new test Reduced significantly (Prompt in mins vs scripts in hours)
Code written by QA engineers Reduced substantially (Focus shifts to scenario logic)
Maintenance effort Lower due to centralized, reusable MCP action handlers
Failure triage time Reduced through automated AI DOM root-cause diagnostics
Release feedback speed Improved in parallelized CI/CD test pipelines
Section 15

15. Future Enhancements & Conclusion

1
Prompt templates for common enterprise business flows
2
Visual regression validation using multimodal models
3
Combined API and UI prompt execution chains
4
AI-generated synthetic test data and edge cases
5
Historical flaky test detection and automated self-healing
6
Approval workflow for mission-critical plan changes

Conclusion

This project demonstrates a transformative shift from code-centric automation to prompt-driven automation. Testers describe expected behavior in natural language, ChatGPT converts the request into a structured execution plan, and the MCP Playwright engine executes the browser automation reliably and securely.

The combination of Playwright for Python, MCP orchestration, and the ChatGPT API creates a scalable, maintainable, and intelligent automation framework ideally suited for enterprise validation workflows.

Ready to Modernize Your Test Automation?

Talk with CBNITS QA automation architects about implementing prompt-driven, MCP-sandboxed testing frameworks for your enterprise web applications.

Contact CBNITS Experts