Skip to content

The agent that grows with you

fix(web): keyless MCP honours SSE CR terminators and declared charsets

teknium14b00842536ab
diff --git a/plugins/web/keyless_mcp.py b/plugins/web/keyless_mcp.py
index 116feaff329..e59d33b71bd 100644
--- a/plugins/web/keyless_mcp.py
+++ b/plugins/web/keyless_mcp.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import logging
+import re
import threading
import uuid
from typing import Any, Callable, Dict, List, Optional
@@ -122,9 +123,9 @@ def _parse_mcp_body(body: str) -> str:
(Parallel) or SSE ``data: {...}`` lines (Exa). Raises :class:`KeylessMCPError` for
JSON-RPC errors and ``isError`` tool results (e.g. Exa's free-tier rate limit).
- SSE frames are split on ``\\n`` only: ``str.splitlines()`` also breaks on U+0085 /
- U+2028 / U+2029, which legitimately occur inside CJK page text and would cut a
- ``data:`` line in two. A parsed envelope with no text is reported as such — it is
+ SSE frames are split on the SSE line terminators (CRLF, CR, LF) only:
+ ``str.splitlines()`` also breaks on U+0085 / U+2028 / U+2029, which legitimately
+ occur inside CJK page text and would cut a ``data:`` line in two. A parsed envelope with no text is reported as such — it is
the vendor's answer, not an unrecognized shape."""
def _from_payload(payload: str) -> Optional[str]:
@@ -143,7 +144,7 @@ def _parse_mcp_body(body: str) -> str:
stripped = body.strip()
candidates = [stripped] if stripped.startswith("{") else []
- candidates += [line[len("data: "):] for line in body.split("\n") if line.startswith("data: ")]
+ candidates += [line[len("data: "):] for line in re.split(r"\r\n|\r|\n", body) if line.startswith("data: ")]
envelope_seen = False
for candidate in candidates:
try:
@@ -156,6 +157,17 @@ def _parse_mcp_body(body: str) -> str:
raise KeylessMCPError("MCP response contained no text content" if envelope_seen else "Unrecognized MCP response shape")
+def _response_text(response: Any) -> str:
+ """Body decoded with the declared charset, else UTF-8. JSON-RPC and SSE bodies are UTF-8 by
+ spec, but ``text/event-stream`` carries no charset and ``requests`` then decodes ``.text`` as
+ ISO-8859-1 — mojibake for every non-ASCII result and, for CJK, stray U+0085 line breaks that
+ made the envelope unparseable."""
+ from requests.utils import get_encoding_from_headers
+ content_type = response.headers.get("Content-Type", "")
+ declared = get_encoding_from_headers({"content-type": content_type}) if "charset=" in content_type.lower() else None
+ return response.content.decode(declared or "utf-8", errors="replace")
+
+
def mcp_call(url: str, tool: str, arguments: Dict[str, Any], timeout: int = _TIMEOUT_SECONDS) -> str:
"""POST a JSON-RPC ``tools/call`` and return the text payload. Raises
:class:`KeylessMCPError` on transport failures, non-2xx, JSON-RPC and tool errors."""
@@ -167,11 +179,8 @@ def mcp_call(url: str, tool: str, arguments: Dict[str, Any], timeout: int = _TIM
except requests.RequestException as exc:
raise KeylessMCPError(f"request failed: {exc}") from exc
if response.status_code >= 400:
- raise KeylessMCPError(f"HTTP {response.status_code}: {response.text[:300]}")
- # JSON-RPC and SSE bodies are UTF-8 by spec, but ``text/event-stream`` carries no charset and
- # ``requests`` then decodes ``.text`` as ISO-8859-1 — mojibake for every non-ASCII result and,
- # for CJK, stray U+0085 line breaks that made the envelope unparseable.
- return _parse_mcp_body(response.content.decode("utf-8", errors="replace"))
+ raise KeylessMCPError(f"HTTP {response.status_code}: {_response_text(response)[:300]}")
+ return _parse_mcp_body(_response_text(response))
# --- Parallel (search.parallel.ai) — JSON text payloads -----------------------
@@ -282,7 +291,7 @@ def _keenable_request(method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
headers["Content-Type"] = "application/json"
response = getattr(requests, method)(f"{KEENABLE_API_URL}{path}", headers=headers, timeout=_TIMEOUT_SECONDS, **kwargs)
if response.status_code >= 400:
- raise KeylessMCPError((response.text or "").strip() or f"HTTP {response.status_code}")
+ raise KeylessMCPError(_response_text(response).strip() or f"HTTP {response.status_code}")
return response.json()
diff --git a/tests/tools/test_web_keyless_fallback.py b/tests/tools/test_web_keyless_fallback.py
index 762d3c52f77..fe0b2400f33 100644
--- a/tests/tools/test_web_keyless_fallback.py
+++ b/tests/tools/test_web_keyless_fallback.py
@@ -112,6 +112,42 @@ class TestParseMcpBody:
with pytest.raises(keyless_mcp.KeylessMCPError, match="no text content"):
keyless_mcp._parse_mcp_body(body)
+ @pytest.mark.parametrize("terminator", ["\r", "\r\n"])
+ def test_sse_frames_split_on_every_spec_line_terminator(self, terminator):
+ """SSE permits CR, LF and CRLF as line terminators; splitting on ``\\n`` alone lost bare-CR frames."""
+ payload = json.dumps({"result": {"content": [{"type": "text", "text": "Title: hello"}]}})
+ body = f"event: message{terminator}data: {payload}{terminator}{terminator}"
+ assert keyless_mcp._parse_mcp_body(body) == "Title: hello"
+
+ def test_declared_charset_wins_over_utf8_default(self):
+ import requests
+
+ title = "你好"
+ payload = json.dumps({"result": {"content": [{"type": "text", "text": f"Title: {title}"}]}}, ensure_ascii=False)
+ response = requests.Response()
+ response.status_code = 200
+ response.headers["Content-Type"] = "text/event-stream; charset=gbk"
+ response.encoding = "gbk"
+ response._content = f"event: message\ndata: {payload}\n\n".encode("gbk")
+ with patch.object(requests, "post", return_value=response):
+ assert keyless_mcp.mcp_call(keyless_mcp.EXA_MCP_URL, "web_search_exa", {"query": title}) == f"Title: {title}"
+
+ @pytest.mark.parametrize("call", ["mcp", "keenable"])
+ def test_non_ascii_error_body_without_charset_is_decoded_as_utf8(self, call):
+ import requests
+
+ response = requests.Response()
+ response.status_code = 429
+ response.headers["Content-Type"] = "text/plain"
+ response.encoding = "ISO-8859-1" # what the adapter picks for text/* without a charset
+ response._content = "请求过多".encode("utf-8")
+ with patch.object(requests, "post", return_value=response), patch.object(requests, "get", return_value=response):
+ with pytest.raises(keyless_mcp.KeylessMCPError, match="请求过多"):
+ if call == "mcp":
+ keyless_mcp.mcp_call(keyless_mcp.EXA_MCP_URL, "web_search_exa", {"query": "q"})
+ else:
+ keyless_mcp._keenable_request("get", "/v1/search/public")
+
class TestExaTextParsing:
def test_parses_blocks(self):