Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ src/
│ ├── testingbot.provider.ts # TestingBot (browser + mobile + Storage)
│ └── digitalai.provider.ts # Digital.ai Testing (browser + mobile; accessKey cap, deviceQuery)
├── trace/ # Playwright-compatible trace recording (recorder.ts, tool-mapping.ts, zip-writer.ts)
├── tools/ # One file per MCP tool (see Tool Pattern below); includes the Electron
├── tools/ # One file per tool family (some define several tools; see Tool Pattern below); includes the Electron
│ # surface (electron-execute, electron-deeplink), mocking, and web extensions
├── resources/ # One file per MCP resource (see Recording below)
├── resources/ # One file per resource family (see Recording below)
├── recording/ # step-recorder.ts (withRecording HOF) + code-generator.ts
├── scripts/ # Browser/mobile scripts executed via browser.execute() — no try/catch, raw data only
├── locators/ # Element detection, selector generation, XML parsing (mobile)
Expand All @@ -59,9 +59,9 @@ src/
### Session State

Multiple live sessions: `state.ts` holds the session maps plus the default (`currentSession`); read `SessionMetadata` there.
`src/session/routing.ts` — `registerTool` wraps every tool in `withSessionTarget` (adds the optional `session` arg) unless
`sessionless`; it resolves the target via `resolveSession()`, queues calls per session and prefixes results with `[session: name (id8)]` only when a target is passed or more than one session is live.
`src/session/context.ts` — AsyncLocalStorage; `activeSessionId()` is what `getBrowser()` reads. Never read `currentSession` directly in tools.
`registerTool` (in `server.ts`) wraps every tool in `withSessionTarget` from `src/session/routing.ts` (adds the optional `session` arg) unless
the definition is `sessionless`; `withSessionTarget` resolves the target via `resolveSession()`, queues calls per session and prefixes results with `[session: name (id8)]` only when a target is passed or more than one session is live.
`src/session/context.ts` — AsyncLocalStorage; `activeSessionId()` is what `getBrowser()` reads. Tools use `getBrowser()`/`activeSessionId()`; only the session start/attach tools read `currentSession` directly.
`registerSession()` takes `{ keep, name }`: `keep` leaves the existing default in place.

Session lifecycle managed via `src/session/lifecycle.ts`:
Expand All @@ -71,8 +71,9 @@ Session lifecycle managed via `src/session/lifecycle.ts`:

### Tool Pattern

All tools follow this structure — one file per tool under `src/tools/`, registered in `server.ts`
with `registerTool(myToolDefinition, myTool)`, or `withRecording('my_tool', myTool)` to record steps:
All tools follow this structure — defined under `src/tools/` and registered in `server.ts` with
`registerTool(myToolDefinition, myTool)`; wrap the callback in `instrument('my_tool', myTool)`
(`withTrace` + `withRecording`) to record steps and trace:

```typescript
// 1. Definition with Zod schema
Expand Down Expand Up @@ -101,19 +102,21 @@ registerTool(myToolDefinition, myTool);

### Recording

Selected tools are wrapped with `withRecording()` in `server.ts`. Steps accumulate in `state.sessionHistory` (keyed by sessionId).
Selected tools are wrapped with `instrument()` (`withTrace` + `withRecording`) in `server.ts`; `start_session` uses `withRecording` directly. Steps accumulate in `state.sessionHistory` (keyed by sessionId).

MCP resources expose live session data — all at fixed URIs discoverable via ListResources:
MCP resources expose live session data. Fixed URIs appear in ListResources; template URIs (`{param}` path segments) are not listed and must be read by constructing the URI:

**Session history:**

- `wdio://sessions` — index of all sessions
- `wdio://session/current/steps` — current session step log
- `wdio://session/current/code` — generated WebdriverIO JS for current session
- `wdio://session/{sessionId}/steps` — step log for any session (URI template)
- `wdio://session/{sessionId}/code` — generated JS for any session (URI template)

**Live page state (current session):** `wdio://session/current/` + `elements`, `accessibility`,
`screenshot`, `cookies`, `tabs`, `contexts`, `context`, `app-state`, `geolocation`, `capabilities`, `logs`.
`screenshot`, `cookies`, `tabs`, `contexts`, `context`, `geolocation`, `capabilities`, `logs`, and the
template `app-state/{bundleId}`.

- `elements` is viewport-only — use the `get_elements` tool with `inViewportOnly: false` for all
- `capabilities` are the *resolved* values the driver accepted, including provider defaults
Expand Down Expand Up @@ -196,7 +199,7 @@ Only files whose purpose is not evident from the tree above.

### Package Manager Is pnpm

`packageManager: pnpm@10.32.1` and only `pnpm-lock.yaml` at the root. The `npm run` scripts below work,
`packageManager: pnpm@10.32.1` and only `pnpm-lock.yaml` at the root. The `npm run` scripts above work,
but installing a dependency with `npm install` forks the lockfile — use `pnpm add`.

### Console Output
Expand All @@ -209,14 +212,13 @@ stdout, which corrupts the MCP stdio protocol. Do not remove those reassignments
`get-interactable-browser-elements.ts` executes in browser context via `browser.execute()`. Cannot use Node.js APIs or
external imports.

### Auto-Detach Behavior
### Close vs Detach

Sessions created with `noReset: true` or without `appPath` automatically detach on close (don't terminate on Appium
server).
`close_session` ends the session unless it came from `attach_session` or `provider: 'external'` — those detach by default and keep running. Appium `noReset` sessions are closed (app data kept). `detach: true` detaches any non-Electron session.

### MCP Resource URI Templates

The MCP SDK only supports path-segment templates `{param}` in resource URIs — NOT RFC 6570 query param syntax `{?param}`. Resources using `{?param}` silently return "Resource not found". Keep resources at fixed URIs; expose parameterised access via tools instead.
The MCP SDK only supports path-segment templates `{param}` in resource URIs — NOT RFC 6570 query param syntax `{?param}`. Resources using `{?param}` silently return "Resource not found". Use path-segment templates or fixed URIs; expose query-style parameters via tools instead.

### Scripts vs Tools vs Resources

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ start_session({
})
```

The `tunnel` parameter replaces the deprecated `browserstackLocal`, `saucelabsLocal`, and `testmuLocal` params. Set it to `true` to auto-start the tunnel (stopped automatically after the session), or `'external'` to use a tunnel already running on your machine.
Set `tunnel` to `true` to auto-start the tunnel (stopped automatically after the session), or `'external'` to use a tunnel already running on your machine.

> **Note**: With `tunnel: true` the provider downloads and manages the tunnel binary for you. For `tunnel: 'external'` you run it yourself — the `wdio://saucelabs/local-binary`, `wdio://testmu/local-binary`, and `wdio://testingbot/local-binary` resources provide download URLs and setup instructions. The TestingBot Tunnel is a single cross-platform Java JAR (requires Java 11+) rather than a per-platform binary.

Expand Down Expand Up @@ -1200,7 +1200,7 @@ Test my hybrid app:
- To switch between browser and mobile, close the current session first
- Use `close_session({ detach: true })` to disconnect without terminating the session on the Appium server
- **State preservation** can be controlled with `noReset` and `fullReset` parameters during session creation
- Sessions created with `noReset: true` or without `appPath` will automatically detach on close
- Sessions created with `noReset: true` keep app data but are closed by `close_session`; pass `detach: true` to leave them running
- Sessions adopted with `attach_session` always detach on close unless `detach: false` is explicitly requested

⚠️ **Task Planning:**
Expand Down Expand Up @@ -1275,8 +1275,8 @@ close_session({detach: true})
close_session({detach: false})
```

Sessions created with `noReset: true` or without `appPath` will automatically detach on close.
Sessions adopted with `attach_session` are externally managed and also detach by default; pass `detach: false` only when the
Sessions created with `noReset: true` are closed like any other; pass `detach: true` to leave them running.
Sessions adopted with `attach_session` are externally managed and detach by default; pass `detach: false` only when the
MCP should deliberately terminate the existing remote session.

This is particularly useful when:
Expand Down
2 changes: 1 addition & 1 deletion src/providers/cloud/browserstack.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,19 @@
const platform = options.platform as string;
const userCapabilities = (options.capabilities as Record<string, unknown> | undefined) ?? {};

const browserstackLocal = (options.tunnel ?? options.browserstackLocal) as boolean | string | undefined;
const browserstackLocal = options.tunnel as boolean | string | undefined;

if (platform === 'browser') {
const bstackOptions: Record<string, unknown> = {
browserVersion: (options.browserVersion as string | undefined) ?? 'latest',
};
if (options.os) bstackOptions.os = options.os;

Check warning on line 34 in src/providers/cloud/browserstack.provider.ts

View workflow job for this annotation

GitHub Actions / lint

Using 'IfStatement > ExpressionStatement > AssignmentExpression' is not allowed
if (options.osVersion) bstackOptions.osVersion = options.osVersion;

Check warning on line 35 in src/providers/cloud/browserstack.provider.ts

View workflow job for this annotation

GitHub Actions / lint

Using 'IfStatement > ExpressionStatement > AssignmentExpression' is not allowed
if (browserstackLocal) bstackOptions.local = true;

Check warning on line 36 in src/providers/cloud/browserstack.provider.ts

View workflow job for this annotation

GitHub Actions / lint

Using 'IfStatement > ExpressionStatement > AssignmentExpression' is not allowed

const reporting = options.reporting as { project?: string; build?: string; session?: string } | undefined;

if (reporting?.project) bstackOptions.projectName = reporting.project;

Check warning on line 40 in src/providers/cloud/browserstack.provider.ts

View workflow job for this annotation

GitHub Actions / lint

Using 'IfStatement > ExpressionStatement > AssignmentExpression' is not allowed
if (reporting?.build) bstackOptions.buildName = reporting.build;
if (reporting?.session) bstackOptions.sessionName = reporting.session;

Expand Down
2 changes: 1 addition & 1 deletion src/providers/cloud/saucelabs.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class SauceLabsProvider implements SessionProvider {
const platform = options.platform as string;
const region = this.resolveRegion(options);
const userCapabilities = (options.capabilities as Record<string, unknown> | undefined) ?? {};
const saucelabsLocal = (options.tunnel ?? options.saucelabsLocal) as boolean | string | undefined;
const saucelabsLocal = options.tunnel as boolean | string | undefined;
const reporting = options.reporting as { project?: string; build?: string; session?: string } | undefined;

const userSauceOptions = (userCapabilities['sauce:options'] as Record<string, unknown> | undefined) ?? {};
Expand Down
2 changes: 1 addition & 1 deletion src/providers/cloud/testmu.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class TestMuProvider implements SessionProvider {
buildCapabilities(options: Record<string, unknown>): Record<string, unknown> {
const platform = options.platform as string;
const userCapabilities = (options.capabilities as Record<string, unknown> | undefined) ?? {};
const tunnel = (options.tunnel ?? options.testmuLocal) as boolean | string | undefined;
const tunnel = options.tunnel as boolean | string | undefined;
const reporting = options.reporting as { project?: string; build?: string; session?: string } | undefined;

const ltOptions: Record<string, unknown> = { w3c: true };
Expand Down
6 changes: 3 additions & 3 deletions src/resources/browserstack-local.resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ function getLocalBinaryInfo(): {
export const browserstackLocalBinaryResource: ResourceDefinition = {
name: 'browserstack-local-binary',
uri: 'wdio://browserstack/local-binary',
description: 'BrowserStack Local binary download URL and daemon setup instructions for the current platform. MUST be read and followed before using browserstackLocal: true in start_session.',
description: 'BrowserStack Local binary download URL and daemon setup instructions for the current platform. Only needed for tunnel: "external" — tunnel: true starts BrowserStack Local for you.',
handler: async () => {
const info = getLocalBinaryInfo();
const accessKey = process.env.BROWSERSTACK_ACCESS_KEY ?? '<BROWSERSTACK_ACCESS_KEY>';

const content = {
requirement: 'MUST start the BrowserStack Local daemon BEFORE calling start_session with browserstackLocal: true. Without it, all navigation to local/internal URLs will fail with ERR_TUNNEL_CONNECTION_FAILED.',
requirement: 'Start the BrowserStack Local daemon before calling start_session with tunnel: "external". Without a tunnel, navigation to local/internal URLs fails with ERR_TUNNEL_CONNECTION_FAILED. (tunnel: true starts it automatically.)',
platform: info.platform,
arch: info.arch,
downloadUrl: info.downloadUrl,
Expand All @@ -81,7 +81,7 @@ export const browserstackLocalBinaryResource: ResourceDefinition = {
stop: `./${info.binaryName} --key ${accessKey} --daemon stop`,
status: `./${info.binaryName} --daemon list`,
},
afterDaemonIsRunning: 'Call start_session with browserstackLocal: true to route BrowserStack traffic through the tunnel.',
afterDaemonIsRunning: 'Call start_session with tunnel: "external" to route BrowserStack traffic through the tunnel.',
};

return {
Expand Down
20 changes: 5 additions & 15 deletions src/tools/session.tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,6 @@ export const startSessionToolDefinition: ToolDefinition = {
region: z.enum(['us-west-1', 'eu-central-1', 'apac-southeast-1']).optional().default('eu-central-1').describe('Sauce Labs only'),
tunnel: z.union([z.literal('external'), coerceBoolean]).optional().default(false).describe('Cloud: true starts a tunnel, "external" uses a running one'),
tunnelName: z.string().optional(),
browserstackLocal: z.union([z.literal('external'), coerceBoolean]).optional().describe('Deprecated: tunnel'),
saucelabsLocal: z.union([z.literal('external'), coerceBoolean]).optional().describe('Deprecated: tunnel'),
testmuLocal: z.union([z.literal('external'), coerceBoolean]).optional().describe('Deprecated: tunnel'),
navigationUrl: z.string().optional().describe('URL to open after starting'),
networkLogs: networkLogsEnum.optional().describe('Local Chromium performance log capture (default from WDIO_MCP_NETWORK_LOGS or "none")'),
capabilities: z.record(z.string(), z.unknown()).optional().describe('Extra capabilities to merge, e.g. "wdio:electronServiceOptions"'),
Expand Down Expand Up @@ -160,9 +157,6 @@ type StartSessionArgs = {
region?: 'us-west-1' | 'eu-central-1' | 'apac-southeast-1';
tunnel?: boolean | 'external';
tunnelName?: string;
browserstackLocal?: boolean | 'external';
saucelabsLocal?: boolean | 'external';
testmuLocal?: boolean | 'external';
navigationUrl?: string;
networkLogs?: NetworkLogsMode;
capabilities?: Record<string, unknown>;
Expand All @@ -185,7 +179,7 @@ type AttachSessionArgs = {

export const closeSessionToolDefinition: ToolDefinition = {
name: 'close_session',
description: 'Closes the session, or with detach: true disconnects and leaves it running. Attached sessions and Appium sessions with noReset are detached unless detach: false.',
description: 'Closes the session, or with detach: true disconnects and leaves it running. Sessions from attach_session or provider "external" are detached unless detach: false; every other session, including Appium sessions with noReset, is closed.',
annotations: { title: 'Close Session', destructiveHint: true },
unqueued: true,
inputSchema: {
Expand Down Expand Up @@ -310,10 +304,8 @@ async function startBrowserSession(args: StartSessionArgs, defaultNetworkLogs: N
const provider = getProvider(args.provider ?? 'local', 'browser');
const connectionConfig = provider.getConnectionConfig(args as Record<string, unknown>);

// Normalize tunnel flag — support legacy browserstackLocal/saucelabsLocal/testmuLocal params
// MUST compute tunnelName BEFORE buildCapabilities so it is available in the capabilities
const effectiveTunnel = args.tunnel ?? args.browserstackLocal ?? args.saucelabsLocal ?? args.testmuLocal ?? false;
const tunnelEnabled = effectiveTunnel === true;
const tunnelEnabled = args.tunnel === true;
const tunnelName = tunnelEnabled && !args.tunnelName ? `wdio-mcp-${Date.now()}` : args.tunnelName;

const mergedCapabilities = provider.buildCapabilities({
Expand Down Expand Up @@ -515,10 +507,8 @@ async function startMobileSession(args: StartSessionArgs): Promise<CallToolResul
const provider = getProvider(args.provider ?? 'local', args.platform);
const serverConfig = provider.getConnectionConfig(args as Record<string, unknown>);

// Normalize tunnel flag — support legacy browserstackLocal/saucelabsLocal/testmuLocal params
// MUST compute tunnelName BEFORE buildCapabilities so it is available in the capabilities
const effectiveTunnel = args.tunnel ?? args.browserstackLocal ?? args.saucelabsLocal ?? args.testmuLocal ?? false;
const tunnelEnabled = effectiveTunnel === true;
const tunnelEnabled = args.tunnel === true;
const tunnelName = tunnelEnabled && !args.tunnelName ? `wdio-mcp-${Date.now()}` : args.tunnelName;

const mergedCapabilities = provider.buildCapabilities({ ...args as Record<string, unknown>, tunnelName });
Expand Down Expand Up @@ -566,8 +556,8 @@ async function startMobileSession(args: StartSessionArgs): Promise<CallToolResul
: appPath
? `\nApp: ${appPath}`
: '\nApp: (connected to running app)';
const detachNote = shouldAutoDetach
? '\n\n(Auto-detach enabled: session will be preserved on close. Use close_session({ detach: false }) to force terminate.)'
const detachNote = noReset === true
? '\n\n(noReset: app data is kept. close_session ends the Appium session; close_session({ detach: true }) leaves it running.)'
Comment on lines +559 to +560

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 App data promise is unsupported

A cloud mobile session started with noReset: true now says “app data is kept,” but the cloud providers do not pass that option to Appium. For example, BrowserStackProvider.buildCapabilities() sends no appium:noReset unless the caller supplies it separately through capabilities. Users are therefore promised behavior their session did not request. Only show this assurance when the generated capabilities actually request it.

: '';

const reportNote = provider.getStartNote?.(browser) ?? '';
Expand Down
16 changes: 8 additions & 8 deletions tests/providers/browserstack.provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,18 +95,18 @@ describe('BrowserStackProvider', () => {
expect((caps['goog:chromeOptions'] as any)?.args).toContain('--custom-flag');
});

it('sets local: true in bstack:options when browserstackLocal is true', () => {
it('sets local: true in bstack:options when tunnel is true', () => {
const caps = provider.buildCapabilities({
platform: 'browser',
browser: 'chrome',
browserstackLocal: true,
tunnel: true,
});
const bstack = caps['bstack:options'] as Record<string, unknown>;
expect(bstack.local).toBe(true);
});

it('does not set local in bstack:options when browserstackLocal is false', () => {
const caps = provider.buildCapabilities({ platform: 'browser', browser: 'chrome' });
it('does not set local in bstack:options when tunnel is false', () => {
const caps = provider.buildCapabilities({ platform: 'browser', browser: 'chrome', tunnel: false });
const bstack = caps['bstack:options'] as Record<string, unknown>;
expect(bstack.local).toBeUndefined();
});
Expand Down Expand Up @@ -176,23 +176,23 @@ describe('BrowserStackProvider', () => {
expect(caps['appium:newCommandTimeout']).toBe(300);
});

it('sets local: true in bstack:options when browserstackLocal is true', () => {
it('sets local: true in bstack:options when tunnel is true', () => {
const caps = provider.buildCapabilities({
platform: 'android',
deviceName: 'Pixel 7',
app: 'bs://abc',
browserstackLocal: true,
tunnel: true,
});
const bstack = caps['bstack:options'] as Record<string, unknown>;
expect(bstack.local).toBe(true);
});

it('sets local: true in bstack:options when browserstackLocal is "external"', () => {
it('sets local: true in bstack:options when tunnel is "external"', () => {
const caps = provider.buildCapabilities({
platform: 'android',
deviceName: 'Pixel 7',
app: 'bs://abc',
browserstackLocal: 'external',
tunnel: 'external',
});
const bstack = caps['bstack:options'] as Record<string, unknown>;
expect(bstack.local).toBe(true);
Expand Down
11 changes: 0 additions & 11 deletions tests/providers/saucelabs.provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,6 @@ describe('SauceLabsProvider', () => {
expect(sauce.tunnelName).toBe('my-tunnel');
});

it('supports legacy saucelabsLocal alias', () => {
const caps = provider.buildCapabilities({
platform: 'browser',
browser: 'chrome',
saucelabsLocal: true,
tunnelName: 'legacy-tunnel',
});
const sauce = caps['sauce:options'] as Record<string, unknown>;
expect(sauce.tunnelName).toBe('legacy-tunnel');
});

it('does not set tunnelName when tunnel is enabled but no tunnelName is given', () => {
const caps = provider.buildCapabilities({
platform: 'browser',
Expand Down
2 changes: 1 addition & 1 deletion tests/recording/code-generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ describe('generateCode - BrowserStack Local tunnel', () => {
{
index: 1,
tool: 'start_session',
params: { platform: 'browser', browser: 'chrome', browserstackLocal: true },
params: { platform: 'browser', browser: 'chrome', tunnel: true },
status: 'ok',
durationMs: 100,
timestamp: '2026-01-01T00:00:00.000Z',
Expand Down
Loading
Loading