brainforge-mcp 0.1.0__tar.gz
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.
- brainforge_mcp-0.1.0/.gitignore +7 -0
- brainforge_mcp-0.1.0/LICENSE +21 -0
- brainforge_mcp-0.1.0/PKG-INFO +119 -0
- brainforge_mcp-0.1.0/README.md +100 -0
- brainforge_mcp-0.1.0/pyproject.toml +35 -0
- brainforge_mcp-0.1.0/src/llm_wiki_mcp/__init__.py +3 -0
- brainforge_mcp-0.1.0/src/llm_wiki_mcp/graph.py +259 -0
- brainforge_mcp-0.1.0/src/llm_wiki_mcp/server.py +468 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Myungro Lee
|
|
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,119 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: brainforge-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for Karpathy-style LLM Wiki — turn your markdown notes into an AI-powered knowledge graph
|
|
5
|
+
Project-URL: Homepage, https://github.com/mengro1102/brainforge-mcp
|
|
6
|
+
Project-URL: Repository, https://github.com/mengro1102/brainforge-mcp
|
|
7
|
+
Author-email: Myungro Lee <leeroy7321@gmail.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: knowledge-graph,llm,mcp,obsidian,pkm,second-brain,wiki
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: fastmcp>=3.0.0
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# brainforge-mcp
|
|
21
|
+
|
|
22
|
+
> Turn your markdown notes into an AI-powered knowledge graph.
|
|
23
|
+
|
|
24
|
+
Karpathy의 [LLM Wiki 패턴](https://x.com/karpathy/status/1909363262791352494)을 MCP 서버로 구현한 프로젝트입니다. 마크다운 위키를 지식 그래프로 변환하고, 어떤 LLM 클라이언트에서든 탐색·분석할 수 있습니다.
|
|
25
|
+
|
|
26
|
+
## 특징
|
|
27
|
+
|
|
28
|
+
- 🔗 **위키링크 + 인과 관계** 기반 지식 그래프 자동 빌드
|
|
29
|
+
- 🧠 **의미 해석** — 단순 데이터가 아닌 "왜 중요한지"를 분석
|
|
30
|
+
- 📊 **건강 진단** — 위키의 강점/약점/다음 행동을 제안
|
|
31
|
+
- ⚡ **인과 체인 추적** — 개념 간 "왜" 연결을 상류/하류로 분석
|
|
32
|
+
- 🔌 **MCP 표준** — Claude Desktop, Cursor, Kiro, VS Code 등 어디서든 동작
|
|
33
|
+
|
|
34
|
+
## 빠른 시작
|
|
35
|
+
|
|
36
|
+
### 1. 새 위키 초기화
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
uvx brainforge-mcp init ~/my-brain
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### 2. MCP 클라이언트에 등록
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"mcpServers": {
|
|
47
|
+
"wiki": {
|
|
48
|
+
"command": "uvx",
|
|
49
|
+
"args": ["brainforge-mcp", "--vault", "~/my-brain/wiki"]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 3. 채팅에서 사용
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
"LoRA가 내 위키에서 어떤 위치야?" → explain_node
|
|
59
|
+
"메타러닝이랑 Transformer 어떻게 연결돼?" → find_path
|
|
60
|
+
"DiscoRL의 인과 관계 보여줘" → causal_chain
|
|
61
|
+
"위키 상태 어때?" → graph_summary
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## 도구 목록
|
|
65
|
+
|
|
66
|
+
| 도구 | 설명 |
|
|
67
|
+
|------|------|
|
|
68
|
+
| `explain_node` | 노드 프로파일 — 위치 분석, 인과 역할, 연결 맥락, 성장 제안 |
|
|
69
|
+
| `find_path` | 두 개념 간 최단 경로 — 연결 강도 해석, 매개 노드 분석 |
|
|
70
|
+
| `causal_chain` | 인과 네트워크 — 상류/하류 분리, 관계 자연어 해석 |
|
|
71
|
+
| `graph_summary` | 위키 건강 리포트 — 규모 판정, 강점/약점, 행동 제안 |
|
|
72
|
+
| `rebuild_graph` | 그래프 재빌드 — 마크다운 변경 후 갱신 |
|
|
73
|
+
|
|
74
|
+
## 위키 구조
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
my-brain/
|
|
78
|
+
├── raw/ # 불변 원본 (논문, 기사, 메모)
|
|
79
|
+
│ ├── papers/
|
|
80
|
+
│ ├── articles/
|
|
81
|
+
│ ├── transcripts/
|
|
82
|
+
│ └── notes/
|
|
83
|
+
├── wiki/ # AI가 유지하는 위키
|
|
84
|
+
│ ├── sources/ # 원본 요약
|
|
85
|
+
│ ├── concepts/ # 개념 페이지
|
|
86
|
+
│ ├── entities/ # 인물·조직·모델
|
|
87
|
+
│ ├── syntheses/ # 종합·분석
|
|
88
|
+
│ ├── index.md # 목차
|
|
89
|
+
│ └── log.md # 작업 기록
|
|
90
|
+
├── output/ # 블로그, 포트폴리오 등
|
|
91
|
+
└── graph.json # 지식 그래프
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## 인과 관계 표기
|
|
95
|
+
|
|
96
|
+
위키링크(`[[]]`)는 연결만 표현합니다. "왜" 연결되는지는 인과 callout으로 명시합니다:
|
|
97
|
+
|
|
98
|
+
```markdown
|
|
99
|
+
> [!causal] 인과 관계
|
|
100
|
+
> [[메타러닝]] →(가능하게 함)→ [[DiscoRL]]의 RL 규칙 자동 발견
|
|
101
|
+
> 신뢰도: 높음 | 출처: [[discovering-sota-rl-algorithms]]
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
지원하는 관계 유형:
|
|
105
|
+
- `→(가능하게 함)→` / `→(성능 향상)→` / `→(성능 저하)→`
|
|
106
|
+
- `→(기반이 됨)→` / `→(발전시킴)→` / `→(대체함)→`
|
|
107
|
+
- `→(포함함)→` / `→(적용됨)→`
|
|
108
|
+
|
|
109
|
+
## 기존 옵시디언 볼트에 적용
|
|
110
|
+
|
|
111
|
+
이미 옵시디언을 사용 중이라면 `wiki/` 폴더를 볼트 안에 만들고 `--vault` 옵션으로 지정하면 됩니다. 기존 `[[위키링크]]`를 자동으로 파싱합니다.
|
|
112
|
+
|
|
113
|
+
## 라이선스
|
|
114
|
+
|
|
115
|
+
MIT
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
Inspired by [Andrej Karpathy's LLM Wiki idea](https://x.com/karpathy/status/1909363262791352494).
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# brainforge-mcp
|
|
2
|
+
|
|
3
|
+
> Turn your markdown notes into an AI-powered knowledge graph.
|
|
4
|
+
|
|
5
|
+
Karpathy의 [LLM Wiki 패턴](https://x.com/karpathy/status/1909363262791352494)을 MCP 서버로 구현한 프로젝트입니다. 마크다운 위키를 지식 그래프로 변환하고, 어떤 LLM 클라이언트에서든 탐색·분석할 수 있습니다.
|
|
6
|
+
|
|
7
|
+
## 특징
|
|
8
|
+
|
|
9
|
+
- 🔗 **위키링크 + 인과 관계** 기반 지식 그래프 자동 빌드
|
|
10
|
+
- 🧠 **의미 해석** — 단순 데이터가 아닌 "왜 중요한지"를 분석
|
|
11
|
+
- 📊 **건강 진단** — 위키의 강점/약점/다음 행동을 제안
|
|
12
|
+
- ⚡ **인과 체인 추적** — 개념 간 "왜" 연결을 상류/하류로 분석
|
|
13
|
+
- 🔌 **MCP 표준** — Claude Desktop, Cursor, Kiro, VS Code 등 어디서든 동작
|
|
14
|
+
|
|
15
|
+
## 빠른 시작
|
|
16
|
+
|
|
17
|
+
### 1. 새 위키 초기화
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
uvx brainforge-mcp init ~/my-brain
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### 2. MCP 클라이언트에 등록
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"mcpServers": {
|
|
28
|
+
"wiki": {
|
|
29
|
+
"command": "uvx",
|
|
30
|
+
"args": ["brainforge-mcp", "--vault", "~/my-brain/wiki"]
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 3. 채팅에서 사용
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
"LoRA가 내 위키에서 어떤 위치야?" → explain_node
|
|
40
|
+
"메타러닝이랑 Transformer 어떻게 연결돼?" → find_path
|
|
41
|
+
"DiscoRL의 인과 관계 보여줘" → causal_chain
|
|
42
|
+
"위키 상태 어때?" → graph_summary
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 도구 목록
|
|
46
|
+
|
|
47
|
+
| 도구 | 설명 |
|
|
48
|
+
|------|------|
|
|
49
|
+
| `explain_node` | 노드 프로파일 — 위치 분석, 인과 역할, 연결 맥락, 성장 제안 |
|
|
50
|
+
| `find_path` | 두 개념 간 최단 경로 — 연결 강도 해석, 매개 노드 분석 |
|
|
51
|
+
| `causal_chain` | 인과 네트워크 — 상류/하류 분리, 관계 자연어 해석 |
|
|
52
|
+
| `graph_summary` | 위키 건강 리포트 — 규모 판정, 강점/약점, 행동 제안 |
|
|
53
|
+
| `rebuild_graph` | 그래프 재빌드 — 마크다운 변경 후 갱신 |
|
|
54
|
+
|
|
55
|
+
## 위키 구조
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
my-brain/
|
|
59
|
+
├── raw/ # 불변 원본 (논문, 기사, 메모)
|
|
60
|
+
│ ├── papers/
|
|
61
|
+
│ ├── articles/
|
|
62
|
+
│ ├── transcripts/
|
|
63
|
+
│ └── notes/
|
|
64
|
+
├── wiki/ # AI가 유지하는 위키
|
|
65
|
+
│ ├── sources/ # 원본 요약
|
|
66
|
+
│ ├── concepts/ # 개념 페이지
|
|
67
|
+
│ ├── entities/ # 인물·조직·모델
|
|
68
|
+
│ ├── syntheses/ # 종합·분석
|
|
69
|
+
│ ├── index.md # 목차
|
|
70
|
+
│ └── log.md # 작업 기록
|
|
71
|
+
├── output/ # 블로그, 포트폴리오 등
|
|
72
|
+
└── graph.json # 지식 그래프
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## 인과 관계 표기
|
|
76
|
+
|
|
77
|
+
위키링크(`[[]]`)는 연결만 표현합니다. "왜" 연결되는지는 인과 callout으로 명시합니다:
|
|
78
|
+
|
|
79
|
+
```markdown
|
|
80
|
+
> [!causal] 인과 관계
|
|
81
|
+
> [[메타러닝]] →(가능하게 함)→ [[DiscoRL]]의 RL 규칙 자동 발견
|
|
82
|
+
> 신뢰도: 높음 | 출처: [[discovering-sota-rl-algorithms]]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
지원하는 관계 유형:
|
|
86
|
+
- `→(가능하게 함)→` / `→(성능 향상)→` / `→(성능 저하)→`
|
|
87
|
+
- `→(기반이 됨)→` / `→(발전시킴)→` / `→(대체함)→`
|
|
88
|
+
- `→(포함함)→` / `→(적용됨)→`
|
|
89
|
+
|
|
90
|
+
## 기존 옵시디언 볼트에 적용
|
|
91
|
+
|
|
92
|
+
이미 옵시디언을 사용 중이라면 `wiki/` 폴더를 볼트 안에 만들고 `--vault` 옵션으로 지정하면 됩니다. 기존 `[[위키링크]]`를 자동으로 파싱합니다.
|
|
93
|
+
|
|
94
|
+
## 라이선스
|
|
95
|
+
|
|
96
|
+
MIT
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
Inspired by [Andrej Karpathy's LLM Wiki idea](https://x.com/karpathy/status/1909363262791352494).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "brainforge-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "MCP server for Karpathy-style LLM Wiki — turn your markdown notes into an AI-powered knowledge graph"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = {text = "MIT"}
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
authors = [
|
|
9
|
+
{name = "Myungro Lee", email = "leeroy7321@gmail.com"},
|
|
10
|
+
]
|
|
11
|
+
keywords = ["mcp", "knowledge-graph", "wiki", "obsidian", "second-brain", "pkm", "llm"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Text Processing :: Markup :: Markdown",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"fastmcp>=3.0.0",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
brainforge-mcp = "llm_wiki_mcp.server:main"
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/mengro1102/brainforge-mcp"
|
|
28
|
+
Repository = "https://github.com/mengro1102/brainforge-mcp"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["hatchling"]
|
|
32
|
+
build-backend = "hatchling.build"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/llm_wiki_mcp"]
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""위키 마크다운에서 지식 그래프를 빌드하고 조회하는 핵심 엔진."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections import deque
|
|
8
|
+
from datetime import date
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# ── 정규식 ─────────────────────────────────────────────────
|
|
13
|
+
|
|
14
|
+
WIKILINK_RE = re.compile(r"\[\[([^\]|]+)(?:\|[^\]]+)?\]\]")
|
|
15
|
+
|
|
16
|
+
CAUSAL_STRICT_RE = re.compile(
|
|
17
|
+
r"\[\[([^\]]+)\]\]\s*→\(([^)]+)\)→\s*\[\[([^\]]+)\]\]"
|
|
18
|
+
)
|
|
19
|
+
CAUSAL_FLEX_RE = re.compile(
|
|
20
|
+
r"\[\[([^\]]+)\]\][^\n→]*→\(([^)]+)\)→\s*(.+?)(?:\n|$)"
|
|
21
|
+
)
|
|
22
|
+
CAUSAL_REVERSE_RE = re.compile(
|
|
23
|
+
r"([^\n\[]+?)→\(([^)]+)\)→\s*\[\[([^\]]+)\]\]"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---", re.DOTALL)
|
|
27
|
+
YAML_FIELD_RE = re.compile(r"^(\w+):\s*(.+)$", re.MULTILINE)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ── 유틸리티 ───────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
def normalize_to_slug(text: str) -> str:
|
|
33
|
+
s = text.strip().lower()
|
|
34
|
+
s = re.sub(r"[\s_]+", "-", s)
|
|
35
|
+
s = re.sub(r"-+", "-", s).strip("-")
|
|
36
|
+
return s
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_frontmatter(content: str) -> dict:
|
|
40
|
+
match = FRONTMATTER_RE.match(content)
|
|
41
|
+
if not match:
|
|
42
|
+
return {}
|
|
43
|
+
fm = {}
|
|
44
|
+
for m in YAML_FIELD_RE.finditer(match.group(1)):
|
|
45
|
+
key, val = m.group(1), m.group(2).strip().strip('"').strip("'")
|
|
46
|
+
fm[key] = val
|
|
47
|
+
return fm
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_alias_map(nodes: dict) -> dict:
|
|
51
|
+
alias = {}
|
|
52
|
+
for nid, n in nodes.items():
|
|
53
|
+
alias[nid] = nid
|
|
54
|
+
alias[nid.lower()] = nid
|
|
55
|
+
label = n.get("label", "")
|
|
56
|
+
if label:
|
|
57
|
+
alias[label.lower()] = nid
|
|
58
|
+
alias[normalize_to_slug(label)] = nid
|
|
59
|
+
paren = re.search(r"\(([^)]+)\)", label)
|
|
60
|
+
if paren:
|
|
61
|
+
alias[paren.group(1).lower()] = nid
|
|
62
|
+
alias[normalize_to_slug(paren.group(1))] = nid
|
|
63
|
+
korean = label[: label.index("(")].strip()
|
|
64
|
+
alias[korean.lower()] = nid
|
|
65
|
+
return alias
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def resolve_target(target_text: str, alias_map: dict) -> str:
|
|
69
|
+
t = target_text.strip()
|
|
70
|
+
if t in alias_map:
|
|
71
|
+
return alias_map[t]
|
|
72
|
+
if t.lower() in alias_map:
|
|
73
|
+
return alias_map[t.lower()]
|
|
74
|
+
slug = normalize_to_slug(t)
|
|
75
|
+
if slug in alias_map:
|
|
76
|
+
return alias_map[slug]
|
|
77
|
+
return t
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ── 그래프 빌드 ────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
class WikiGraph:
|
|
83
|
+
"""마크다운 위키에서 빌드된 지식 그래프."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, wiki_dir: str | Path):
|
|
86
|
+
self.wiki_dir = Path(wiki_dir)
|
|
87
|
+
self.nodes: dict[str, dict] = {}
|
|
88
|
+
self.links: list[dict] = []
|
|
89
|
+
self._label_to_id: dict[str, str] = {}
|
|
90
|
+
|
|
91
|
+
def build(self) -> None:
|
|
92
|
+
"""wiki_dir의 마크다운을 파싱하여 그래프를 빌드한다."""
|
|
93
|
+
self.nodes, self.links = self._extract(self.wiki_dir)
|
|
94
|
+
self.links = self._deduplicate(self.links)
|
|
95
|
+
self._add_unresolved()
|
|
96
|
+
self._build_label_map()
|
|
97
|
+
|
|
98
|
+
def _build_label_map(self) -> None:
|
|
99
|
+
self._label_to_id = {}
|
|
100
|
+
for n in self.nodes.values():
|
|
101
|
+
self._label_to_id[n.get("label", "").lower()] = n.get("id", "")
|
|
102
|
+
for nid in self.nodes:
|
|
103
|
+
self._label_to_id[nid.lower()] = nid
|
|
104
|
+
|
|
105
|
+
def resolve(self, query: str) -> str | None:
|
|
106
|
+
q = query.lower().strip()
|
|
107
|
+
if q in self._label_to_id:
|
|
108
|
+
return self._label_to_id[q]
|
|
109
|
+
for label, nid in self._label_to_id.items():
|
|
110
|
+
if q in label:
|
|
111
|
+
return nid
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
def degree_map(self) -> dict[str, int]:
|
|
115
|
+
deg: dict[str, int] = {}
|
|
116
|
+
for l in self.links:
|
|
117
|
+
deg[l["source"]] = deg.get(l["source"], 0) + 1
|
|
118
|
+
deg[l["target"]] = deg.get(l["target"], 0) + 1
|
|
119
|
+
return deg
|
|
120
|
+
|
|
121
|
+
def save(self, output_path: Path) -> dict:
|
|
122
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
graph = {
|
|
124
|
+
"nodes": [{"id": k, **v} for k, v in self.nodes.items()],
|
|
125
|
+
"links": self.links,
|
|
126
|
+
"metadata": {
|
|
127
|
+
"total_nodes": len(self.nodes),
|
|
128
|
+
"total_edges": len(self.links),
|
|
129
|
+
"causal_edges": sum(1 for l in self.links if l["type"] == "causal"),
|
|
130
|
+
"wikilink_edges": sum(1 for l in self.links if l["type"] == "wikilink"),
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
output_path.write_text(json.dumps(graph, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
134
|
+
return graph["metadata"]
|
|
135
|
+
|
|
136
|
+
def load(self, graph_path: Path) -> None:
|
|
137
|
+
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
|
138
|
+
self.nodes = {n["id"]: n for n in data["nodes"]}
|
|
139
|
+
self.links = data["links"]
|
|
140
|
+
self._build_label_map()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ── 내부 메서드 ────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
def _extract(self, wiki_dir: Path):
|
|
146
|
+
nodes = {}
|
|
147
|
+
edges = []
|
|
148
|
+
md_files = [f for f in wiki_dir.rglob("*.md") if f.name != ".steering.md"]
|
|
149
|
+
|
|
150
|
+
file_contents = {}
|
|
151
|
+
for md_file in md_files:
|
|
152
|
+
content = md_file.read_text(encoding="utf-8")
|
|
153
|
+
fm = parse_frontmatter(content)
|
|
154
|
+
rel_path = md_file.relative_to(wiki_dir)
|
|
155
|
+
slug = md_file.stem
|
|
156
|
+
parts = rel_path.parts
|
|
157
|
+
category = parts[0] if len(parts) > 1 else "root"
|
|
158
|
+
nodes[slug] = {
|
|
159
|
+
"label": fm.get("title", slug),
|
|
160
|
+
"file": str(rel_path),
|
|
161
|
+
"category": category,
|
|
162
|
+
"tags": fm.get("tags", ""),
|
|
163
|
+
}
|
|
164
|
+
file_contents[slug] = content
|
|
165
|
+
|
|
166
|
+
alias_map = build_alias_map(nodes)
|
|
167
|
+
|
|
168
|
+
for slug, content in file_contents.items():
|
|
169
|
+
# 위키링크
|
|
170
|
+
for m in WIKILINK_RE.finditer(content):
|
|
171
|
+
raw = m.group(1).strip()
|
|
172
|
+
target = resolve_target(raw, alias_map)
|
|
173
|
+
if target != slug:
|
|
174
|
+
edges.append({
|
|
175
|
+
"source": slug, "target": target,
|
|
176
|
+
"type": "wikilink",
|
|
177
|
+
"key": f"wikilink_{slug}_{target}",
|
|
178
|
+
"weight": 1.0,
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
# 인과: 엄격
|
|
182
|
+
for m in CAUSAL_STRICT_RE.finditer(content):
|
|
183
|
+
cause = resolve_target(m.group(1).strip().split("|")[0], alias_map)
|
|
184
|
+
effect = resolve_target(m.group(3).strip().split("|")[0], alias_map)
|
|
185
|
+
edges.append({
|
|
186
|
+
"source": cause, "target": effect,
|
|
187
|
+
"type": "causal", "relation": m.group(2).strip(),
|
|
188
|
+
"key": f"causal_{cause}_{effect}", "weight": 2.0,
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
# 인과: 유연 (좌측 위키링크 + 우측 텍스트)
|
|
192
|
+
for m in CAUSAL_FLEX_RE.finditer(content):
|
|
193
|
+
cause = resolve_target(m.group(1).strip().split("|")[0], alias_map)
|
|
194
|
+
relation = m.group(2).strip()
|
|
195
|
+
right = m.group(3).strip()
|
|
196
|
+
right_links = WIKILINK_RE.findall(right)
|
|
197
|
+
if right_links:
|
|
198
|
+
for rl in right_links:
|
|
199
|
+
effect = resolve_target(rl.strip(), alias_map)
|
|
200
|
+
key = f"causal_{cause}_{effect}"
|
|
201
|
+
if not any(e["key"] == key for e in edges):
|
|
202
|
+
edges.append({
|
|
203
|
+
"source": cause, "target": effect,
|
|
204
|
+
"type": "causal", "relation": relation,
|
|
205
|
+
"key": key, "weight": 2.0,
|
|
206
|
+
})
|
|
207
|
+
else:
|
|
208
|
+
clean = re.sub(r"\s*\([^)]*\)\s*$", "", right).strip()
|
|
209
|
+
if clean and cause:
|
|
210
|
+
effect_slug = normalize_to_slug(clean)[:60]
|
|
211
|
+
if effect_slug:
|
|
212
|
+
effect = resolve_target(effect_slug, alias_map)
|
|
213
|
+
key = f"causal_{cause}_{effect}"
|
|
214
|
+
if not any(e["key"] == key for e in edges):
|
|
215
|
+
edges.append({
|
|
216
|
+
"source": cause, "target": effect,
|
|
217
|
+
"type": "causal", "relation": relation,
|
|
218
|
+
"key": key, "weight": 2.0,
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
# 인과: 역방향 (좌측 텍스트 + 우측 위키링크)
|
|
222
|
+
for m in CAUSAL_REVERSE_RE.finditer(content):
|
|
223
|
+
left = m.group(1).strip()
|
|
224
|
+
relation = m.group(2).strip()
|
|
225
|
+
effect = resolve_target(m.group(3).strip().split("|")[0], alias_map)
|
|
226
|
+
left_links = WIKILINK_RE.findall(left)
|
|
227
|
+
if left_links:
|
|
228
|
+
for ll in left_links:
|
|
229
|
+
cause = resolve_target(ll.strip(), alias_map)
|
|
230
|
+
key = f"causal_{cause}_{effect}"
|
|
231
|
+
if not any(e["key"] == key for e in edges):
|
|
232
|
+
edges.append({
|
|
233
|
+
"source": cause, "target": effect,
|
|
234
|
+
"type": "causal", "relation": relation,
|
|
235
|
+
"key": key, "weight": 2.0,
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
return nodes, edges
|
|
239
|
+
|
|
240
|
+
def _deduplicate(self, edges):
|
|
241
|
+
seen = set()
|
|
242
|
+
unique = []
|
|
243
|
+
for e in edges:
|
|
244
|
+
key = (e["source"], e["target"], e["type"])
|
|
245
|
+
if key not in seen:
|
|
246
|
+
seen.add(key)
|
|
247
|
+
unique.append(e)
|
|
248
|
+
return unique
|
|
249
|
+
|
|
250
|
+
def _add_unresolved(self):
|
|
251
|
+
all_ids = set(self.nodes.keys())
|
|
252
|
+
for e in self.links:
|
|
253
|
+
for key in ("source", "target"):
|
|
254
|
+
if e[key] not in all_ids:
|
|
255
|
+
self.nodes[e[key]] = {
|
|
256
|
+
"label": e[key], "file": None,
|
|
257
|
+
"category": "unresolved", "tags": "",
|
|
258
|
+
}
|
|
259
|
+
all_ids.add(e[key])
|
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""llm-wiki-mcp MCP 서버 — 지식 그래프 기반 위키 탐색 도구."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from collections import deque
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from fastmcp import FastMCP
|
|
12
|
+
|
|
13
|
+
import sys as _sys
|
|
14
|
+
from pathlib import Path as _Path
|
|
15
|
+
# 패키지 미설치 시 src/ 경로를 sys.path에 추가
|
|
16
|
+
_src = str(_Path(__file__).resolve().parent.parent)
|
|
17
|
+
if _src not in _sys.path:
|
|
18
|
+
_sys.path.insert(0, _src)
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
from .graph import WikiGraph
|
|
22
|
+
except ImportError:
|
|
23
|
+
from llm_wiki_mcp.graph import WikiGraph
|
|
24
|
+
|
|
25
|
+
# ── 전역 상태 ──────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
_graph: WikiGraph | None = None
|
|
28
|
+
_wiki_dir: Path | None = None
|
|
29
|
+
_graph_path: Path | None = None
|
|
30
|
+
|
|
31
|
+
mcp = FastMCP(name="LLM Wiki MCP")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _get_graph() -> WikiGraph:
|
|
35
|
+
global _graph
|
|
36
|
+
if _graph is None:
|
|
37
|
+
_graph = WikiGraph(_wiki_dir)
|
|
38
|
+
if _graph_path and _graph_path.exists():
|
|
39
|
+
_graph.load(_graph_path)
|
|
40
|
+
else:
|
|
41
|
+
_graph.build()
|
|
42
|
+
if _graph_path:
|
|
43
|
+
_graph.save(_graph_path)
|
|
44
|
+
return _graph
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _percentile_rank(value: int, all_values: list[int]) -> int:
|
|
48
|
+
if not all_values:
|
|
49
|
+
return 0
|
|
50
|
+
count_below = sum(1 for v in all_values if v < value)
|
|
51
|
+
return round(count_below / len(all_values) * 100)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _relation_meaning(relation: str) -> str:
|
|
55
|
+
meanings = {
|
|
56
|
+
"가능하게 함": "존재/작동을 가능하게 하는 핵심 기반",
|
|
57
|
+
"성능 향상": "성능을 높이는 보강 요인",
|
|
58
|
+
"성능 저하": "성능을 낮추는 제약 요인",
|
|
59
|
+
"기반이 됨": "이론적/기술적 토대",
|
|
60
|
+
"발전시킴": "확장·발전의 원동력",
|
|
61
|
+
"대체함": "기존 방식을 대체하는 새로운 접근",
|
|
62
|
+
"포함함": "상위 개념으로서 포함하는 관계",
|
|
63
|
+
"적용됨": "실제 적용되는 대상",
|
|
64
|
+
}
|
|
65
|
+
return meanings.get(relation, f"'{relation}' 관계")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ── 도구: explain_node ─────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
@mcp.tool
|
|
71
|
+
def explain_node(query: str) -> str:
|
|
72
|
+
"""노드의 상세 정보와 연결 관계를 조회한다.
|
|
73
|
+
노드 이름이나 ID의 일부를 입력하면 해당 노드의 카테고리, 파일 경로,
|
|
74
|
+
태그, 나가는/들어오는 엣지 목록을 반환한다.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
query: 검색할 노드 이름 또는 ID (부분 매칭 지원)
|
|
78
|
+
"""
|
|
79
|
+
g = _get_graph()
|
|
80
|
+
nid = g.resolve(query)
|
|
81
|
+
if not nid:
|
|
82
|
+
return f"노드를 찾을 수 없습니다: {query}"
|
|
83
|
+
|
|
84
|
+
node = g.nodes[nid]
|
|
85
|
+
degree = g.degree_map()
|
|
86
|
+
all_degrees = list(degree.values())
|
|
87
|
+
node_degree = degree.get(nid, 0)
|
|
88
|
+
pct = _percentile_rank(node_degree, all_degrees)
|
|
89
|
+
|
|
90
|
+
outgoing = [l for l in g.links if l["source"] == nid]
|
|
91
|
+
incoming = [l for l in g.links if l["target"] == nid]
|
|
92
|
+
causal_out = [l for l in outgoing if l["type"] == "causal"]
|
|
93
|
+
causal_in = [l for l in incoming if l["type"] == "causal"]
|
|
94
|
+
|
|
95
|
+
cat_dist: dict[str, int] = {}
|
|
96
|
+
for l in outgoing + incoming:
|
|
97
|
+
other = l["target"] if l["source"] == nid else l["source"]
|
|
98
|
+
cat = g.nodes.get(other, {}).get("category", "unresolved")
|
|
99
|
+
cat_dist[cat] = cat_dist.get(cat, 0) + 1
|
|
100
|
+
top_cat = sorted(cat_dist.items(), key=lambda x: x[1], reverse=True)
|
|
101
|
+
|
|
102
|
+
if node_degree == 0:
|
|
103
|
+
role = "고립 노드 — 다른 개념과 연결이 없음"
|
|
104
|
+
elif pct >= 80:
|
|
105
|
+
role = f"핵심 허브 — 연결도 상위 {100 - pct}%, 위키의 중심 개념"
|
|
106
|
+
elif pct >= 50:
|
|
107
|
+
role = f"중간 연결자 — 연결도 상위 {100 - pct}%, 여러 개념을 잇는 역할"
|
|
108
|
+
else:
|
|
109
|
+
role = f"말단 노드 — 연결도 하위 {100 - pct}%, 특정 소스에 종속"
|
|
110
|
+
|
|
111
|
+
if causal_out and causal_in:
|
|
112
|
+
causal_role = f"매개자 — 원인 역할 {len(causal_out)}개, 결과 역할 {len(causal_in)}개"
|
|
113
|
+
elif causal_out:
|
|
114
|
+
causal_role = f"기반 기술 — 다른 {len(causal_out)}개 개념을 가능하게 함"
|
|
115
|
+
elif causal_in:
|
|
116
|
+
causal_role = f"파생 결과 — {len(causal_in)}개 개념으로부터 영향받음"
|
|
117
|
+
else:
|
|
118
|
+
causal_role = "인과 관계 미등록 — 인과 callout 추가 권장"
|
|
119
|
+
|
|
120
|
+
lines = [
|
|
121
|
+
f"## {node['label']}",
|
|
122
|
+
f"카테고리: {node.get('category', '')} | 태그: {node.get('tags', '')}",
|
|
123
|
+
f"파일: {node.get('file', 'N/A')}",
|
|
124
|
+
"", "### 위치 분석",
|
|
125
|
+
f"- 연결도: {node_degree} (상위 {100 - pct}%) → {role}",
|
|
126
|
+
f"- 인과 역할: {causal_role}",
|
|
127
|
+
]
|
|
128
|
+
if top_cat:
|
|
129
|
+
lines.append(f"- 최다 연결 카테고리: {', '.join(f'{c}({n})' for c, n in top_cat[:3])}")
|
|
130
|
+
|
|
131
|
+
if causal_out or causal_in:
|
|
132
|
+
lines.append("\n### 인과 요약")
|
|
133
|
+
for l in causal_out:
|
|
134
|
+
tgt = g.nodes.get(l["target"], {}).get("label", l["target"])
|
|
135
|
+
lines.append(f"- {node['label']} →({l.get('relation', '?')})→ {tgt}")
|
|
136
|
+
for l in causal_in:
|
|
137
|
+
src = g.nodes.get(l["source"], {}).get("label", l["source"])
|
|
138
|
+
lines.append(f"- {src} →({l.get('relation', '?')})→ {node['label']}")
|
|
139
|
+
|
|
140
|
+
lines.append("\n### 연결 맥락")
|
|
141
|
+
for cat_name in ["concepts", "sources", "entities", "syntheses", "unresolved"]:
|
|
142
|
+
cat_links = []
|
|
143
|
+
for l in outgoing + incoming:
|
|
144
|
+
other = l["target"] if l["source"] == nid else l["source"]
|
|
145
|
+
other_node = g.nodes.get(other, {})
|
|
146
|
+
if other_node.get("category", "unresolved") == cat_name:
|
|
147
|
+
cat_links.append(other_node.get("label", other))
|
|
148
|
+
if cat_links:
|
|
149
|
+
unique = list(dict.fromkeys(cat_links))
|
|
150
|
+
lines.append(f"- {cat_name}: {', '.join(unique[:8])}")
|
|
151
|
+
|
|
152
|
+
suggestions = []
|
|
153
|
+
unresolved_neighbors = [
|
|
154
|
+
g.nodes.get(l["target"], {}).get("label", l["target"])
|
|
155
|
+
for l in outgoing if g.nodes.get(l["target"], {}).get("category") == "unresolved"
|
|
156
|
+
]
|
|
157
|
+
if unresolved_neighbors:
|
|
158
|
+
suggestions.append(f"미해결 연결 {len(unresolved_neighbors)}개 → 페이지 생성 권장: {', '.join(unresolved_neighbors[:5])}")
|
|
159
|
+
if not causal_out and not causal_in:
|
|
160
|
+
suggestions.append("인과 관계 callout이 없음 → 관련 소스에서 인과 관계 추출 권장")
|
|
161
|
+
if node_degree <= 2:
|
|
162
|
+
suggestions.append("연결이 적음 → 관련 concepts/entities 페이지와 위키링크 추가 권장")
|
|
163
|
+
if suggestions:
|
|
164
|
+
lines.append("\n### 성장 제안")
|
|
165
|
+
for s in suggestions:
|
|
166
|
+
lines.append(f"- {s}")
|
|
167
|
+
|
|
168
|
+
return "\n".join(lines)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# ── 도구: find_path ────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
@mcp.tool
|
|
174
|
+
def find_path(start: str, end: str) -> str:
|
|
175
|
+
"""두 노드 사이의 최단 경로를 BFS로 탐색한다.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
start: 시작 노드 이름 또는 ID
|
|
179
|
+
end: 도착 노드 이름 또는 ID
|
|
180
|
+
"""
|
|
181
|
+
g = _get_graph()
|
|
182
|
+
start_id = g.resolve(start)
|
|
183
|
+
end_id = g.resolve(end)
|
|
184
|
+
if not start_id:
|
|
185
|
+
return f"시작 노드를 찾을 수 없습니다: {start}"
|
|
186
|
+
if not end_id:
|
|
187
|
+
return f"도착 노드를 찾을 수 없습니다: {end}"
|
|
188
|
+
if start_id == end_id:
|
|
189
|
+
return f"동일한 노드입니다: {g.nodes.get(start_id, {}).get('label', start_id)}"
|
|
190
|
+
|
|
191
|
+
adj: dict[str, list[dict]] = {}
|
|
192
|
+
for l in g.links:
|
|
193
|
+
adj.setdefault(l["source"], []).append(l)
|
|
194
|
+
adj.setdefault(l["target"], []).append(
|
|
195
|
+
{**l, "source": l["target"], "target": l["source"], "_reverse": True}
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
visited = {start_id}
|
|
199
|
+
queue = deque([(start_id, [(start_id, None)])])
|
|
200
|
+
while queue:
|
|
201
|
+
current, path = queue.popleft()
|
|
202
|
+
if current == end_id:
|
|
203
|
+
sl = g.nodes.get(start_id, {}).get("label", start_id)
|
|
204
|
+
el = g.nodes.get(end_id, {}).get("label", end_id)
|
|
205
|
+
hops = len(path) - 1
|
|
206
|
+
if hops == 1: strength = "직접 연결 — 강한 관계"
|
|
207
|
+
elif hops == 2: strength = "1단계 매개 — 중간 개념을 통해 연결"
|
|
208
|
+
elif hops <= 4: strength = f"{hops-1}단계 매개 — 간접적 관계"
|
|
209
|
+
else: strength = f"{hops-1}단계 매개 — 매우 먼 관계"
|
|
210
|
+
has_causal = any(e and e.get("type") == "causal" for _, e in path)
|
|
211
|
+
lines = [f"## {sl} ↔ {el}", f"거리: {hops}홉 | {strength}"]
|
|
212
|
+
if has_causal:
|
|
213
|
+
lines.append("⚡ 경로에 인과 관계 포함 — 논리적 연결이 존재")
|
|
214
|
+
lines.append("\n### 경로")
|
|
215
|
+
for nid, edge in path:
|
|
216
|
+
n = g.nodes.get(nid, {})
|
|
217
|
+
label = n.get("label", nid)
|
|
218
|
+
cat = n.get("category", "")
|
|
219
|
+
if edge:
|
|
220
|
+
rel = edge.get("relation", edge["type"])
|
|
221
|
+
d = "←" if edge.get("_reverse") else "→"
|
|
222
|
+
icon = "🔗" if edge["type"] == "wikilink" else "⚡"
|
|
223
|
+
lines.append(f" {d} {icon} [{rel}] {label} ({cat})")
|
|
224
|
+
else:
|
|
225
|
+
lines.append(f" ● {label} ({cat})")
|
|
226
|
+
intermediates = [g.nodes.get(nid, {}).get("label", nid) for nid, _ in path[1:-1]]
|
|
227
|
+
if intermediates:
|
|
228
|
+
lines.append(f"\n### 매개 노드 해석")
|
|
229
|
+
lines.append(f"- {sl}과 {el}은 {'→'.join(intermediates)}을(를) 통해 연결됨")
|
|
230
|
+
return "\n".join(lines)
|
|
231
|
+
for link in adj.get(current, []):
|
|
232
|
+
neighbor = link["target"]
|
|
233
|
+
if neighbor not in visited:
|
|
234
|
+
visited.add(neighbor)
|
|
235
|
+
queue.append((neighbor, path + [(neighbor, link)]))
|
|
236
|
+
|
|
237
|
+
sl = g.nodes.get(start_id, {}).get("label", start_id)
|
|
238
|
+
el = g.nodes.get(end_id, {}).get("label", end_id)
|
|
239
|
+
return f"## {sl} ↔ {el}\n경로 없음 — 두 개념이 현재 위키에서 연결되지 않음"
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ── 도구: causal_chain ─────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
@mcp.tool
|
|
245
|
+
def causal_chain(query: str) -> str:
|
|
246
|
+
"""특정 노드와 관련된 모든 인과 관계를 조회한다.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
query: 검색할 노드 이름 또는 ID
|
|
250
|
+
"""
|
|
251
|
+
g = _get_graph()
|
|
252
|
+
nid = g.resolve(query)
|
|
253
|
+
if not nid:
|
|
254
|
+
return f"노드를 찾을 수 없습니다: {query}"
|
|
255
|
+
|
|
256
|
+
causal = [l for l in g.links if l["type"] == "causal"]
|
|
257
|
+
upstream = [l for l in causal if l["target"] == nid]
|
|
258
|
+
downstream = [l for l in causal if l["source"] == nid]
|
|
259
|
+
label = g.nodes.get(nid, {}).get("label", nid)
|
|
260
|
+
|
|
261
|
+
if not upstream and not downstream:
|
|
262
|
+
return (f"## {label}의 인과 관계\n\n인과 관계가 등록되지 않음.\n"
|
|
263
|
+
f"→ 관련 소스에서 `> [!causal]` callout 추가 권장")
|
|
264
|
+
|
|
265
|
+
lines = [f"## {label}의 인과 네트워크\n"]
|
|
266
|
+
if upstream:
|
|
267
|
+
lines.append("### 상류 (이 개념을 가능하게 한 것)")
|
|
268
|
+
for l in upstream:
|
|
269
|
+
src = g.nodes.get(l["source"], {}).get("label", l["source"])
|
|
270
|
+
rel = l.get("relation", "?")
|
|
271
|
+
lines.append(f"- {src} →({rel})→ {label}")
|
|
272
|
+
lines.append(f" 해석: {src}이(가) {label}의 {_relation_meaning(rel)}")
|
|
273
|
+
else:
|
|
274
|
+
lines.append("### 상류\n- 없음 → 기반 개념 추적으로 인과 체인 확장 가능")
|
|
275
|
+
|
|
276
|
+
lines.append("")
|
|
277
|
+
if downstream:
|
|
278
|
+
lines.append("### 하류 (이 개념이 영향을 준 것)")
|
|
279
|
+
for l in downstream:
|
|
280
|
+
tgt = g.nodes.get(l["target"], {}).get("label", l["target"])
|
|
281
|
+
rel = l.get("relation", "?")
|
|
282
|
+
lines.append(f"- {label} →({rel})→ {tgt}")
|
|
283
|
+
lines.append(f" 해석: {label}이(가) {tgt}의 {_relation_meaning(rel)}")
|
|
284
|
+
else:
|
|
285
|
+
lines.append("### 하류\n- 없음 → 후속 개념/기술 추적으로 확장 가능")
|
|
286
|
+
|
|
287
|
+
total = len(upstream) + len(downstream)
|
|
288
|
+
lines.append(f"\n### 인과 깊이: {total}단계")
|
|
289
|
+
if total <= 2: lines.append("- 얕은 인과 체인 → 상류/하류 확장 권장")
|
|
290
|
+
elif total <= 5: lines.append("- 적절한 인과 체인 → 핵심 논리 흐름 형성됨")
|
|
291
|
+
else: lines.append("- 풍부한 인과 체인 → 논리 추론 가능")
|
|
292
|
+
return "\n".join(lines)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ── 도구: graph_summary ────────────────────────────────────
|
|
296
|
+
|
|
297
|
+
@mcp.tool
|
|
298
|
+
def graph_summary() -> str:
|
|
299
|
+
"""현재 위키 그래프의 전체 요약 통계를 반환한다."""
|
|
300
|
+
g = _get_graph()
|
|
301
|
+
degree = g.degree_map()
|
|
302
|
+
categories: dict[str, int] = {}
|
|
303
|
+
for n in g.nodes.values():
|
|
304
|
+
cat = n.get("category", "unknown")
|
|
305
|
+
categories[cat] = categories.get(cat, 0) + 1
|
|
306
|
+
|
|
307
|
+
hubs = sorted(degree.items(), key=lambda x: x[1], reverse=True)[:5]
|
|
308
|
+
unresolved = sorted(
|
|
309
|
+
[(nid, degree.get(nid, 0)) for nid, n in g.nodes.items() if n.get("category") == "unresolved"],
|
|
310
|
+
key=lambda x: x[1], reverse=True,
|
|
311
|
+
)
|
|
312
|
+
causal_count = sum(1 for l in g.links if l["type"] == "causal")
|
|
313
|
+
total_nodes = len(g.nodes)
|
|
314
|
+
total_edges = len(g.links)
|
|
315
|
+
resolved = total_nodes - len(unresolved)
|
|
316
|
+
density = round(total_edges / total_nodes, 2) if total_nodes else 0
|
|
317
|
+
causal_ratio = round(causal_count / total_edges * 100, 1) if total_edges else 0
|
|
318
|
+
unresolved_ratio = round(len(unresolved) / total_nodes * 100, 1) if total_nodes else 0
|
|
319
|
+
|
|
320
|
+
if resolved < 20: scale = "초기 단계"
|
|
321
|
+
elif resolved < 50: scale = "성장 단계"
|
|
322
|
+
elif resolved < 100: scale = "확장 단계"
|
|
323
|
+
else: scale = "성숙 단계"
|
|
324
|
+
|
|
325
|
+
lines = [
|
|
326
|
+
"## 위키 건강 리포트\n",
|
|
327
|
+
f"### 규모: {scale}",
|
|
328
|
+
f"- 실제 페이지: {resolved}개 (concepts {categories.get('concepts',0)}, sources {categories.get('sources',0)}, entities {categories.get('entities',0)}, syntheses {categories.get('syntheses',0)})",
|
|
329
|
+
f"- 총 엣지: {total_edges} (밀도: {density} 엣지/노드)",
|
|
330
|
+
]
|
|
331
|
+
if density >= 4.0: lines.append(" → 높은 밀도")
|
|
332
|
+
elif density >= 2.5: lines.append(" → 양호한 밀도")
|
|
333
|
+
else: lines.append(" → 낮은 밀도 — 위키링크 추가 권장")
|
|
334
|
+
|
|
335
|
+
lines.append("\n### 강점")
|
|
336
|
+
if hubs:
|
|
337
|
+
hub_strs = [f"{g.nodes[nid].get('label', nid)}({deg})" for nid, deg in hubs[:3]]
|
|
338
|
+
lines.append(f"- 허브: {', '.join(hub_strs)}")
|
|
339
|
+
if causal_count:
|
|
340
|
+
lines.append(f"- 인과 관계 {causal_count}개 존재")
|
|
341
|
+
|
|
342
|
+
lines.append("\n### 약점")
|
|
343
|
+
if unresolved_ratio > 25:
|
|
344
|
+
lines.append(f"- 미해결 노드 {len(unresolved)}개 ({unresolved_ratio}%)")
|
|
345
|
+
if causal_ratio < 5:
|
|
346
|
+
lines.append(f"- 인과 비율 {causal_ratio}% — callout 추가 권장")
|
|
347
|
+
if not categories.get("syntheses"):
|
|
348
|
+
lines.append("- syntheses/ 0개 — 질의 결과 저장 시작 권장")
|
|
349
|
+
|
|
350
|
+
lines.append("\n### 다음 행동")
|
|
351
|
+
if unresolved:
|
|
352
|
+
lines.append(f"1. 미해결 페이지 생성: {', '.join(f'{nid}({d})' for nid,d in unresolved[:5])}")
|
|
353
|
+
return "\n".join(lines)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# ── 도구: rebuild_graph ────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
@mcp.tool
|
|
359
|
+
def rebuild_graph() -> str:
|
|
360
|
+
"""위키 마크다운을 파싱하여 그래프를 재빌드한다."""
|
|
361
|
+
global _graph
|
|
362
|
+
_graph = WikiGraph(_wiki_dir)
|
|
363
|
+
_graph.build()
|
|
364
|
+
if _graph_path:
|
|
365
|
+
meta = _graph.save(_graph_path)
|
|
366
|
+
return (f"그래프 재빌드 완료: {meta['total_nodes']}노드, "
|
|
367
|
+
f"{meta['total_edges']}엣지 (위키링크 {meta['wikilink_edges']}, "
|
|
368
|
+
f"인과 {meta['causal_edges']})")
|
|
369
|
+
return "그래프 재빌드 완료 (메모리만, 파일 저장 안 함)"
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
# ── init 명령 ──────────────────────────────────────────────
|
|
373
|
+
|
|
374
|
+
INIT_STRUCTURE = {
|
|
375
|
+
"raw/papers/.gitkeep": "",
|
|
376
|
+
"raw/articles/.gitkeep": "",
|
|
377
|
+
"raw/transcripts/.gitkeep": "",
|
|
378
|
+
"raw/notes/.gitkeep": "",
|
|
379
|
+
"raw/code/.gitkeep": "",
|
|
380
|
+
"raw/assets/.gitkeep": "",
|
|
381
|
+
"wiki/sources/.gitkeep": "",
|
|
382
|
+
"wiki/concepts/.gitkeep": "",
|
|
383
|
+
"wiki/entities/.gitkeep": "",
|
|
384
|
+
"wiki/syntheses/.gitkeep": "",
|
|
385
|
+
"wiki/index.md": """---
|
|
386
|
+
title: 위키 인덱스
|
|
387
|
+
created: {date}
|
|
388
|
+
updated: {date}
|
|
389
|
+
---
|
|
390
|
+
|
|
391
|
+
# 위키 인덱스
|
|
392
|
+
|
|
393
|
+
AI가 생성·유지하는 세컨드 브레인 위키.
|
|
394
|
+
|
|
395
|
+
## Sources (원본 요약)
|
|
396
|
+
|
|
397
|
+
## Concepts (개념)
|
|
398
|
+
|
|
399
|
+
## Entities (인물·조직·모델·도구)
|
|
400
|
+
|
|
401
|
+
## Syntheses (종합·분석)
|
|
402
|
+
""",
|
|
403
|
+
"wiki/log.md": """---
|
|
404
|
+
title: 위키 로그
|
|
405
|
+
created: {date}
|
|
406
|
+
updated: {date}
|
|
407
|
+
---
|
|
408
|
+
|
|
409
|
+
# 위키 로그
|
|
410
|
+
|
|
411
|
+
시간순 작업 기록. Append-only.
|
|
412
|
+
|
|
413
|
+
## [{date}] init | 위키 초기화
|
|
414
|
+
|
|
415
|
+
- llm-wiki-mcp init으로 생성됨
|
|
416
|
+
""",
|
|
417
|
+
"output/.gitkeep": "",
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def init_vault(vault_path: str) -> None:
|
|
422
|
+
"""새 LLM Wiki 볼트를 초기화한다."""
|
|
423
|
+
from datetime import date as d
|
|
424
|
+
vault = Path(vault_path).resolve()
|
|
425
|
+
today = d.today().isoformat()
|
|
426
|
+
|
|
427
|
+
if vault.exists() and any(vault.iterdir()):
|
|
428
|
+
print(f"⚠ {vault} 가 비어있지 않습니다. 기존 파일은 유지됩니다.")
|
|
429
|
+
|
|
430
|
+
created = 0
|
|
431
|
+
for rel_path, content in INIT_STRUCTURE.items():
|
|
432
|
+
full = vault / rel_path
|
|
433
|
+
if not full.exists():
|
|
434
|
+
full.parent.mkdir(parents=True, exist_ok=True)
|
|
435
|
+
full.write_text(content.format(date=today), encoding="utf-8")
|
|
436
|
+
created += 1
|
|
437
|
+
|
|
438
|
+
print(f"✅ LLM Wiki 볼트 초기화 완료: {vault}")
|
|
439
|
+
print(f" 생성된 파일: {created}개")
|
|
440
|
+
print(f"\n다음 단계:")
|
|
441
|
+
print(f" 1. raw/ 폴더에 논문, 기사, 메모를 넣으세요")
|
|
442
|
+
print(f" 2. MCP 클라이언트에 등록:")
|
|
443
|
+
print(f' "wiki": {{"command": "uvx", "args": ["llm-wiki-mcp", "--vault", "{vault}"]}}')
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
# ── 엔트리포인트 ───────────────────────────────────────────
|
|
447
|
+
|
|
448
|
+
def main():
|
|
449
|
+
parser = argparse.ArgumentParser(description="LLM Wiki MCP Server")
|
|
450
|
+
parser.add_argument("command", nargs="?", default="serve", choices=["serve", "init"])
|
|
451
|
+
parser.add_argument("--vault", type=str, help="위키 볼트 경로")
|
|
452
|
+
parser.add_argument("--graph", type=str, help="graph.json 저장 경로")
|
|
453
|
+
parser.add_argument("path", nargs="?", help="init 시 볼트 경로")
|
|
454
|
+
args = parser.parse_args()
|
|
455
|
+
|
|
456
|
+
if args.command == "init":
|
|
457
|
+
vault = args.path or args.vault or "."
|
|
458
|
+
init_vault(vault)
|
|
459
|
+
return
|
|
460
|
+
|
|
461
|
+
global _wiki_dir, _graph_path
|
|
462
|
+
_wiki_dir = Path(args.vault) if args.vault else Path("wiki")
|
|
463
|
+
_graph_path = Path(args.graph) if args.graph else _wiki_dir.parent / "graph.json"
|
|
464
|
+
mcp.run()
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
if __name__ == "__main__":
|
|
468
|
+
main()
|