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}');`;
    }

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