Skip to main content
Glama
williamvd4

Playwright Server

by williamvd4

playwright_get_text_content

Extract text content from web page elements for data collection or content analysis during browser automation.

Instructions

Get the text content of all elements

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The GetTextContentToolHandler class implements the core logic for the playwright_get_text_content tool. It retrieves the current browser page session, executes custom JavaScript to collect unique text contents from visible elements with few children (≤3), and returns them as text content.
    class GetTextContentToolHandler(ToolHandler):
        async def handle(self, name: str, arguments: dict | None) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
            if not self._sessions:
                return [types.TextContent(type="text", text="No active session. Please create a new session first.")]
            session_id = list(self._sessions.keys())[-1]
            page = self._sessions[session_id]["page"]
            # text_contents = await page.locator('body').all_inner_texts()
    
    
            async def get_unique_texts_js(page):
                unique_texts = await page.evaluate('''() => {
                var elements = Array.from(document.querySelectorAll('*')); // 先选择所有元素,再进行过滤
                var uniqueTexts = new Set();
    
                for (var element of elements) {
                    if (element.offsetWidth > 0 || element.offsetHeight > 0) { // 判断是否可见
                        var childrenCount = element.querySelectorAll('*').length;
                        if (childrenCount <= 3) {
                            var innerText = element.innerText ? element.innerText.trim() : '';
                            if (innerText && innerText.length <= 1000) {
                                uniqueTexts.add(innerText);
                            }
                            var value = element.getAttribute('value');
                            if (value) {
                                uniqueTexts.add(value);
                            }
                        }
                    }
                }
                //console.log( Array.from(uniqueTexts));
                return Array.from(uniqueTexts);
            }
            ''')
                return unique_texts
    
            # 使用示例
            text_contents = await get_unique_texts_js(page)
    
    
    
            return [types.TextContent(type="text", text=f"Text content of all elements: {text_contents}")]
  • JSON Schema definition for the tool in the list_tools response, defining the tool name, description, and an empty input schema (no required parameters).
     types.Tool(
        name="playwright_get_text_content",
        description="Get the text content of all elements",
        inputSchema={
            "type": "object",
            "properties": {
            },
        }
    ),
  • The tool is registered in the tool_handlers dictionary, mapping the tool name to an instance of GetTextContentToolHandler for execution in the call_tool handler.
    "playwright_get_text_content": GetTextContentToolHandler(),
  • The tool is registered in the list_tools handler by including it in the returned list of available tools with its schema.
    @server.list_tools()
    async def handle_list_tools() -> list[types.Tool]:
        """
        List available tools.
        Each tool specifies its arguments using JSON Schema validation.
        """
        return [
            # types.Tool(
            #     name="playwright_new_session",
            #     description="Create a new browser session",
            #     inputSchema={
            #         "type": "object",
            #         "properties": {
            #             "url": {"type": "string", "description": "Initial URL to navigate to"}
            #         }
            #     }
            # ),
            types.Tool(
                name="playwright_navigate",
                description="Navigate to a URL,thip op will auto create a session",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "url": {"type": "string"}
                    },
                    "required": ["url"]
                }
            ),
            types.Tool(
                name="playwright_screenshot",
                description="Take a screenshot of the current page or a specific element",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "selector": {"type": "string", "description": "CSS selector for element to screenshot,null is full page"},
                    },
                    "required": ["name"]
                }
            ),
            types.Tool(
                name="playwright_click",
                description="Click an element on the page using CSS selector",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "selector": {"type": "string", "description": "CSS selector for element to click"}
                    },
                    "required": ["selector"]
                }
            ),
            types.Tool(
                name="playwright_fill",
                description="Fill out an input field",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "selector": {"type": "string", "description": "CSS selector for input field"},
                        "value": {"type": "string", "description": "Value to fill"}
                    },
                    "required": ["selector", "value"]
                }
            ),
            types.Tool(
                name="playwright_evaluate",
                description="Execute JavaScript in the browser console",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "script": {"type": "string", "description": "JavaScript code to execute"}
                    },
                    "required": ["script"]
                }
            ),
            types.Tool(
                name="playwright_click_text",
                description="Click an element on the page by its text content",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "text": {"type": "string", "description": "Text content of the element to click"}
                    },
                    "required": ["text"]
                }
            ),
             types.Tool(
                name="playwright_get_text_content",
                description="Get the text content of all elements",
                inputSchema={
                    "type": "object",
                    "properties": {
                    },
                }
            ),
            types.Tool(
                name="playwright_get_html_content",
                description="Get the HTML content of the page",
                 inputSchema={
                    "type": "object",
                    "properties": {
                        "selector": {"type": "string", "description": "CSS selector for the element"}
                    },
                    "required": ["selector"]
                }
            )
        ]

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.1/5.0
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral information. It doesn't disclose whether this is a read-only operation, what happens if no elements exist, performance characteristics, or what format the text content is returned in. The phrase 'all elements' is vague without context.

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 that directly states the tool's purpose without any unnecessary words. It's appropriately sized for a simple tool with no parameters.

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?

For a tool with no annotations, no output schema, and no parameters, the description is insufficient. It doesn't explain what 'all elements' refers to (current page? specific selector?), what format the text is returned in, or how this differs from similar sibling tools. The agent lacks necessary context for proper use.

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?

The tool has zero parameters with 100% schema description coverage, so the description doesn't need to compensate for missing parameter documentation. The baseline for zero parameters is 4, as there are no parameters to explain beyond what's already covered.

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 action ('Get') and target ('text content of all elements'), which is specific and unambiguous. However, it doesn't differentiate from sibling tools like 'playwright_get_html_content' or explain what 'all elements' means in context.

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?

No guidance is provided on when to use this tool versus alternatives like 'playwright_get_html_content' or 'playwright_evaluate'. The description doesn't mention prerequisites, context requirements, or typical use cases.

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