diff --git a/CLAUDE.md b/CLAUDE.md index 1170f11..8ed6dfe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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) @@ -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`: @@ -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 @@ -101,11 +102,12 @@ 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 @@ -113,7 +115,8 @@ MCP resources expose live session data — all at fixed URIs discoverable via Li - `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 @@ -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 @@ -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 diff --git a/README.md b/README.md index 34e2197..fa7850c 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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:** @@ -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: diff --git a/src/providers/cloud/browserstack.provider.ts b/src/providers/cloud/browserstack.provider.ts index 6fa8192..7252d91 100644 --- a/src/providers/cloud/browserstack.provider.ts +++ b/src/providers/cloud/browserstack.provider.ts @@ -25,7 +25,7 @@ export class BrowserStackProvider implements SessionProvider { const platform = options.platform as string; const userCapabilities = (options.capabilities as Record | 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 = { diff --git a/src/providers/cloud/saucelabs.provider.ts b/src/providers/cloud/saucelabs.provider.ts index a9b1111..f9b3869 100644 --- a/src/providers/cloud/saucelabs.provider.ts +++ b/src/providers/cloud/saucelabs.provider.ts @@ -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 | 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 | undefined) ?? {}; diff --git a/src/providers/cloud/testmu.provider.ts b/src/providers/cloud/testmu.provider.ts index c696cec..455440e 100644 --- a/src/providers/cloud/testmu.provider.ts +++ b/src/providers/cloud/testmu.provider.ts @@ -24,7 +24,7 @@ export class TestMuProvider implements SessionProvider { buildCapabilities(options: Record): Record { const platform = options.platform as string; const userCapabilities = (options.capabilities as Record | 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 = { w3c: true }; diff --git a/src/resources/browserstack-local.resource.ts b/src/resources/browserstack-local.resource.ts index 1e6e75a..a99b867 100644 --- a/src/resources/browserstack-local.resource.ts +++ b/src/resources/browserstack-local.resource.ts @@ -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 ?? ''; 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, @@ -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 { diff --git a/src/tools/session.tool.ts b/src/tools/session.tool.ts index 326b50f..8e402b1 100644 --- a/src/tools/session.tool.ts +++ b/src/tools/session.tool.ts @@ -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"'), @@ -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; @@ -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: { @@ -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); - // 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({ @@ -515,10 +507,8 @@ async function startMobileSession(args: StartSessionArgs): Promise); - // 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, tunnelName }); @@ -566,8 +556,8 @@ async function startMobileSession(args: StartSessionArgs): Promise { 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; 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; expect(bstack.local).toBeUndefined(); }); @@ -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; 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; expect(bstack.local).toBe(true); diff --git a/tests/providers/saucelabs.provider.test.ts b/tests/providers/saucelabs.provider.test.ts index 04d4135..eff2e2a 100644 --- a/tests/providers/saucelabs.provider.test.ts +++ b/tests/providers/saucelabs.provider.test.ts @@ -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; - 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', diff --git a/tests/recording/code-generator.test.ts b/tests/recording/code-generator.test.ts index 866e8e6..fb6033e 100644 --- a/tests/recording/code-generator.test.ts +++ b/tests/recording/code-generator.test.ts @@ -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', diff --git a/tests/tools/start-session-browserstack.test.ts b/tests/tools/start-session-browserstack.test.ts index a63e547..0a9e294 100644 --- a/tests/tools/start-session-browserstack.test.ts +++ b/tests/tools/start-session-browserstack.test.ts @@ -107,9 +107,9 @@ describe('start_session with provider: browserstack', () => { }); }); -describe('start_session with browserstackLocal: true', () => { +describe('start_session with tunnel: true', () => { it('creates a BrowserstackTunnel instance and calls start() before remote()', async () => { - await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', browserstackLocal: true }); + await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', tunnel: true }); const tunnelInstance = vi.mocked(BrowserstackTunnel).mock.instances[0] as unknown as { start: ReturnType; stop: ReturnType }; expect(tunnelInstance.start).toHaveBeenCalledWith( @@ -122,8 +122,8 @@ describe('start_session with browserstackLocal: true', () => { expect(startOrder).toBeLessThan(remoteOrder); }); - it('does NOT call BrowserstackTunnel when browserstackLocal is false', async () => { - await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', browserstackLocal: false }); + it('does NOT call BrowserstackTunnel when tunnel is false', async () => { + await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', tunnel: false }); expect(BrowserstackTunnel).not.toHaveBeenCalled(); }); @@ -135,21 +135,21 @@ describe('start_session with browserstackLocal: true', () => { this.stop = vi.fn(); }); - const result = await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', browserstackLocal: true }); + const result = await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', tunnel: true }); expect(result.isError).toBe(true); expect(result.content[0].text).toContain('tunnel failed'); expect(mockRemote).not.toHaveBeenCalled(); }); - it('does NOT call BrowserstackTunnel when browserstackLocal is "external"', async () => { - await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', browserstackLocal: 'external' }); + it('does NOT call BrowserstackTunnel when tunnel is "external"', async () => { + await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', tunnel: 'external' }); expect(BrowserstackTunnel).not.toHaveBeenCalled(); }); - it('sets local: true in bstack:options when browserstackLocal is "external"', async () => { - await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', browserstackLocal: 'external' }); + it('sets local: true in bstack:options when tunnel is "external"', async () => { + await callTool({ provider: 'browserstack', platform: 'browser', browser: 'chrome', tunnel: 'external' }); const [call] = mockRemote.mock.calls; const bstackOpts = call[0].capabilities['bstack:options']; @@ -162,7 +162,7 @@ describe('start_session with browserstackLocal: true', () => { platform: 'android', deviceName: 'Samsung Galaxy S23', app: 'bs://abc123', - browserstackLocal: true, + tunnel: true, }); const tunnelInstance = vi.mocked(BrowserstackTunnel).mock.instances[0] as unknown as { start: ReturnType };