Skip to main content
Glama
webdriverio

WebDriverIO MCP Server

Official

switch_context

Idempotent

Switch between NATIVE_APP and WEBVIEW_* contexts in hybrid mobile apps. Use accessibility IDs in native context, CSS/XPath in webview. Changes persist for all subsequent commands.

Instructions

Switches between native and webview automation contexts in a hybrid mobile app. In NATIVE_APP context, use accessibility IDs; in WEBVIEW_* context, use CSS/XPath. Changes persist for all subsequent commands. Accepts context name or 1-based index. Use get_contexts to discover available targets. Mobile-only.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contextYesContext name to switch to (e.g., "NATIVE_APP", "WEBVIEW_com.example.app", or use index from wdio://session/current/contexts resource)

Implementation Reference

  • The actual handler function that receives the context argument (name or index) and calls browser.switchContext(). Supports index-based switching (1-based) or direct context name switching.
    export const switchContextTool: ToolCallback = async (args: {
      context: string;
    }): Promise<CallToolResult> => {
      try {
        const browser = getBrowser();
        const { context } = args;
    
        if (/^\d+$/.test(context)) {
          const contexts = await browser.getContexts();
          const index = Number.parseInt(context, 10) - 1;
          if (index >= 0 && index < contexts.length) {
            const targetContext = contexts[index] as string;
            await browser.switchContext(targetContext);
            return { content: [{ type: 'text', text: `Switched to context: ${targetContext}` }] };
          }
          throw new Error(`Error: Invalid context index ${context}. Available contexts: ${contexts.length}`);
        }
    
        await browser.switchContext(context);
    
        return {
          content: [{ type: 'text', text: `Switched to context: ${context}` }],
        };
      } catch (e) {
        return {
          isError: true,
          content: [{ type: 'text', text: `Error switching context: ${e}` }],
        };
      }
    };
  • Tool definition with name 'switch_context', description, annotations, and inputSchema defining a single 'context' string parameter.
    export const switchContextToolDefinition: ToolDefinition = {
      name: 'switch_context',
      description: 'Switches between native and webview automation contexts in a hybrid mobile app. In NATIVE_APP context, use accessibility IDs; in WEBVIEW_* context, use CSS/XPath. Changes persist for all subsequent commands. Accepts context name or 1-based index. Use get_contexts to discover available targets. Mobile-only.',
      annotations: { title: 'Switch Context', destructiveHint: false, idempotentHint: true },
      inputSchema: {
        context: z
          .string()
          .describe(
            'Context name to switch to (e.g., "NATIVE_APP", "WEBVIEW_com.example.app", or use index from wdio://session/current/contexts resource)',
          ),
      },
    };
  • The ToolDefinition interface used to type the switch_context definition.
    export interface ToolDefinition<T extends ZodRawShape = ZodRawShape> {
      name: string;
      description: string;
      inputSchema: T;
      annotations?: ToolAnnotations;
    }
  • src/server.ts:144-144 (registration)
    Registration of the switch_context tool via registerTool(switchContextToolDefinition, switchContextTool).
    registerTool(switchContextToolDefinition, switchContextTool);
  • The get_contexts tool, described as a companion to switch_context — 'Use before switch_context to discover NATIVE_APP and WEBVIEW_* targets.'
    export const getContextsToolDefinition: ToolDefinition = {
      name: 'get_contexts',
      description: 'Returns available automation contexts and the currently active one. Use before switch_context to discover NATIVE_APP and WEBVIEW_* targets. Mobile-only.',
      annotations: { title: 'Get Automation Contexts', readOnlyHint: true, idempotentHint: true },
      inputSchema: {},
    };
    
    export const getContextsTool: ToolCallback = async (): Promise<CallToolResult> => {
      const [contexts, current] = await Promise.all([readContexts(), readCurrentContext()]);
      if (contexts.mimeType === 'text/plain' && contexts.text.startsWith('Error')) {
        return { isError: true, content: [{ type: 'text', text: contexts.text }] };
      }
      if (current.mimeType === 'text/plain' && current.text.startsWith('Error')) {
        return { isError: true, content: [{ type: 'text', text: current.text }] };
      }
      const combined = {
        contexts: JSON.parse(contexts.text),
        currentContext: JSON.parse(current.text),
      };
      return { content: [{ type: 'text', text: JSON.stringify(combined) }] };
    };
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Beyond annotations, the description discloses that context persists for subsequent commands and is mobile-only. This adds valuable behavioral context beyond the idempotentHint and destructiveHint annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Four concise sentences, each adding essential information. No redundancy, well-structured with key points front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (one parameter, no output schema) and thoroughness of description, all necessary information is provided. References sibling tool for discovery, fulfilling completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema covers 100% with a clear description and examples. The description adds extra context on accepting both name and 1-based index, enhancing usability.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it switches between NATIVE_APP and WEBVIEW contexts in hybrid mobile apps, specifying different locator strategies for each. It also distinguishes itself from sibling tools like get_contexts by directing usage.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides clear guidance on when to use (switching contexts) and what to use (accessibility IDs for native, CSS/XPath for webview). Mentions using get_contexts for discovery and that changes persist, but does not explicitly state when not to use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/webdriverio/mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server