Skip to main content
Glama
cyberchitta

Scrapling Fetch MCP

by cyberchitta

s_fetch_pattern

Extract content matching regex patterns from web pages while avoiding bot detection. Retrieve specific website data with configurable modes for different security levels.

Instructions

Extracts content matching regex patterns from web pages. Retrieves specific content from websites with bot-detection avoidance. For best performance, start with 'basic' mode (fastest), then only escalate to 'stealth' or 'max-stealth' modes if basic mode fails. Returns matched content as 'METADATA: {json}\n\n[content]' where metadata includes match statistics and truncation information. Each matched content chunk is delimited with '॥๛॥' and prefixed with '[Position: start-end]' indicating its byte position in the original document, allowing targeted follow-up requests with s-fetch-page using specific start_index values.

Args:
    url: URL to fetch
    search_pattern: Regular expression pattern to search for in the content
    mode: Fetching mode (basic, stealth, or max-stealth)
    format: Output format (html or markdown)
    max_length: Maximum number of characters to return.
    context_chars: Number of characters to include before and after each match

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYes
search_patternYes
modeNobasic
formatNomarkdown
max_lengthNo
context_charsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 's_fetch_pattern' tool. It is registered via the @mcp.tool() decorator and implements the tool logic by calling the underlying fetch_pattern_impl, with error handling.
    @mcp.tool()
    async def s_fetch_pattern(
        url: str,
        search_pattern: str,
        mode: str = "basic",
        format: str = "markdown",
        max_length: int = 5000,
        context_chars: int = 200,
    ) -> str:
        """Extracts content matching regex patterns from web pages. Retrieves specific content from websites with bot-detection avoidance. For best performance, start with 'basic' mode (fastest), then only escalate to 'stealth' or 'max-stealth' modes if basic mode fails. Returns matched content as 'METADATA: {json}\\n\\n[content]' where metadata includes match statistics and truncation information. Each matched content chunk is delimited with '॥๛॥' and prefixed with '[Position: start-end]' indicating its byte position in the original document, allowing targeted follow-up requests with s-fetch-page using specific start_index values.
    
        Args:
            url: URL to fetch
            search_pattern: Regular expression pattern to search for in the content
            mode: Fetching mode (basic, stealth, or max-stealth)
            format: Output format (html or markdown)
            max_length: Maximum number of characters to return.
            context_chars: Number of characters to include before and after each match
        """
        try:
            result = await fetch_pattern_impl(
                url, search_pattern, mode, format, max_length, context_chars
            )
            return result
        except Exception as e:
            logger = getLogger("scrapling_fetch_mcp")
            logger.error("DETAILED ERROR IN s_fetch_pattern: %s", str(e))
            logger.error("TRACEBACK: %s", format_exc())
            raise
  • The core helper function implementing the pattern fetching logic: fetches the page, converts to format, searches with regex, extracts contexts, truncates, and formats metadata.
    async def fetch_pattern_impl(
        url: str,
        search_pattern: str,
        mode: str,
        format: str,
        max_length: int,
        context_chars: int,
    ) -> str:
        page = await browse_url(url, mode)
        is_markdown = format == "markdown"
        full_content = (
            _html_to_markdown(page.html_content) if is_markdown else page.html_content
        )
    
        original_length = len(full_content)
        matched_content, match_count = _search_content(
            full_content, search_pattern, context_chars
        )
    
        if not matched_content:
            metadata_json = _create_metadata(original_length, 0, False, None, 0)
            return f"METADATA: {metadata_json}\n\n"
    
        truncated_content = matched_content[:max_length]
        is_truncated = len(matched_content) > max_length
    
        metadata_json = _create_metadata(
            original_length, len(truncated_content), is_truncated, None, match_count
        )
        return f"METADATA: {metadata_json}\n\n{truncated_content}"
  • Helper function that performs regex search on content, extracts context around matches, merges overlapping chunks, and formats the output with position markers.
    def _search_content(
        content: str, pattern: str, context_chars: int = 200
    ) -> tuple[str, int]:
        try:
            matches = list(compile(pattern).finditer(content))
            if not matches:
                return "", 0
            chunks = [
                (
                    max(0, match.start() - context_chars),
                    min(len(content), match.end() + context_chars),
                )
                for match in matches
            ]
            merged_chunks = reduce(
                lambda acc, chunk: (
                    [*acc[:-1], (acc[-1][0], max(acc[-1][1], chunk[1]))]
                    if acc and chunk[0] <= acc[-1][1]
                    else [*acc, chunk]
                ),
                chunks,
                [],
            )
            result_sections = [
                f"॥๛॥\n[Position: {start}-{end}]\n{content[start:end]}"
                for start, end in merged_chunks
            ]
            return "\n".join(result_sections), len(matches)
        except re_error as e:
            return f"ERROR: Invalid regex pattern: {str(e)}", 0
Behavior4/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 effectively describes key behaviors: bot-detection avoidance capabilities, performance characteristics of different modes, output format details including metadata structure and content delimiters, and how results enable follow-up requests with s_fetch_page. However, it doesn't mention error handling, rate limits, or authentication requirements.

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

Conciseness4/5

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

The description is well-structured with purpose first, usage guidance second, output format third, and parameters last. It's appropriately detailed for a complex tool but could be slightly more concise in the output format explanation. Every sentence serves a clear purpose.

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 complexity (6 parameters, regex matching, multiple modes), no annotations, but with an output schema present, the description provides excellent contextual completeness. It covers purpose, usage guidelines, behavioral details, parameter semantics, and output format - everything needed for effective tool use without needing to explain return values (handled by output schema).

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

Parameters5/5

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

With 0% schema description coverage, the description must fully compensate, which it does excellently. The Args section provides clear semantic explanations for all 6 parameters, including practical guidance for 'mode' selection and explaining what 'context_chars' and 'max_length' control. This adds substantial value beyond the bare schema.

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 the tool's purpose: 'Extracts content matching regex patterns from web pages.' It specifies the verb ('extracts'), resource ('content'), and method ('regex patterns'), distinguishing it from the sibling tool s_fetch_page which presumably fetches full pages rather than pattern-matched content.

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

Usage Guidelines5/5

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

The description provides explicit usage guidance: 'For best performance, start with 'basic' mode (fastest), then only escalate to 'stealth' or 'max-stealth' modes if basic mode fails.' This gives clear when-to-use instructions for mode selection and implicitly suggests basic mode as the default approach.

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/cyberchitta/scrapling-fetch-mcp'

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