Skip to content

🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev

perf(mcp): Optimize the tokens a bit more.

Karim shoair54c3a54360e7
diff --git a/scrapling/core/_types.py b/scrapling/core/_types.py
index ea589e9..27b7089 100644
--- a/scrapling/core/_types.py
+++ b/scrapling/core/_types.py
@@ -32,7 +32,7 @@ from typing import (
Coroutine,
SupportsIndex,
)
-from typing_extensions import Self, Unpack, TypedDict, NotRequired
+from typing_extensions import Self, Unpack, TypedDict, NotRequired, TypeAliasType
# Proxy can be a string URL or a dict (Playwright format: {"server": "...", "username": "...", "password": "..."})
ProxyType = Union[str, Dict[str, str]]
diff --git a/scrapling/core/ai.py b/scrapling/core/ai.py
index d8f2aed..2412f34 100644
--- a/scrapling/core/ai.py
+++ b/scrapling/core/ai.py
@@ -10,6 +10,7 @@ from dataclasses import dataclass, field
from anyio import CancelScope
from curl_cffi.curl import CurlError
+from curl_cffi.requests import BrowserTypeLiteral
from mcp.server import MCPServer
from mcp.server.mcpserver import Image
from mcp.server.mcpserver.exceptions import ToolError
@@ -34,7 +35,6 @@ from scrapling.core._browser_actions import (
from scrapling.core._network_formatting import NetworkPart, NetworkRequestInfo, NetworkRequestModel, _request_details
from scrapling.core.shell import Convertor, _CONTROL_CHARS_PATTERN
from scrapling.engines.toolbelt.custom import Response as _ScraplingResponse
-from scrapling.engines.static import ImpersonateType
from scrapling.fetchers import FetcherSession, AsyncStealthySession
from scrapling.engines._browsers._types import StealthFetchParams
from scrapling.core._types import (
@@ -48,6 +48,7 @@ from scrapling.core._types import (
Awaitable,
Callable,
Annotated,
+ TypeAliasType,
Set,
Sequence,
Iterator,
@@ -58,6 +59,9 @@ from scrapling.core._types import (
SUPPORTED_HTTP_METHODS,
)
+_BrowserProfile = TypeAliasType("_BrowserProfile", BrowserTypeLiteral)
+_MCPImpersonateType = _BrowserProfile | List[_BrowserProfile] | None
+
SessionType = Literal["stealthy", "static"]
SessionExtractionType = Literal[extraction_types, "snapshot"]
ScreenshotType = Literal["png", "jpeg"]
@@ -323,7 +327,7 @@ class ScraplingMCPServer:
async def open_request_session(
self,
session_id: Optional[str] = None,
- impersonate: ImpersonateType = "chrome",
+ impersonate: _MCPImpersonateType = "chrome",
proxy: Optional[str] = None,
) -> SessionCreatedModel:
"""Open a reusable HTTP session for `session_make_request`, keeping cookies, connections, and request settings.
@@ -562,7 +566,7 @@ class ScraplingMCPServer:
async def make_request(
url: str,
method: SUPPORTED_HTTP_METHODS = "GET",
- impersonate: ImpersonateType = "chrome",
+ impersonate: _MCPImpersonateType = "chrome",
extraction_type: extraction_types = "markdown",
css_selector: Optional[str] = None,
main_content_only: bool = True,
diff --git a/tests/ai/test_ai_mcp.py b/tests/ai/test_ai_mcp.py
index 8d42a4c..6540320 100644
--- a/tests/ai/test_ai_mcp.py
+++ b/tests/ai/test_ai_mcp.py
@@ -276,6 +276,69 @@ setTimeout(() => { const p = document.querySelector('#answer'); p.textContent =
assert existing.session.mock_calls == []
+class TestRequestProfiles:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("tool", ["make_request", "open_request_session"])
+ @pytest.mark.parametrize("impersonate", ["chrome", ["chrome", "firefox"], None])
+ async def test_profiles_fetch_through_mcp(self, httpbin, tool, impersonate):
+ server = ScraplingMCPServer()
+ async with Client(server._build_server("127.0.0.1", 8000)) as client:
+ args = {"url": f"{httpbin.url}/html", "css_selector": "h1"}
+ try:
+ if tool == "open_request_session":
+ opened = await client.call_tool(tool, {"session_id": "profiles", "impersonate": impersonate})
+ assert not opened.is_error and opened.structured_content is not None
+ assert server._sessions["profiles"].session._default_impersonate == impersonate
+ args["session_id"] = "profiles"
+ else:
+ args["impersonate"] = impersonate
+ result = await client.call_tool(
+ "session_make_request" if tool == "open_request_session" else tool, args
+ )
+ assert not result.is_error and result.structured_content is not None
+ assert result.structured_content["status"] == 200
+ assert "Herman Melville - Moby-Dick" in "".join(result.structured_content["content"])
+ finally:
+ if "profiles" in server._sessions:
+ closed = await client.call_tool("close_session", {"session_id": "profiles"})
+ assert not closed.is_error
+ assert not server._sessions
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("tool", ["make_request", "open_request_session"])
+ @pytest.mark.parametrize("impersonate", ["unknown-browser", ["chrome", "unknown-browser"]])
+ async def test_invalid_profiles_fail_before_opening_sessions(self, monkeypatch, tool, impersonate):
+ factory = Mock()
+ monkeypatch.setattr("scrapling.core.ai.FetcherSession", factory)
+ server = ScraplingMCPServer()
+ args = {"url": "https://example.com"} if tool == "make_request" else {"session_id": "profiles"}
+ args["impersonate"] = impersonate
+ async with Client(server._build_server("127.0.0.1", 8000)) as client:
+ result = await client.call_tool(tool, args)
+ assert result.is_error
+ assert result.content and isinstance(result.content[0], TextContent)
+ assert "impersonate" in result.content[0].text
+ factory.assert_not_called()
+ assert not server._sessions
+
+ @pytest.mark.asyncio
+ async def test_profile_schemas_share_the_enum_and_keep_titles(self):
+ async with Client(ScraplingMCPServer()._build_server("127.0.0.1", 8000)) as client:
+ tools = {tool.name: tool for tool in (await client.list_tools()).tools}
+ for name in ("make_request", "open_request_session"):
+ schema = tools[name].input_schema
+ profile = schema["properties"]["impersonate"]
+ assert profile["title"] == "Impersonate" and profile["default"] == "chrome"
+ choices = profile["anyOf"]
+ scalar = next(choice for choice in choices if "$ref" in choice)
+ array = next(choice for choice in choices if choice.get("type") == "array")
+ assert array["items"] == scalar
+ assert {"type": "null"} in choices
+ definition = schema["$defs"][scalar["$ref"].removeprefix("#/$defs/")]
+ assert definition["type"] == "string"
+ assert {"chrome", "firefox"} <= set(definition["enum"])
+
+
class TestSessionTypeChecks:
@pytest.mark.parametrize(
"session_type, allowed, error",