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


##########
tools/ai/hugegraph-ai-deepwiki-skill/plugins/hugegraph-ai-deepwiki-skill/skills/hugegraph-ai-deepwiki-skill/scripts/deepwiki_mcp.py:
##########
@@ -0,0 +1,465 @@
+#!/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 sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+DEFAULT_ENDPOINT = "https://mcp.deepwiki.com/mcp";
+SCRIPT_DIR = Path(__file__).resolve().parent
+SKILL_DIR = SCRIPT_DIR.parent
+REPOS_PATH = SKILL_DIR / "references" / "repos.json"
+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 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 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 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"
+    return Path.home() / ".cache" / "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.with_suffix(path.suffix + ".tmp")
+    tmp_path.write_text(text, encoding="utf-8")
+    tmp_path.replace(path)
+
+
+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: 
{data[:500]}") from exc
+    if not isinstance(parsed, dict):
+        raise McpError(f"DeepWiki MCP returned an unexpected JSON payload: 
{data[:500]}")
+    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 = float(os.environ.get("DEEPWIKI_MCP_STREAM_TIMEOUT", "120"))
+    deadline = time.monotonic() + max_seconds
+    timed_out = False
+
+    while True:
+        if time.monotonic() > deadline:
+            timed_out = True
+            break
+        raw_line = response.readline()

Review Comment:
   Follow-up Python 3.9 socket timeout compatibility fix added in 8305e3d.



##########
tools/ai/hugegraph-ai-deepwiki-skill/plugins/hugegraph-ai-deepwiki-skill/skills/hugegraph-ai-deepwiki-skill/scripts/deepwiki_mcp.py:
##########
@@ -0,0 +1,465 @@
+#!/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 sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+DEFAULT_ENDPOINT = "https://mcp.deepwiki.com/mcp";
+SCRIPT_DIR = Path(__file__).resolve().parent
+SKILL_DIR = SCRIPT_DIR.parent
+REPOS_PATH = SKILL_DIR / "references" / "repos.json"
+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 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 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 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"
+    return Path.home() / ".cache" / "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.with_suffix(path.suffix + ".tmp")
+    tmp_path.write_text(text, encoding="utf-8")
+    tmp_path.replace(path)
+
+
+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: 
{data[:500]}") from exc
+    if not isinstance(parsed, dict):
+        raise McpError(f"DeepWiki MCP returned an unexpected JSON payload: 
{data[:500]}")
+    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 = float(os.environ.get("DEEPWIKI_MCP_STREAM_TIMEOUT", "120"))
+    deadline = time.monotonic() + max_seconds
+    timed_out = False
+
+    while True:
+        if time.monotonic() > deadline:
+            timed_out = True
+            break
+        raw_line = response.readline()
+        if not raw_line:
+            break
+
+        line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
+        if line.startswith("data:"):
+            data_lines.append(line[5:].lstrip())
+            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:
+        data = "\n".join(data_lines)
+        seen_payloads.append(data)
+        parsed = parse_json(data)
+        if expected_id is None or parsed.get("id") == expected_id:
+            return parsed
+
+    preview = "\n".join(seen_payloads[-3:])
+    if timed_out:
+        raise McpError(
+            f"DeepWiki MCP stream timed out waiting for response id 
{expected_id} "
+            f"after {max_seconds:.0f}s: {preview[:500]}"
+        )
+    raise McpError(f"DeepWiki MCP stream ended without response id 
{expected_id}: {preview[:500]}")
+
+
+class McpClient:
+    def __init__(self, endpoint: str, protocol_version: str) -> None:
+        self.endpoint = endpoint
+        self.protocol_version = protocol_version
+        self.session_id: str | None = None
+        self.next_id = 1
+
+    def request(self, payload: dict[str, Any], expect_response: bool = True) 
-> dict[str, Any] | None:
+        body = json.dumps(payload).encode("utf-8")
+        headers = {
+            "Accept": "application/json, text/event-stream",
+            "Content-Type": "application/json",
+            "Mcp-Protocol-Version": self.protocol_version,
+            "User-Agent": "hugegraph-ai-deepwiki-skill/0.1.4",
+        }
+        if self.session_id:
+            headers["Mcp-Session-Id"] = self.session_id
+
+        req = urllib.request.Request(self.endpoint, data=body, 
headers=headers, method="POST")
+        try:
+            with urllib.request.urlopen(req, timeout=90) as response:
+                session_id = response.headers.get("Mcp-Session-Id")

Review Comment:
   Follow-up Python 3.9 socket timeout compatibility fix added in 8305e3d.



-- 
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