LRriver commented on code in PR #355:
URL: https://github.com/apache/hugegraph-ai/pull/355#discussion_r3339311974


##########
tools/ai/hugegraph-ai-deepwiki-skill/plugins/hugegraph-ai-deepwiki-skill/skills/hugegraph-ai-deepwiki-skill/scripts/deepwiki_mcp.py:
##########
@@ -0,0 +1,556 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Small DeepWiki MCP client for repository-scoped Q&A."""
+
+# ruff: noqa: T201
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import socket
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+DEFAULT_ENDPOINT = "https://mcp.deepwiki.com/mcp";
+CLIENT_NAME = "hugegraph-ai-deepwiki-skill"
+SCRIPT_DIR = Path(__file__).resolve().parent
+SKILL_DIR = SCRIPT_DIR.parent
+PLUGIN_MANIFEST_PATH = SKILL_DIR.parent.parent / ".codex-plugin" / 
"plugin.json"
+REPOS_PATH = SKILL_DIR / "references" / "repos.json"
+CLIENT_VERSION_FALLBACK = "0.1.4"
+CONTEXT_WINDOW_SIZE = 30
+CONTEXT_STRIDE = 10
+STOPWORDS = {
+    "a",
+    "an",
+    "and",
+    "apache",
+    "are",
+    "as",
+    "for",
+    "hugegraph",
+    "how",
+    "in",
+    "is",
+    "it",
+    "of",
+    "on",
+    "or",
+    "the",
+    "to",
+    "used",
+    "what",
+    "where",
+    "which",
+    "why",
+}
+
+
+class McpError(RuntimeError):
+    pass
+
+
+def env_float(name: str, default: float) -> float:
+    raw_value = os.environ.get(name)
+    if raw_value is None:
+        return default
+    try:
+        return float(raw_value)
+    except ValueError as exc:
+        raise McpError(f"{name} must be a number, got {raw_value!r}.") from exc
+
+
+def stream_timeout_seconds() -> float:
+    return max(1.0, env_float("DEEPWIKI_MCP_STREAM_TIMEOUT", 120.0))
+
+
+def load_client_version() -> str:
+    try:
+        parsed = json.loads(PLUGIN_MANIFEST_PATH.read_text(encoding="utf-8"))
+    except (OSError, json.JSONDecodeError):
+        return CLIENT_VERSION_FALLBACK
+    if isinstance(parsed, dict) and isinstance(parsed.get("version"), str):
+        return parsed["version"]
+    return CLIENT_VERSION_FALLBACK
+
+
+CLIENT_VERSION = load_client_version()
+
+
+def preview_text(text: str, limit: int = 500) -> str:
+    if len(text) <= limit:
+        return text
+    return f"{text[:limit]}..."
+
+
+def positive_int(value: str) -> int:
+    try:
+        parsed = int(value)
+    except ValueError as exc:
+        raise argparse.ArgumentTypeError("--limit must be an integer") from exc
+    if parsed < 1:
+        raise argparse.ArgumentTypeError("--limit must be >= 1")
+    return parsed
+
+
+def load_repos() -> dict[str, dict[str, Any]]:
+    try:
+        with REPOS_PATH.open("r", encoding="utf-8") as file:
+            repos = json.load(file)
+    except FileNotFoundError as exc:
+        raise McpError(f"Repository profile file is missing: {REPOS_PATH}") 
from exc
+    except UnicodeError as exc:
+        raise McpError(f"Repository profile file is not valid UTF-8: 
{REPOS_PATH}") from exc
+    except OSError as exc:
+        raise McpError(f"Repository profile file could not be read: 
{REPOS_PATH}") from exc
+    except json.JSONDecodeError as exc:
+        raise McpError(f"Repository profile file is not valid JSON: 
{REPOS_PATH}") from exc
+
+    if not isinstance(repos, dict):
+        raise McpError(f"Repository profile file must contain a JSON object: 
{REPOS_PATH}")
+    return repos
+
+
+def resolve_repo(alias_or_name: str) -> str:
+    repos = load_repos()
+    profile = repos.get(alias_or_name)
+    if profile is None:
+        known = ", ".join(sorted(repos))
+        raise McpError(f"Unknown repository alias '{alias_or_name}'. Known 
aliases: {known}.")
+    if not isinstance(profile, dict):
+        raise McpError(f"Repository profile for '{alias_or_name}' must be a 
JSON object.")
+    if not profile.get("enabled", False):
+        raise McpError(
+            f"Repository alias '{alias_or_name}' is reserved but not enabled 
yet ({profile.get('repoName')})."
+        )
+    repo_name = profile.get("repoName")
+    if not isinstance(repo_name, str) or not repo_name:
+        raise McpError(f"Repository alias '{alias_or_name}' is missing a valid 
repoName.")
+    return repo_name
+
+
+def cache_root() -> Path:
+    configured = os.environ.get("DEEPWIKI_MCP_CACHE_DIR")
+    if configured:
+        return Path(configured).expanduser()
+    xdg_cache = os.environ.get("XDG_CACHE_HOME")
+    if xdg_cache:
+        return Path(xdg_cache).expanduser() / "deepwiki-mcp"
+    try:
+        return Path.home() / ".cache" / "deepwiki-mcp"
+    except RuntimeError:
+        return Path(tempfile.gettempdir()) / "deepwiki-mcp"
+
+
+def repo_cache_dir(repo_name: str) -> Path:
+    return cache_root() / repo_name.replace("/", "__")
+
+
+def contents_cache_path(repo_name: str) -> Path:
+    return repo_cache_dir(repo_name) / "wiki-contents.md"
+
+
+def write_text_atomic(path: Path, text: str) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    tmp_path: Path | None = None
+    try:
+        with tempfile.NamedTemporaryFile(
+            "w",
+            encoding="utf-8",
+            dir=path.parent,
+            prefix=f"{path.name}.",
+            suffix=".tmp",
+            delete=False,
+        ) as tmp_file:
+            tmp_file.write(text)
+            tmp_path = Path(tmp_file.name)
+        tmp_path.replace(path)
+    finally:
+        if tmp_path is not None and tmp_path.exists():
+            tmp_path.unlink()
+
+
+def parse_json(data: str) -> dict[str, Any]:
+    try:
+        parsed = json.loads(data)
+    except json.JSONDecodeError as exc:
+        raise McpError(f"DeepWiki MCP returned non-JSON content: 
{preview_text(data)}") from exc
+    if not isinstance(parsed, dict):
+        raise McpError(f"DeepWiki MCP returned an unexpected JSON payload: 
{preview_text(data)}")
+    return parsed
+
+
+def read_sse_response(response: Any, expected_id: int | None) -> dict[str, 
Any]:

Review Comment:
   Fixed. Added focused `unittest` coverage for `read_sse_response()` timeout 
handling, cache write fallback, invalid cache refetch, and cached-context 
scoring/selection. Local Ruff check/format, py_compile, and unit tests pass; 
the latest PR CI is also passing.



##########
tools/ai/hugegraph-ai-deepwiki-skill/plugins/hugegraph-ai-deepwiki-skill/skills/hugegraph-ai-deepwiki-skill/scripts/deepwiki_mcp.py:
##########
@@ -0,0 +1,559 @@
+#!/usr/bin/env python3

Review Comment:
   Fixed in the latest `deepwiki-skill` head. Added explicit archive rules in 
the root `.gitattributes` for this skill’s `scripts/` directory and files, and 
verified with `git archive HEAD | tar -tf -` that `scripts/deepwiki_mcp.py` is 
now included alongside the tests/manifests.



##########
tools/ai/hugegraph-ai-deepwiki-skill/plugins/hugegraph-ai-deepwiki-skill/skills/hugegraph-ai-deepwiki-skill/scripts/deepwiki_mcp.py:
##########
@@ -0,0 +1,559 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Small DeepWiki MCP client for repository-scoped Q&A."""
+
+# ruff: noqa: T201
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import socket
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+DEFAULT_ENDPOINT = "https://mcp.deepwiki.com/mcp";
+CLIENT_NAME = "hugegraph-ai-deepwiki-skill"
+SCRIPT_DIR = Path(__file__).resolve().parent
+SKILL_DIR = SCRIPT_DIR.parent
+PLUGIN_MANIFEST_PATH = SKILL_DIR.parent.parent / ".codex-plugin" / 
"plugin.json"
+REPOS_PATH = SKILL_DIR / "references" / "repos.json"
+CLIENT_VERSION_FALLBACK = "0.1.4"
+CONTEXT_WINDOW_SIZE = 30
+CONTEXT_STRIDE = 10
+STOPWORDS = {
+    "a",
+    "an",
+    "and",
+    "apache",
+    "are",
+    "as",
+    "for",
+    "hugegraph",
+    "how",
+    "in",
+    "is",
+    "it",
+    "of",
+    "on",
+    "or",
+    "the",
+    "to",
+    "used",
+    "what",
+    "where",
+    "which",
+    "why",
+}
+
+
+class McpError(RuntimeError):
+    pass
+
+
+def env_float(name: str, default: float) -> float:
+    raw_value = os.environ.get(name)
+    if raw_value is None:
+        return default
+    try:
+        return float(raw_value)
+    except ValueError as exc:
+        raise McpError(f"{name} must be a number, got {raw_value!r}.") from exc
+
+
+def stream_timeout_seconds() -> float:
+    return max(1.0, env_float("DEEPWIKI_MCP_STREAM_TIMEOUT", 120.0))
+
+
+def load_client_version() -> str:
+    try:
+        parsed = json.loads(PLUGIN_MANIFEST_PATH.read_text(encoding="utf-8"))
+    except (OSError, json.JSONDecodeError):
+        return CLIENT_VERSION_FALLBACK
+    if isinstance(parsed, dict) and isinstance(parsed.get("version"), str):
+        return parsed["version"]
+    return CLIENT_VERSION_FALLBACK
+
+
+CLIENT_VERSION = load_client_version()
+
+
+def preview_text(text: str, limit: int = 500) -> str:
+    if len(text) <= limit:
+        return text
+    return f"{text[:limit]}..."
+
+
+def positive_int(value: str) -> int:
+    try:
+        parsed = int(value)
+    except ValueError as exc:
+        raise argparse.ArgumentTypeError("--limit must be an integer") from exc
+    if parsed < 1:
+        raise argparse.ArgumentTypeError("--limit must be >= 1")
+    return parsed
+
+
+def load_repos() -> dict[str, dict[str, Any]]:
+    try:
+        with REPOS_PATH.open("r", encoding="utf-8") as file:
+            repos = json.load(file)
+    except FileNotFoundError as exc:
+        raise McpError(f"Repository profile file is missing: {REPOS_PATH}") 
from exc
+    except UnicodeError as exc:
+        raise McpError(f"Repository profile file is not valid UTF-8: 
{REPOS_PATH}") from exc
+    except OSError as exc:
+        raise McpError(f"Repository profile file could not be read: 
{REPOS_PATH}") from exc
+    except json.JSONDecodeError as exc:
+        raise McpError(f"Repository profile file is not valid JSON: 
{REPOS_PATH}") from exc
+
+    if not isinstance(repos, dict):
+        raise McpError(f"Repository profile file must contain a JSON object: 
{REPOS_PATH}")
+    return repos
+
+
+def resolve_repo(alias_or_name: str) -> str:
+    repos = load_repos()
+    profile = repos.get(alias_or_name)
+    if profile is None:
+        known = ", ".join(sorted(repos))
+        raise McpError(f"Unknown repository alias '{alias_or_name}'. Known 
aliases: {known}.")
+    if not isinstance(profile, dict):
+        raise McpError(f"Repository profile for '{alias_or_name}' must be a 
JSON object.")
+    if not profile.get("enabled", False):
+        raise McpError(
+            f"Repository alias '{alias_or_name}' is reserved but not enabled 
yet ({profile.get('repoName')})."
+        )
+    repo_name = profile.get("repoName")
+    if not isinstance(repo_name, str) or not repo_name:
+        raise McpError(f"Repository alias '{alias_or_name}' is missing a valid 
repoName.")
+    return repo_name
+
+
+def cache_root() -> Path:
+    configured = os.environ.get("DEEPWIKI_MCP_CACHE_DIR")
+    if configured:
+        return Path(configured).expanduser()
+    xdg_cache = os.environ.get("XDG_CACHE_HOME")
+    if xdg_cache:
+        return Path(xdg_cache).expanduser() / "deepwiki-mcp"
+    try:
+        return Path.home() / ".cache" / "deepwiki-mcp"
+    except RuntimeError:
+        return Path(tempfile.gettempdir()) / "deepwiki-mcp"
+
+
+def repo_cache_dir(repo_name: str) -> Path:
+    return cache_root() / repo_name.replace("/", "__")
+
+
+def contents_cache_path(repo_name: str) -> Path:
+    return repo_cache_dir(repo_name) / "wiki-contents.md"
+
+
+def write_text_atomic(path: Path, text: str) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    tmp_path: Path | None = None
+    try:
+        with tempfile.NamedTemporaryFile(
+            "w",
+            encoding="utf-8",
+            dir=path.parent,
+            prefix=f"{path.name}.",
+            suffix=".tmp",
+            delete=False,
+        ) as tmp_file:
+            tmp_file.write(text)
+            tmp_path = Path(tmp_file.name)
+        tmp_path.replace(path)
+    finally:
+        if tmp_path is not None and tmp_path.exists():
+            tmp_path.unlink()
+
+
+def parse_json(data: str) -> dict[str, Any]:
+    try:
+        parsed = json.loads(data)
+    except json.JSONDecodeError as exc:
+        raise McpError(f"DeepWiki MCP returned non-JSON content: 
{preview_text(data)}") from exc
+    if not isinstance(parsed, dict):
+        raise McpError(f"DeepWiki MCP returned an unexpected JSON payload: 
{preview_text(data)}")
+    return parsed
+
+
+def read_sse_response(response: Any, expected_id: int | None) -> dict[str, 
Any]:
+    data_lines: list[str] = []
+    seen_payloads: list[str] = []
+    max_seconds = stream_timeout_seconds()
+    deadline = time.monotonic() + max_seconds
+    timed_out = False
+
+    while True:
+        if time.monotonic() > deadline:
+            timed_out = True
+            break
+        try:
+            raw_line = response.readline()
+        except (TimeoutError, socket.timeout):  # noqa: UP041
+            timed_out = True
+            break
+        if not raw_line:
+            break
+
+        line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
+        if line.startswith("data:"):
+            data_content = line[5:]
+            if data_content.startswith(" "):
+                data_content = data_content[1:]
+            data_lines.append(data_content)
+            continue
+        if line:
+            continue
+
+        if not data_lines:
+            continue
+
+        data = "\n".join(data_lines)
+        data_lines = []
+        seen_payloads.append(data)
+        parsed = parse_json(data)
+        if expected_id is None or parsed.get("id") == expected_id:
+            return parsed
+
+    if data_lines:

Review Comment:
   Fixed in the latest `deepwiki-skill` head. `read_sse_response()` now treats 
buffered partial SSE data as a timeout when the stream times out instead of 
parsing incomplete JSON. Added 
`test_read_sse_response_reports_partial_event_timeout`; local Ruff, py_compile, 
and unittest checks pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to