Skip to main content
Glama
pvinis
by pvinis

playwright_assert_response

Validate the content and presence of an HTTP response initiated earlier, ensuring it matches the expected data. Use the response ID to confirm accuracy in automated web interactions.

Instructions

Wait for and validate a previously initiated HTTP response wait operation.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idYesIdentifier of the HTTP response initially expected using `Playwright_expect_response`.
valueNoData to expect in the body of the HTTP response. If provided, the assertion will fail if this value is not found in the response body.

Implementation Reference

  • The AssertResponseTool class that implements the execute method for handling the playwright_assert_response tool logic, including waiting for the response promise, parsing JSON body, asserting optional value presence, and cleaning up the promise map.
    export class AssertResponseTool extends BrowserToolBase {
      /**
       * Execute the assert response tool
       */
      async execute(
        args: AssertResponseArgs,
        context: ToolContext
      ): Promise<ToolResponse> {
        return this.safeExecute(context, async () => {
          if (!args.id) {
            return createErrorResponse(
              "Missing required parameter: id must be provided"
            );
          }
    
          const responsePromise = responsePromises.get(args.id);
          if (!responsePromise) {
            return createErrorResponse(
              `No response wait operation found with ID: ${args.id}`
            );
          }
    
          try {
            const response = await responsePromise;
            const body = await response.json();
    
            if (args.value) {
              const bodyStr = JSON.stringify(body);
              if (!bodyStr.includes(args.value)) {
                const messages = [
                  `Response body does not contain expected value: ${args.value}`,
                  `Actual body: ${bodyStr}`,
                ];
                return createErrorResponse(messages.join("\n"));
              }
            }
    
            const messages = [
              `Response assertion for ID ${args.id} successful`,
              `URL: ${response.url()}`,
              `Status: ${response.status()}`,
              `Body: ${JSON.stringify(body, null, 2)}`,
            ];
            return createSuccessResponse(messages.join("\n"));
          } catch (error) {
            return createErrorResponse(
              `Failed to assert response: ${(error as Error).message}`
            );
          } finally {
            responsePromises.delete(args.id);
          }
        });
      }
    }
  • Tool schema definition including name, description, and input schema with required 'id' and optional 'value' parameters.
    {
      name: "playwright_assert_response",
      description: "Wait for and validate a previously initiated HTTP response wait operation.",
      inputSchema: {
        type: "object",
        properties: {
          id: { type: "string", description: "Identifier of the HTTP response initially expected using `Playwright_expect_response`." },
          value: { type: "string", description: "Data to expect in the body of the HTTP response. If provided, the assertion will fail if this value is not found in the response body." }
        },
        required: ["id"],
      },
    },
  • Switch case in the main tool handler that registers and dispatches 'playwright_assert_response' calls to the AssertResponseTool instance.
    case "playwright_expect_response":
      return await expectResponseTool.execute(args, context);
    
    case "playwright_assert_response":
      return await assertResponseTool.execute(args, context);
  • src/tools.ts:416-416 (registration)
    Inclusion in BROWSER_TOOLS array which triggers browser context setup for this tool.
    "playwright_assert_response",
  • Code generation case for including assert_response logic in generated Playwright tests.
        case 'playwright_assert_response':
          return this.generateAssertResponseStep(parameters);
        case 'playwright_hover':
          return this.generateHoverStep(parameters);
        case 'playwright_select':
          return this.generateSelectStep(parameters);
        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}`;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states it 'waits for and validates' without detailing behavioral traits like timeout behavior, error handling, or what happens if validation fails. It mentions assertion failure if value not found, but lacks context on retries, logging, or performance implications.

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, efficient sentence with zero waste—it directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse quickly.

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

Completeness3/5

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

Given no annotations and no output schema, the description is minimal but covers the basic operation. For a validation tool with 2 parameters, it lacks details on return values, error conditions, or integration context, leaving gaps in completeness despite the concise description.

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?

Schema description coverage is 100%, so the schema already fully documents both parameters. The description adds no additional meaning beyond what's in the schema descriptions, such as examples or edge cases. Baseline 3 is appropriate when schema does the heavy lifting.

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 clearly states the tool's purpose as 'Wait for and validate a previously initiated HTTP response wait operation,' which specifies the action (wait and validate) and resource (HTTP response). It distinguishes from siblings by referencing `playwright_expect_response`, but doesn't explicitly differentiate from other validation tools like `playwright_console_logs`.

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

Usage Guidelines3/5

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

The description implies usage by referencing `playwright_expect_response` as a prerequisite, suggesting it should be used after that tool. However, it doesn't provide explicit when-to-use guidance, alternatives, or exclusions compared to other validation tools in the sibling list.

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