Skip to main content
Glama
pvinis
by pvinis

playwright_custom_user_agent

Set a custom User Agent for the Playwright browser instance to simulate specific devices or browsers during web interactions, testing, or scraping tasks.

Instructions

Set a custom User Agent for the browser

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
userAgentYesCustom User Agent for the Playwright browser instance

Implementation Reference

  • The CustomUserAgentTool class implements the core handler logic for the 'playwright_custom_user_agent' tool. It validates that the current page's user agent matches the requested one, confirming successful application during browser launch.
    /**
     * Tool for validating custom User Agent settings
     */
    export class CustomUserAgentTool extends BrowserToolBase {
      /**
       * Execute the custom user agent tool
       */
      async execute(args: CustomUserAgentArgs, context: ToolContext): Promise<ToolResponse> {
        return this.safeExecute(context, async (page) => {
          if (!args.userAgent) {
            return createErrorResponse("Missing required parameter: userAgent must be provided");
          }
    
          try {
            const currentUserAgent = await page.evaluate(() => navigator.userAgent);
            
            if (currentUserAgent !== args.userAgent) {
              const messages = [
                "Page was already initialized with a different User Agent.",
                `Requested: ${args.userAgent}`,
                `Current: ${currentUserAgent}`
              ];
              return createErrorResponse(messages.join('\n'));
            }
    
            return createSuccessResponse("User Agent validation successful");
          } catch (error) {
            return createErrorResponse(`Failed to validate User Agent: ${(error as Error).message}`);
          }
        });
      }
    } 
  • Tool schema definition including name, description, and input schema requiring a 'userAgent' string.
    {
      name: "playwright_custom_user_agent",
      description: "Set a custom User Agent for the browser",
      inputSchema: {
        type: "object",
        properties: {
          userAgent: { type: "string", description: "Custom User Agent for the Playwright browser instance" }
        },
        required: ["userAgent"],
      },
    },
  • Registration and dispatch in the main handleToolCall switch statement, delegating execution to the CustomUserAgentTool instance.
    case "playwright_custom_user_agent":
      return await customUserAgentTool.execute(args, context);
  • Instantiation of the CustomUserAgentTool instance during tool initialization.
    if (!customUserAgentTool)
      customUserAgentTool = new CustomUserAgentTool(server);
  • Helper function in codegen generator that produces Playwright code for the custom user agent action.
        case 'playwright_custom_user_agent':
          return this.generateCustomUserAgentStep(parameters);
        default:
          console.warn(`Unsupported tool: ${toolName}`);
          return null;
      }
    }
    
    private generateNavigateStep(parameters: Record<string, unknown>): string {
      const { url, waitUntil } = parameters;
      const options = waitUntil ? `, { waitUntil: '${waitUntil}' }` : '';
      return `
      // Navigate to URL
      await page.goto('${url}'${options});`;
    }
    
    private generateFillStep(parameters: Record<string, unknown>): string {
      const { selector, value } = parameters;
      return `
      // Fill input field
      await page.fill('${selector}', '${value}');`;
    }
    
    private generateClickStep(parameters: Record<string, unknown>): string {
      const { selector } = parameters;
      return `
      // Click element
      await page.click('${selector}');`;
    }
    
    private generateScreenshotStep(parameters: Record<string, unknown>): string {
      const { name, fullPage = false, path } = parameters;
      const options = [];
      if (fullPage) options.push('fullPage: true');
      if (path) options.push(`path: '${path}'`);
      
      const optionsStr = options.length > 0 ? `, { ${options.join(', ')} }` : '';
      return `
      // Take screenshot
      await page.screenshot({ path: '${name}.png'${optionsStr} });`;
    }
    
    private generateExpectResponseStep(parameters: Record<string, unknown>): string {
      const { url, id } = parameters;
      return `
      // Wait for response
      const ${id}Response = page.waitForResponse('${url}');`;
    }
    
    private generateAssertResponseStep(parameters: Record<string, unknown>): string {
      const { id, value } = parameters;
      const assertion = value 
        ? `\n    const responseText = await ${id}Response.text();\n    expect(responseText).toContain('${value}');`
        : `\n    expect(${id}Response.ok()).toBeTruthy();`;
      return `
      // Assert response${assertion}`;
    }
    
    private generateHoverStep(parameters: Record<string, unknown>): string {
      const { selector } = parameters;
      return `
      // Hover over element
      await page.hover('${selector}');`;
    }
    
    private generateSelectStep(parameters: Record<string, unknown>): string {
      const { selector, value } = parameters;
      return `
      // Select option
      await page.selectOption('${selector}', '${value}');`;
    }
    
    private generateCustomUserAgentStep(parameters: Record<string, unknown>): string {
      const { userAgent } = parameters;
      return `
      // Set custom user agent
      await context.setUserAgent('${userAgent}');`;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool sets a custom User Agent but does not cover critical aspects like whether this affects all subsequent browser actions, requires specific browser state, has side effects, or how it interacts with other Playwright tools. This leaves significant gaps in understanding its behavior.

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?

The description is a single, direct sentence that efficiently conveys the core function without unnecessary words. It is front-loaded and wastes no space, making it highly concise and well-structured for quick comprehension.

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

Completeness2/5

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

Given the tool's complexity as a browser configuration action with no annotations and no output schema, the description is incomplete. It fails to address behavioral context, usage scenarios, or expected outcomes, leaving the agent with insufficient information to effectively invoke or understand the tool's impact.

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

Parameters3/5

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

The input schema has 100% description coverage, with the 'userAgent' parameter well-documented as 'Custom User Agent for the Playwright browser instance'. The description adds no additional meaning beyond this, such as format examples or constraints, so it meets the baseline for high schema coverage without compensating further.

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

Purpose4/5

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

The description 'Set a custom User Agent for the browser' clearly states the action ('Set') and resource ('User Agent for the browser'), making the purpose evident. However, it does not explicitly differentiate from sibling tools like 'playwright_navigate' or 'playwright_get', which might also involve browser configuration, leaving room for minor ambiguity in distinguishing its specific role.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives, such as default User Agent settings or other browser configuration methods. It lacks context on prerequisites, timing, or exclusions, offering only a basic functional statement without usage instructions.

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

Related 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/pvinis/mcp-playwright-stealth'

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