Copilot commented on code in PR #355: URL: https://github.com/apache/hugegraph-ai/pull/355#discussion_r3333577366
########## 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: The stream “timeout” logic won’t reliably work because `response.readline()` is a blocking call; if the server stalls without sending a newline, the code can block inside `readline()` and never re-check `deadline`. Consider setting a short socket read timeout (and looping) or using non-blocking IO/select so the monotonic deadline is actually enforced. ########## 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: `urlopen(..., timeout=90)` can terminate SSE reads earlier than `DEEPWIKI_MCP_STREAM_TIMEOUT` (default 120s above), and may do so via a socket timeout path that isn’t wrapped as an `McpError`. It’d be more reliable to derive the `urlopen` timeout from the same env/config used for streaming, and explicitly catch socket timeouts to raise a clear MCP timeout error. ########## 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", Review Comment: The client version string is hardcoded in multiple places, which makes it easy for the MCP client’s reported version to drift from the plugin manifests’ version. Consider centralizing the version (single constant, or reading from a package/manifest) and reusing it for both `User-Agent` and `clientInfo.version`. ########## 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) Review Comment: Using a fixed `*.tmp` name is prone to race conditions if two processes refresh the cache concurrently (they’ll overwrite the same temp file). Prefer creating a unique temp file in the same directory (e.g., PID/UUID-based) and then `replace()` it, so concurrent refreshes don’t corrupt each other’s writes. ########## 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") + if session_id: + self.session_id = session_id + if not expect_response: + return None + content_type = response.headers.get("Content-Type", "") + if "text/event-stream" in content_type: + parsed = read_sse_response(response, payload.get("id")) + else: + text = response.read().decode("utf-8", errors="replace") + if not text.strip(): + raise McpError("DeepWiki MCP returned an empty response.") + parsed = parse_json(text) + except urllib.error.HTTPError as exc: + details = exc.read().decode("utf-8", errors="replace") + raise McpError(f"DeepWiki MCP HTTP {exc.code}: {details}") from exc + except urllib.error.URLError as exc: + raise McpError(f"Could not reach DeepWiki MCP endpoint: {exc.reason}") from exc + + if "error" in parsed: + raise McpError(f"DeepWiki MCP error: {json.dumps(parsed['error'], ensure_ascii=False)}") + return parsed + + def rpc(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]: + payload: dict[str, Any] = {"jsonrpc": "2.0", "id": self.next_id, "method": method} + self.next_id += 1 + if params is not None: + payload["params"] = params + result = self.request(payload) + if result is None: + raise McpError(f"DeepWiki MCP returned no response for {method}.") + return result + + def notify(self, method: str, params: dict[str, Any] | None = None) -> None: + payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method} + if params is not None: + payload["params"] = params + self.request(payload, expect_response=False) + + def initialize(self) -> None: + self.rpc( + "initialize", + { + "protocolVersion": self.protocol_version, + "capabilities": {}, + "clientInfo": {"name": "hugegraph-ai-deepwiki-skill", "version": "0.1.4"}, Review Comment: The client version string is hardcoded in multiple places, which makes it easy for the MCP client’s reported version to drift from the plugin manifests’ version. Consider centralizing the version (single constant, or reading from a package/manifest) and reusing it for both `User-Agent` and `clientInfo.version`. -- 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]
