dendron-mesh 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: dendron-mesh
3
+ Version: 1.0.0
4
+ Summary: Hierarchical Git-Native Knowledge Base & Agent Memory (Zero-Dependency CLI & Stdio MCP Server)
5
+ Author-email: THE HIVE // BSO <diamantenschmiede@proton.me>
6
+ Maintainer: tastenkasperle
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/tastenkasperle/dendron_mesh
9
+ Project-URL: Bug Tracker, https://github.com/tastenkasperle/dendron_mesh/issues
10
+ Project-URL: Repository, https://github.com/tastenkasperle/dendron_mesh.git
11
+ Keywords: mcp,mcp-server,dendron,knowledge-base,agent-memory,wikilinks,markdown,zero-dependency
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Software Development :: Documentation
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # Dendron Mesh
23
+
24
+ > **Hierarchical Git-Native Knowledge Base & Agent Memory (CLI & Stdio MCP Server)**
25
+
26
+ `dendron-mesh` liberates the hierarchical dot-notation knowledge paradigm of [Dendron](https://github.com/dendronhq/dendron) from VS Code extension lock-in into a **zero-dependency, standalone Python engine** built for both humans and autonomous AI agents.
27
+
28
+ ## โœจ Key Features
29
+
30
+ - **Dot-Notation Hierarchy:** Organize notes cleanly as flat Markdown files (`root.md`, `cloud.aws.iam.md`, `agents.memory.decisions.md`) that form a dynamic knowledge tree.
31
+ - **Native Wiki-Links & Backlink Graph:** Automatic extraction of `[[target.note]]` links and bidirectional backlink indexing.
32
+ - **Full-Text Search:** Fast local search across all notes in your vault.
33
+ - **Zero-Dependency:** Pure Python 3.9+ standard library. No Node.js, no VS Code, no external database required.
34
+ - **Dual Interface:** Use it directly as a **Standalone CLI** (`dendron-mesh`) or as a **Stdio MCP Server** (`dendron-mcp`) for Claude Desktop, Cursor, Antigravity, LangGraph, and CrewAI.
35
+
36
+ ## ๐Ÿš€ Installation
37
+
38
+ ```bash
39
+ pip install dendron-mesh
40
+ ```
41
+
42
+ Or run directly from source:
43
+
44
+ ```bash
45
+ git clone https://github.com/tastenkasperle/dendron_mesh.git
46
+ cd dendron_mesh
47
+ pip install -e .
48
+ ```
49
+
50
+ ## ๐Ÿ› ๏ธ CLI Usage
51
+
52
+ ```bash
53
+ # Create a hierarchical note
54
+ dendron-mesh create cloud.aws.iam --title "AWS IAM Best Practices" --body "Use least-privilege roles. See [[security.zero-trust]]."
55
+
56
+ # Read a note
57
+ dendron-mesh read cloud.aws.iam
58
+
59
+ # Visualize the knowledge tree
60
+ dendron-mesh tree
61
+
62
+ # Inspect backlinks for a note
63
+ dendron-mesh backlinks security.zero-trust
64
+
65
+ # Search across the vault
66
+ dendron-mesh search "least-privilege"
67
+ ```
68
+
69
+ ## ๐Ÿค– MCP Server Integration
70
+
71
+ Add `dendron-mesh` to your MCP client configuration (e.g., `claude_desktop_config.json` or `mcp_config.json`):
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "dendron-mesh": {
77
+ "command": "dendron-mcp",
78
+ "args": []
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ ### Exposed MCP Tools
85
+
86
+ - `dendron_create_note` โ€” Create or update a hierarchical note with optional frontmatter & body
87
+ - `dendron_read_note` โ€” Read a note's metadata and markdown content
88
+ - `dendron_get_tree` โ€” Return the hierarchical dot-notation knowledge tree
89
+ - `dendron_get_backlinks` โ€” List all notes referencing a target note via `[[wiki-links]]`
90
+ - `dendron_search` โ€” Full-text search across the vault
91
+
92
+ ## ๐Ÿงช Testing
93
+
94
+ ```bash
95
+ python -m pytest -v
96
+ ```
97
+
98
+ ## ๐Ÿ“„ License
99
+
100
+ MIT ยฉ 2026 [THE HIVE // BSO](https://github.com/tastenkasperle)
@@ -0,0 +1,10 @@
1
+ dendron_mesh-1.0.0.dist-info/licenses/LICENSE,sha256=Gm0sGZwmjkY5K5_INtlFJYMdy3sCHPeqUwxicqSGkoc,1089
2
+ src/cli/main.py,sha256=CLGViRIUp09qDUqAa8Jau0JuqhIBVomxbcusJMtRbBI,3001
3
+ src/core/graph.py,sha256=X5SkO9ytKI4Ti9XXcvFuqFtuR3W-DEy8SevmIfSlAg4,2712
4
+ src/core/vault.py,sha256=GSIdcRaCupJtiloK-GaXYblBF4_t7QiHB-EU0qIj45E,3200
5
+ src/mcp/server.py,sha256=t1xGORINEeP5dwy2FM2QhOFQ8Pp4bHkJWFRMfObkiMs,7018
6
+ dendron_mesh-1.0.0.dist-info/METADATA,sha256=dLR0Gg-ENhbiLFi7w_3b042Pox5STeFs3z58jeZWBZo,3564
7
+ dendron_mesh-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ dendron_mesh-1.0.0.dist-info/entry_points.txt,sha256=PGFiAf3YFjTC3LvUNgIGr8po3B8zXbABwFTLKgwrSys,85
9
+ dendron_mesh-1.0.0.dist-info/top_level.txt,sha256=74rtVfumQlgAPzR5_2CgYN24MB0XARCg0t-gzk6gTrM,4
10
+ dendron_mesh-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ dendron-mcp = src.mcp.server:main
3
+ dendron-mesh = src.cli.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 THE HIVE // BSO (tastenkasperle)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ src
src/cli/main.py ADDED
@@ -0,0 +1,87 @@
1
+ """Command Line Interface for Dendron Mesh."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from src.core.graph import KnowledgeGraph
7
+ from src.core.vault import DendronVault
8
+
9
+
10
+ def format_tree_ascii(tree: dict, prefix: str = "") -> str:
11
+ lines = []
12
+ keys = sorted(list(tree.keys()))
13
+ for idx, key in enumerate(keys):
14
+ is_last = (idx == len(keys) - 1)
15
+ connector = "โ””โ”€โ”€ " if is_last else "โ”œโ”€โ”€ "
16
+ lines.append(f"{prefix}{connector}{key}")
17
+ children = tree[key].get("_children", {})
18
+ if children:
19
+ sub_prefix = prefix + (" " if is_last else "โ”‚ ")
20
+ lines.append(format_tree_ascii(children, sub_prefix))
21
+ return "\n".join(lines)
22
+
23
+
24
+ def main() -> None:
25
+ parser = argparse.ArgumentParser(
26
+ prog="dendron",
27
+ description="Dendron Mesh - Standalone Hierarchical Knowledge Base & Agent Memory"
28
+ )
29
+ parser.add_argument("--vault", default="./vault", help="Path to Dendron vault directory")
30
+
31
+ subparsers = parser.add_subparsers(dest="command", required=True)
32
+
33
+ # Subcommand: create
34
+ create_p = subparsers.add_parser("create", help="Create or update a note")
35
+ create_p.add_argument("id", help="Hierarchical note ID (e.g. dev.python.best-practices)")
36
+ create_p.add_argument("--body", default="", help="Markdown body content")
37
+ create_p.add_argument("--title", help="Optional title")
38
+
39
+ # Subcommand: read
40
+ read_p = subparsers.add_parser("read", help="Read a note")
41
+ read_p.add_argument("id", help="Hierarchical note ID")
42
+
43
+ # Subcommand: tree
44
+ tree_p = subparsers.add_parser("tree", help="Display hierarchy tree")
45
+ tree_p.add_argument("--json", action="store_true", help="Output tree as JSON")
46
+
47
+ # Subcommand: backlinks
48
+ bl_p = subparsers.add_parser("backlinks", help="Find all notes referencing this note")
49
+ bl_p.add_argument("id", help="Target hierarchical note ID")
50
+
51
+ # Subcommand: search
52
+ search_p = subparsers.add_parser("search", help="Search vault notes")
53
+ search_p.add_argument("query", help="Text to search for")
54
+
55
+ args = parser.parse_args()
56
+ vault = DendronVault(args.vault)
57
+ graph = KnowledgeGraph(vault)
58
+
59
+ if args.command == "create":
60
+ res = vault.write_note(args.id, args.body, args.title)
61
+ print(json.dumps(res, indent=2))
62
+
63
+ elif args.command == "read":
64
+ note = vault.read_note(args.id)
65
+ if not note:
66
+ print(f"Error: Note '{args.id}' not found.", file=sys.stderr)
67
+ sys.exit(1)
68
+ print(note["raw"])
69
+
70
+ elif args.command == "tree":
71
+ tree = graph.build_tree()
72
+ if args.json:
73
+ print(json.dumps(tree, indent=2))
74
+ else:
75
+ print(format_tree_ascii(tree))
76
+
77
+ elif args.command == "backlinks":
78
+ bl = graph.get_backlinks(args.id)
79
+ print(json.dumps(bl, indent=2))
80
+
81
+ elif args.command == "search":
82
+ matches = graph.search(args.query)
83
+ print(json.dumps(matches, indent=2))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
src/core/graph.py ADDED
@@ -0,0 +1,81 @@
1
+ """Hierarchical tree builder and wikilink graph indexer."""
2
+
3
+ import re
4
+ from typing import Any, Dict, List, Set
5
+ from src.core.vault import DendronVault
6
+
7
+
8
+ class KnowledgeGraph:
9
+ """Computes hierarchy trees and cross-link graphs across Dendron notes."""
10
+
11
+ WIKILINK_PATTERN = re.compile(r"\[\[([a-zA-Z0-9_\-\.]+)\]\]")
12
+
13
+ def __init__(self, vault: DendronVault) -> None:
14
+ self.vault = vault
15
+
16
+ def extract_links(self, text: str) -> List[str]:
17
+ """Finds all [[target.note]] wikilinks in text."""
18
+ return [match.strip().lower() for match in self.WIKILINK_PATTERN.findall(text)]
19
+
20
+ def get_backlinks(self, target_note_id: str) -> List[Dict[str, str]]:
21
+ """Returns all notes that link to target_note_id."""
22
+ target = target_note_id.strip().lower().removesuffix(".md")
23
+ backlinks = []
24
+
25
+ for note_id in self.vault.list_notes():
26
+ if note_id == target:
27
+ continue
28
+ note = self.vault.read_note(note_id)
29
+ if not note:
30
+ continue
31
+ links = self.extract_links(note["body"])
32
+ if target in links:
33
+ backlinks.append({
34
+ "source": note_id,
35
+ "title": note["frontmatter"].get("title", note_id)
36
+ })
37
+
38
+ return backlinks
39
+
40
+ def build_tree(self) -> Dict[str, Any]:
41
+ """Constructs a nested tree from dot-separated hierarchical IDs."""
42
+ note_ids = self.vault.list_notes()
43
+ tree: Dict[str, Any] = {}
44
+
45
+ for note_id in note_ids:
46
+ parts = note_id.split(".")
47
+ current = tree
48
+ accumulated = []
49
+ for part in parts:
50
+ accumulated.append(part)
51
+ full_key = ".".join(accumulated)
52
+ if part not in current:
53
+ current[part] = {
54
+ "_id": full_key,
55
+ "_children": {}
56
+ }
57
+ current = current[part]["_children"]
58
+
59
+ return tree
60
+
61
+ def search(self, query: str) -> List[Dict[str, Any]]:
62
+ """Searches notes for a text query in ID or body."""
63
+ q = query.lower()
64
+ results = []
65
+
66
+ for note_id in self.vault.list_notes():
67
+ note = self.vault.read_note(note_id)
68
+ if not note:
69
+ continue
70
+
71
+ id_match = q in note_id.lower()
72
+ body_match = q in note["body"].lower()
73
+
74
+ if id_match or body_match:
75
+ results.append({
76
+ "id": note_id,
77
+ "title": note["frontmatter"].get("title", note_id),
78
+ "matched_in": "id" if id_match else "body"
79
+ })
80
+
81
+ return results
src/core/vault.py ADDED
@@ -0,0 +1,96 @@
1
+ """File-system based Dendron hierarchical vault manager."""
2
+
3
+ import os
4
+ import re
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional
8
+
9
+
10
+ class DendronVault:
11
+ """Manages hierarchical Markdown notes with dot-delimited names."""
12
+
13
+ def __init__(self, vault_dir: str) -> None:
14
+ self.vault_dir = Path(vault_dir).resolve()
15
+ self.vault_dir.mkdir(parents=True, exist_ok=True)
16
+ self._ensure_root()
17
+
18
+ def _ensure_root(self) -> None:
19
+ root_file = self.vault_dir / "root.md"
20
+ if not root_file.exists():
21
+ self.write_note("root", "# Root Knowledge Hub\nWelcome to your hierarchical knowledge base.")
22
+
23
+ def _get_note_path(self, note_id: str) -> Path:
24
+ sanitized = re.sub(r"[^a-zA-Z0-9_\-\.]", "_", note_id.strip().lower())
25
+ if not sanitized.endswith(".md"):
26
+ sanitized += ".md"
27
+ return self.vault_dir / sanitized
28
+
29
+ def parse_note(self, content: str) -> Dict[str, Any]:
30
+ """Parses YAML-like frontmatter and body."""
31
+ frontmatter: Dict[str, str] = {}
32
+ body = content
33
+
34
+ if content.startswith("---"):
35
+ parts = content.split("---", 2)
36
+ if len(parts) >= 3:
37
+ fm_raw = parts[1].strip()
38
+ body = parts[2].strip()
39
+ for line in fm_raw.splitlines():
40
+ if ":" in line:
41
+ k, v = line.split(":", 1)
42
+ frontmatter[k.strip()] = v.strip()
43
+
44
+ return {"frontmatter": frontmatter, "body": body}
45
+
46
+ def write_note(self, note_id: str, body: str, title: Optional[str] = None) -> Dict[str, Any]:
47
+ """Creates or updates a hierarchical note with frontmatter."""
48
+ note_id = note_id.strip().lower().removesuffix(".md")
49
+ path = self._get_note_path(note_id)
50
+
51
+ title = title or note_id.replace(".", " / ").title()
52
+ now_iso = datetime.now(timezone.utc).isoformat()
53
+
54
+ frontmatter = (
55
+ f"---\n"
56
+ f"id: {note_id}\n"
57
+ f"title: {title}\n"
58
+ f"updated: {now_iso}\n"
59
+ f"---\n\n"
60
+ )
61
+ full_content = frontmatter + body.strip() + "\n"
62
+
63
+ with open(path, "w", encoding="utf-8") as f:
64
+ f.write(full_content)
65
+
66
+ return {
67
+ "id": note_id,
68
+ "path": str(path),
69
+ "title": title,
70
+ "updated": now_iso
71
+ }
72
+
73
+ def read_note(self, note_id: str) -> Optional[Dict[str, Any]]:
74
+ """Reads a note by its hierarchical ID."""
75
+ path = self._get_note_path(note_id)
76
+ if not path.is_file():
77
+ return None
78
+
79
+ with open(path, "r", encoding="utf-8") as f:
80
+ raw = f.read()
81
+
82
+ parsed = self.parse_note(raw)
83
+ return {
84
+ "id": note_id.removesuffix(".md"),
85
+ "path": str(path),
86
+ "frontmatter": parsed["frontmatter"],
87
+ "body": parsed["body"],
88
+ "raw": raw
89
+ }
90
+
91
+ def list_notes(self) -> List[str]:
92
+ """Returns all note IDs in the vault."""
93
+ notes = []
94
+ for p in self.vault_dir.glob("*.md"):
95
+ notes.append(p.stem)
96
+ return sorted(notes)
src/mcp/server.py ADDED
@@ -0,0 +1,189 @@
1
+ """Model Context Protocol (MCP) server for Dendron Mesh."""
2
+
3
+ import json
4
+ import sys
5
+ from typing import Any, Dict
6
+ from src.core.graph import KnowledgeGraph
7
+ from src.core.vault import DendronVault
8
+
9
+ DEFAULT_VAULT_DIR = "./dendron_vault"
10
+ vault = DendronVault(DEFAULT_VAULT_DIR)
11
+ graph = KnowledgeGraph(vault)
12
+
13
+
14
+ def handle_request(req: Dict[str, Any]) -> Dict[str, Any]:
15
+ method = req.get("method")
16
+ params = req.get("params", {})
17
+ req_id = req.get("id")
18
+
19
+ if method == "initialize":
20
+ return {
21
+ "jsonrpc": "2.0",
22
+ "id": req_id,
23
+ "result": {
24
+ "protocolVersion": "2024-11-05",
25
+ "capabilities": {"tools": {}},
26
+ "serverInfo": {"name": "dendron-mcp", "version": "1.0.0"}
27
+ }
28
+ }
29
+
30
+ elif method in ("notifications/initialized", "initialized") or (isinstance(method, str) and method.startswith("notifications/")) or req_id is None:
31
+ return None
32
+
33
+ elif method == "ping":
34
+ return {
35
+ "jsonrpc": "2.0",
36
+ "id": req_id,
37
+ "result": {}
38
+ }
39
+
40
+ elif method == "tools/list":
41
+ return {
42
+ "jsonrpc": "2.0",
43
+ "id": req_id,
44
+ "result": {
45
+ "tools": [
46
+ {
47
+ "name": "dendron_create_note",
48
+ "description": "Creates or updates a hierarchical markdown note in the Dendron vault.",
49
+ "inputSchema": {
50
+ "type": "object",
51
+ "properties": {
52
+ "id": {"type": "string", "description": "Dot-separated hierarchical ID (e.g. cloud.aws.s3)"},
53
+ "body": {"type": "string", "description": "Markdown body content"},
54
+ "title": {"type": "string", "description": "Optional human-readable title"}
55
+ },
56
+ "required": ["id", "body"]
57
+ }
58
+ },
59
+ {
60
+ "name": "dendron_read_note",
61
+ "description": "Reads a hierarchical note by its ID.",
62
+ "inputSchema": {
63
+ "type": "object",
64
+ "properties": {
65
+ "id": {"type": "string", "description": "Dot-separated hierarchical ID"}
66
+ },
67
+ "required": ["id"]
68
+ }
69
+ },
70
+ {
71
+ "name": "dendron_get_tree",
72
+ "description": "Returns the complete hierarchical knowledge tree of all notes.",
73
+ "inputSchema": {"type": "object", "properties": {}}
74
+ },
75
+ {
76
+ "name": "dendron_get_backlinks",
77
+ "description": "Finds all notes that link to a specific note via [[wikilinks]].",
78
+ "inputSchema": {
79
+ "type": "object",
80
+ "properties": {
81
+ "id": {"type": "string", "description": "Target note ID"}
82
+ },
83
+ "required": ["id"]
84
+ }
85
+ },
86
+ {
87
+ "name": "dendron_search",
88
+ "description": "Searches notes for a specific query string.",
89
+ "inputSchema": {
90
+ "type": "object",
91
+ "properties": {
92
+ "query": {"type": "string", "description": "Search term"}
93
+ },
94
+ "required": ["query"]
95
+ }
96
+ }
97
+ ]
98
+ }
99
+ }
100
+
101
+ elif method == "tools/call":
102
+ tool_name = params.get("name")
103
+ args = params.get("arguments", {})
104
+
105
+ try:
106
+ if tool_name == "dendron_create_note":
107
+ res = vault.write_note(args["id"], args["body"], args.get("title"))
108
+ return {
109
+ "jsonrpc": "2.0",
110
+ "id": req_id,
111
+ "result": {"content": [{"type": "text", "text": json.dumps(res, indent=2)}]}
112
+ }
113
+
114
+ elif tool_name == "dendron_read_note":
115
+ note = vault.read_note(args["id"])
116
+ if not note:
117
+ return {
118
+ "jsonrpc": "2.0",
119
+ "id": req_id,
120
+ "error": {"code": -32001, "message": f"Note {args['id']} not found"}
121
+ }
122
+ return {
123
+ "jsonrpc": "2.0",
124
+ "id": req_id,
125
+ "result": {"content": [{"type": "text", "text": json.dumps(note, indent=2)}]}
126
+ }
127
+
128
+ elif tool_name == "dendron_get_tree":
129
+ tree = graph.build_tree()
130
+ return {
131
+ "jsonrpc": "2.0",
132
+ "id": req_id,
133
+ "result": {"content": [{"type": "text", "text": json.dumps(tree, indent=2)}]}
134
+ }
135
+
136
+ elif tool_name == "dendron_get_backlinks":
137
+ bl = graph.get_backlinks(args["id"])
138
+ return {
139
+ "jsonrpc": "2.0",
140
+ "id": req_id,
141
+ "result": {"content": [{"type": "text", "text": json.dumps(bl, indent=2)}]}
142
+ }
143
+
144
+ elif tool_name == "dendron_search":
145
+ matches = graph.search(args["query"])
146
+ return {
147
+ "jsonrpc": "2.0",
148
+ "id": req_id,
149
+ "result": {"content": [{"type": "text", "text": json.dumps(matches, indent=2)}]}
150
+ }
151
+
152
+ else:
153
+ return {
154
+ "jsonrpc": "2.0",
155
+ "id": req_id,
156
+ "error": {"code": -32601, "message": f"Unknown tool: {tool_name}"}
157
+ }
158
+ except Exception as e:
159
+ return {
160
+ "jsonrpc": "2.0",
161
+ "id": req_id,
162
+ "error": {"code": -32000, "message": str(e)}
163
+ }
164
+
165
+ return {
166
+ "jsonrpc": "2.0",
167
+ "id": req_id,
168
+ "error": {"code": -32601, "message": "Method not found"}
169
+ }
170
+
171
+
172
+ def main() -> None:
173
+ for line in sys.stdin:
174
+ if not line.strip():
175
+ continue
176
+ try:
177
+ req = json.loads(line)
178
+ res = handle_request(req)
179
+ if res is not None:
180
+ sys.stdout.write(json.dumps(res) + "\n")
181
+ sys.stdout.flush()
182
+ except Exception as e:
183
+ err_res = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(e)}}
184
+ sys.stdout.write(json.dumps(err_res) + "\n")
185
+ sys.stdout.flush()
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()