factory-graph-mcp 0.1.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.
- factory_graph_mcp/__init__.py +3 -0
- factory_graph_mcp/__main__.py +3 -0
- factory_graph_mcp/graph.py +233 -0
- factory_graph_mcp/sample/connections.csv +25 -0
- factory_graph_mcp/sample/equipment.csv +14 -0
- factory_graph_mcp/server.py +123 -0
- factory_graph_mcp-0.1.0.dist-info/METADATA +211 -0
- factory_graph_mcp-0.1.0.dist-info/RECORD +11 -0
- factory_graph_mcp-0.1.0.dist-info/WHEEL +4 -0
- factory_graph_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- factory_graph_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""설비 연결 그래프 — 설비 대장과 연결 테이블을 읽어 상류를 따라간다.
|
|
2
|
+
|
|
3
|
+
MCP에 의존하지 않는 순수 파이썬이다. 서버(server.py)는 이 모듈을 감싸기만 한다.
|
|
4
|
+
|
|
5
|
+
용어
|
|
6
|
+
상류(upstream) : 어떤 설비에 무언가(전원, 냉각수, 압축공기 …)를 공급하는 쪽
|
|
7
|
+
하류(downstream) : 공급받는 쪽
|
|
8
|
+
연결(edge) : connections.csv 의 한 행. from_id 가 to_id 에 kind 를 공급한다
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import csv
|
|
14
|
+
from collections import deque
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DataError(ValueError):
|
|
20
|
+
"""데이터 파일이 비었거나, 열이 없거나, 없는 설비를 가리킬 때."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Equipment:
|
|
25
|
+
equipment_id: str
|
|
26
|
+
name: str
|
|
27
|
+
type: str
|
|
28
|
+
aliases: tuple[str, ...] = ()
|
|
29
|
+
location: str = ""
|
|
30
|
+
note: str = ""
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict:
|
|
33
|
+
return {
|
|
34
|
+
"equipment_id": self.equipment_id,
|
|
35
|
+
"name": self.name,
|
|
36
|
+
"type": self.type,
|
|
37
|
+
"aliases": list(self.aliases),
|
|
38
|
+
"location": self.location,
|
|
39
|
+
"note": self.note,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Connection:
|
|
45
|
+
from_id: str
|
|
46
|
+
to_id: str
|
|
47
|
+
kind: str
|
|
48
|
+
note: str = ""
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> dict:
|
|
51
|
+
return {"from_id": self.from_id, "to_id": self.to_id, "kind": self.kind, "note": self.note}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class FactoryGraph:
|
|
56
|
+
equipment: dict[str, Equipment]
|
|
57
|
+
connections: list[Connection]
|
|
58
|
+
_up: dict[str, list[Connection]] = field(default_factory=dict, repr=False)
|
|
59
|
+
_down: dict[str, list[Connection]] = field(default_factory=dict, repr=False)
|
|
60
|
+
|
|
61
|
+
def __post_init__(self) -> None:
|
|
62
|
+
unknown = sorted(
|
|
63
|
+
{c.from_id for c in self.connections if c.from_id not in self.equipment}
|
|
64
|
+
| {c.to_id for c in self.connections if c.to_id not in self.equipment}
|
|
65
|
+
)
|
|
66
|
+
if unknown:
|
|
67
|
+
raise DataError(f"connections.csv 가 설비 대장에 없는 설비를 가리킵니다: {', '.join(unknown)}")
|
|
68
|
+
for c in self.connections:
|
|
69
|
+
self._up.setdefault(c.to_id, []).append(c)
|
|
70
|
+
self._down.setdefault(c.from_id, []).append(c)
|
|
71
|
+
|
|
72
|
+
# ── 읽기 ──────────────────────────────────────────────────────────
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_dir(cls, data_dir: str | Path) -> "FactoryGraph":
|
|
75
|
+
d = Path(data_dir)
|
|
76
|
+
eq_rows = _read_csv(d / "equipment.csv", required=("equipment_id", "name", "type"))
|
|
77
|
+
cn_rows = _read_csv(d / "connections.csv", required=("from_id", "to_id", "kind"))
|
|
78
|
+
equipment: dict[str, Equipment] = {}
|
|
79
|
+
for r in eq_rows:
|
|
80
|
+
eid = r["equipment_id"].strip()
|
|
81
|
+
if eid in equipment:
|
|
82
|
+
raise DataError(f"equipment.csv 에 같은 설비 번호가 두 번 있습니다: {eid}")
|
|
83
|
+
aliases = tuple(a.strip() for a in (r.get("aliases") or "").split("|") if a.strip())
|
|
84
|
+
equipment[eid] = Equipment(
|
|
85
|
+
eid, r["name"].strip(), r["type"].strip(), aliases,
|
|
86
|
+
(r.get("location") or "").strip(), (r.get("note") or "").strip(),
|
|
87
|
+
)
|
|
88
|
+
connections = [
|
|
89
|
+
Connection(r["from_id"].strip(), r["to_id"].strip(), r["kind"].strip(), (r.get("note") or "").strip())
|
|
90
|
+
for r in cn_rows
|
|
91
|
+
]
|
|
92
|
+
return cls(equipment, connections)
|
|
93
|
+
|
|
94
|
+
# ── 조회 ──────────────────────────────────────────────────────────
|
|
95
|
+
def find(self, query: str, limit: int = 10) -> list[dict]:
|
|
96
|
+
"""번호, 이름, 별칭, 종류에서 query 를 찾는다. 정확히 맞는 것을 앞에 둔다."""
|
|
97
|
+
q = query.strip().lower()
|
|
98
|
+
if not q:
|
|
99
|
+
return []
|
|
100
|
+
scored = []
|
|
101
|
+
for e in self.equipment.values():
|
|
102
|
+
fields = [e.equipment_id, e.name, *e.aliases]
|
|
103
|
+
texts = [f.lower() for f in fields]
|
|
104
|
+
if q in texts:
|
|
105
|
+
score = 0
|
|
106
|
+
elif any(q in t for t in texts):
|
|
107
|
+
score = 1
|
|
108
|
+
elif q in e.type.lower():
|
|
109
|
+
score = 2
|
|
110
|
+
else:
|
|
111
|
+
continue
|
|
112
|
+
scored.append((score, e.equipment_id, e))
|
|
113
|
+
scored.sort(key=lambda x: (x[0], x[1]))
|
|
114
|
+
return [e.to_dict() for _, _, e in scored[:limit]]
|
|
115
|
+
|
|
116
|
+
def get(self, equipment_id: str) -> dict:
|
|
117
|
+
e = self._require(equipment_id)
|
|
118
|
+
return {
|
|
119
|
+
**e.to_dict(),
|
|
120
|
+
"receives_from": [c.to_dict() for c in self._up.get(e.equipment_id, [])],
|
|
121
|
+
"supplies_to": [c.to_dict() for c in self._down.get(e.equipment_id, [])],
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
def upstream(self, equipment_id: str, max_depth: int = 5, kinds: list[str] | None = None) -> dict:
|
|
125
|
+
"""equipment_id 에서 출발해 공급하는 쪽으로 거슬러 올라간다 (너비 우선 탐색).
|
|
126
|
+
|
|
127
|
+
이미 본 설비는 다시 올라가지 않는다. 서로 주고받는 연결(순환)이 있어도 끝난다.
|
|
128
|
+
결과의 path 는 출발 설비까지 내려오는 길이다: [가장 먼 설비, …, 출발 설비].
|
|
129
|
+
"""
|
|
130
|
+
start = self._require(equipment_id).equipment_id
|
|
131
|
+
kind_set = {k.strip() for k in kinds} if kinds else None
|
|
132
|
+
seen = {start}
|
|
133
|
+
# (설비, 깊이, 출발 설비까지 가는 연결 목록)
|
|
134
|
+
queue: deque[tuple[str, int, list[Connection]]] = deque([(start, 0, [])])
|
|
135
|
+
found: list[dict] = []
|
|
136
|
+
cycles: list[str] = []
|
|
137
|
+
while queue:
|
|
138
|
+
node, depth, via = queue.popleft()
|
|
139
|
+
if depth >= max_depth:
|
|
140
|
+
continue
|
|
141
|
+
for c in self._up.get(node, []):
|
|
142
|
+
if kind_set and c.kind not in kind_set:
|
|
143
|
+
continue
|
|
144
|
+
route = [c, *via]
|
|
145
|
+
if c.from_id in seen:
|
|
146
|
+
if c.from_id == start or any(v.to_id == c.from_id for v in via):
|
|
147
|
+
cycles.append(f"{c.from_id} → {node} ({c.kind})")
|
|
148
|
+
continue
|
|
149
|
+
seen.add(c.from_id)
|
|
150
|
+
found.append({
|
|
151
|
+
**self.equipment[c.from_id].to_dict(),
|
|
152
|
+
"depth": depth + 1,
|
|
153
|
+
"supplies": c.kind,
|
|
154
|
+
"path": _path_text(route),
|
|
155
|
+
})
|
|
156
|
+
queue.append((c.from_id, depth + 1, route))
|
|
157
|
+
return {
|
|
158
|
+
"start": self.equipment[start].to_dict(),
|
|
159
|
+
"max_depth": max_depth,
|
|
160
|
+
"kinds": sorted(kind_set) if kind_set else None,
|
|
161
|
+
"upstream": found,
|
|
162
|
+
"cycles_skipped": cycles,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
def common_upstream(self, equipment_ids: list[str], max_depth: int = 5, kinds: list[str] | None = None) -> dict:
|
|
166
|
+
"""여러 설비에 동시에 이상이 있을 때, 그 설비들이 함께 쓰는 상류를 묶는다.
|
|
167
|
+
|
|
168
|
+
둘 이상이 함께 쓰는 상류만 돌려주고, 많이 겹칠수록·가까울수록 앞에 둔다.
|
|
169
|
+
"""
|
|
170
|
+
ids = list(dict.fromkeys(i.strip() for i in equipment_ids if i.strip()))
|
|
171
|
+
if len(ids) < 2:
|
|
172
|
+
raise DataError("설비를 두 대 이상 주세요. 한 대면 trace_upstream 을 쓰면 됩니다.")
|
|
173
|
+
starts = [self._require(i).equipment_id for i in ids]
|
|
174
|
+
reach: dict[str, dict[str, int]] = {} # 상류 설비 → {출발 설비: 깊이}
|
|
175
|
+
for s in starts:
|
|
176
|
+
for u in self.upstream(s, max_depth, kinds)["upstream"]:
|
|
177
|
+
reach.setdefault(u["equipment_id"], {})[s] = u["depth"]
|
|
178
|
+
shared = []
|
|
179
|
+
for uid, by_start in reach.items():
|
|
180
|
+
if len(by_start) < 2:
|
|
181
|
+
continue
|
|
182
|
+
shared.append({
|
|
183
|
+
**self.equipment[uid].to_dict(),
|
|
184
|
+
"covers": sorted(by_start),
|
|
185
|
+
"covers_all": len(by_start) == len(starts),
|
|
186
|
+
"nearest_depth": min(by_start.values()),
|
|
187
|
+
})
|
|
188
|
+
shared.sort(key=lambda x: (-len(x["covers"]), x["nearest_depth"], x["equipment_id"]))
|
|
189
|
+
return {"equipment_ids": starts, "max_depth": max_depth, "shared_upstream": shared}
|
|
190
|
+
|
|
191
|
+
def summary(self) -> dict:
|
|
192
|
+
kinds: dict[str, int] = {}
|
|
193
|
+
for c in self.connections:
|
|
194
|
+
kinds[c.kind] = kinds.get(c.kind, 0) + 1
|
|
195
|
+
types: dict[str, int] = {}
|
|
196
|
+
for e in self.equipment.values():
|
|
197
|
+
types[e.type] = types.get(e.type, 0) + 1
|
|
198
|
+
return {"equipment": len(self.equipment), "connections": len(self.connections),
|
|
199
|
+
"equipment_types": types, "connection_kinds": kinds}
|
|
200
|
+
|
|
201
|
+
def _require(self, equipment_id: str) -> Equipment:
|
|
202
|
+
key = equipment_id.strip()
|
|
203
|
+
if key in self.equipment:
|
|
204
|
+
return self.equipment[key]
|
|
205
|
+
hits = self.find(key, limit=1)
|
|
206
|
+
if hits and (key in hits[0]["aliases"] or key == hits[0]["name"]):
|
|
207
|
+
return self.equipment[hits[0]["equipment_id"]]
|
|
208
|
+
raise DataError(f"설비를 찾을 수 없습니다: {equipment_id!r}. find_equipment 로 번호를 먼저 찾아보세요.")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _path_text(route: list[Connection]) -> str:
|
|
212
|
+
"""[CT-01→CLT-01, CLT-01→CNC-01] → 'CT-01 —냉각수→ CLT-01 —절삭유 냉각수→ CNC-01'"""
|
|
213
|
+
if not route:
|
|
214
|
+
return ""
|
|
215
|
+
parts = [route[0].from_id]
|
|
216
|
+
for c in route:
|
|
217
|
+
parts.append(f"—{c.kind}→ {c.to_id}")
|
|
218
|
+
return " ".join(parts)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _read_csv(path: Path, required: tuple[str, ...]) -> list[dict]:
|
|
222
|
+
if not path.is_file():
|
|
223
|
+
raise DataError(f"파일이 없습니다: {path}")
|
|
224
|
+
with path.open(encoding="utf-8-sig", newline="") as f:
|
|
225
|
+
reader = csv.DictReader(f)
|
|
226
|
+
cols = set(reader.fieldnames or [])
|
|
227
|
+
missing = [c for c in required if c not in cols]
|
|
228
|
+
if missing:
|
|
229
|
+
raise DataError(f"{path.name} 에 열이 없습니다: {', '.join(missing)}")
|
|
230
|
+
rows = [r for r in reader if any((v or "").strip() for v in r.values())]
|
|
231
|
+
if not rows:
|
|
232
|
+
raise DataError(f"{path.name} 에 행이 없습니다.")
|
|
233
|
+
return rows
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from_id,to_id,kind,note
|
|
2
|
+
TR-1,MCC-1,전원,
|
|
3
|
+
TR-1,MCC-2,전원,
|
|
4
|
+
MCC-1,CNC-01,전원,
|
|
5
|
+
MCC-1,CNC-02,전원,
|
|
6
|
+
MCC-1,CLT-01,전원,
|
|
7
|
+
MCC-2,CNC-03,전원,
|
|
8
|
+
MCC-2,CNC-04,전원,
|
|
9
|
+
MCC-2,CLT-02,전원,
|
|
10
|
+
MCC-2,CMP-01,전원,
|
|
11
|
+
MCC-2,ADR-01,전원,
|
|
12
|
+
MCC-2,P-01,전원,
|
|
13
|
+
CLT-01,CNC-01,절삭유 냉각수,
|
|
14
|
+
CLT-01,CNC-02,절삭유 냉각수,
|
|
15
|
+
CLT-02,CNC-03,절삭유 냉각수,
|
|
16
|
+
CLT-02,CNC-04,절삭유 냉각수,
|
|
17
|
+
CT-01,CLT-01,냉각수,칠러 응축기 냉각
|
|
18
|
+
CT-01,CLT-02,냉각수,칠러 응축기 냉각
|
|
19
|
+
CT-01,CMP-01,냉각수,압축기 후부 냉각기
|
|
20
|
+
P-01,CT-01,순환수,냉각탑 물을 돌린다
|
|
21
|
+
CMP-01,ADR-01,압축공기,
|
|
22
|
+
ADR-01,CNC-01,압축공기,공구 교환·척 클램프
|
|
23
|
+
ADR-01,CNC-02,압축공기,공구 교환·척 클램프
|
|
24
|
+
ADR-01,CNC-03,압축공기,공구 교환·척 클램프
|
|
25
|
+
ADR-01,CNC-04,압축공기,공구 교환·척 클램프
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
equipment_id,name,type,aliases,location,note
|
|
2
|
+
CNC-01,머시닝 센터 1호기,머시닝 센터,1호기|머시닝1,가공동 A열,
|
|
3
|
+
CNC-02,머시닝 센터 2호기,머시닝 센터,2호기|머시닝2,가공동 A열,
|
|
4
|
+
CNC-03,머시닝 센터 3호기,머시닝 센터,3호기|머시닝3,가공동 B열,
|
|
5
|
+
CNC-04,머시닝 센터 4호기,머시닝 센터,4호기|머시닝4,가공동 B열,
|
|
6
|
+
CLT-01,절삭유 칠러 1호,절삭유 칠러,칠러1|1호 칠러,가공동 A열,1·2호기 절삭유를 식힌다
|
|
7
|
+
CLT-02,절삭유 칠러 2호,절삭유 칠러,칠러2|2호 칠러,가공동 B열,3·4호기 절삭유를 식힌다
|
|
8
|
+
CMP-01,공기 압축기 1호,공기 압축기,컴프레서|콤프,유틸리티실,
|
|
9
|
+
ADR-01,에어 드라이어,에어 드라이어,드라이어,유틸리티실,압축공기의 물기를 뺀다
|
|
10
|
+
CT-01,냉각탑,냉각탑,쿨링타워,옥상,칠러와 압축기의 열을 바깥으로 내보낸다
|
|
11
|
+
P-01,냉각탑 순환 펌프,순환 펌프,냉각탑 펌프,옥상,
|
|
12
|
+
TR-1,변압기,변압기,,수전실,
|
|
13
|
+
MCC-1,분전반 1,분전반,1번 분전반,가공동 A열,
|
|
14
|
+
MCC-2,분전반 2,분전반,2번 분전반,유틸리티실,
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""factory-graph-mcp — 설비 연결 그래프를 AI에게 도구로 주는 MCP 서버.
|
|
2
|
+
|
|
3
|
+
실행
|
|
4
|
+
factory-graph-mcp 예제 공장 데이터로 stdio 서버
|
|
5
|
+
factory-graph-mcp --data ./my_plant 내 공장 데이터 폴더 (equipment.csv, connections.csv)
|
|
6
|
+
factory-graph-mcp --http --port 8000 원격 데모용 Streamable HTTP (경로 /mcp)
|
|
7
|
+
|
|
8
|
+
데이터 폴더는 --data 또는 환경 변수 FACTORY_GRAPH_DATA 로 정한다. 둘 다 없으면 예제 공장을 쓴다.
|
|
9
|
+
도구는 모두 읽기 전용이다. 데이터 파일을 바꾸지 않는다.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import os
|
|
16
|
+
from importlib.resources import files
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from mcp.server.mcpserver import MCPServer
|
|
20
|
+
from mcp.types import ToolAnnotations
|
|
21
|
+
|
|
22
|
+
from . import __version__
|
|
23
|
+
from .graph import DataError, FactoryGraph
|
|
24
|
+
|
|
25
|
+
INSTRUCTIONS = """\
|
|
26
|
+
공장 설비가 서로 무엇(전원, 냉각수, 압축공기 …)을 주고받는지 담은 연결 그래프입니다.
|
|
27
|
+
설비에 이상이 생기면 원인은 그 설비가 아니라 상류(그 설비에 무언가를 공급하는 쪽)에 있을 수 있습니다.
|
|
28
|
+
상류 설비는 기준에 닿지 않아 알람이 없을 수도 있습니다.
|
|
29
|
+
|
|
30
|
+
쓰는 순서
|
|
31
|
+
1. 사람이 "1호기", "칠러1"처럼 부르면 find_equipment 로 설비 번호를 찾습니다.
|
|
32
|
+
2. 한 대에 이상이 있으면 trace_upstream 으로 상류를 가까운 것부터 봅니다.
|
|
33
|
+
3. 여러 대에 동시에 이상이 있으면 common_upstream 으로 함께 쓰는 상류를 먼저 봅니다.
|
|
34
|
+
이 도구는 "어디를 봐야 하는지"만 알려 줍니다. 원인을 단정하지 말고, 현장 확인이 필요하다고 함께 안내하세요.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
READ_ONLY = ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def default_data_dir() -> Path:
|
|
41
|
+
env = os.environ.get("FACTORY_GRAPH_DATA")
|
|
42
|
+
return Path(env) if env else Path(str(files("factory_graph_mcp") / "sample"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_server(graph: FactoryGraph) -> MCPServer:
|
|
46
|
+
mcp = MCPServer(
|
|
47
|
+
name="factory-graph",
|
|
48
|
+
title="Factory Graph",
|
|
49
|
+
instructions=INSTRUCTIONS,
|
|
50
|
+
version=__version__,
|
|
51
|
+
website_url="https://github.com/prag-ai/factory-graph-mcp",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
55
|
+
def find_equipment(query: str, limit: int = 10) -> list[dict]:
|
|
56
|
+
"""설비 번호, 이름, 현장에서 부르는 별칭, 설비 종류로 설비를 찾습니다.
|
|
57
|
+
|
|
58
|
+
예: "1호기", "칠러", "CNC-03". 정확히 맞는 것이 앞에 옵니다.
|
|
59
|
+
"""
|
|
60
|
+
return graph.find(query, limit)
|
|
61
|
+
|
|
62
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
63
|
+
def get_equipment(equipment_id: str) -> dict:
|
|
64
|
+
"""설비 한 대의 정보와, 바로 붙은 연결(공급받는 것 receives_from, 공급하는 것 supplies_to)을 돌려줍니다."""
|
|
65
|
+
return graph.get(equipment_id)
|
|
66
|
+
|
|
67
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
68
|
+
def trace_upstream(equipment_id: str, max_depth: int = 5, kinds: list[str] | None = None) -> dict:
|
|
69
|
+
"""설비에서 출발해 공급하는 쪽으로 거슬러 올라가며 상류 설비를 가까운 순서로 돌려줍니다.
|
|
70
|
+
|
|
71
|
+
depth 1 은 바로 공급하는 설비, 2 는 그 설비에 공급하는 설비입니다.
|
|
72
|
+
path 는 상류에서 출발 설비까지 무엇이 흘러오는지 보여 줍니다.
|
|
73
|
+
kinds 로 연결 종류를 좁힐 수 있습니다. 예: ["냉각수", "절삭유 냉각수"].
|
|
74
|
+
서로 주고받는 연결(순환)은 한 번만 따라가고 cycles_skipped 에 적습니다.
|
|
75
|
+
"""
|
|
76
|
+
return graph.upstream(equipment_id, max_depth, kinds)
|
|
77
|
+
|
|
78
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
79
|
+
def common_upstream(equipment_ids: list[str], max_depth: int = 5, kinds: list[str] | None = None) -> dict:
|
|
80
|
+
"""여러 설비에 동시에 이상이 있을 때, 그 설비들이 함께 쓰는 상류 설비를 돌려줍니다.
|
|
81
|
+
|
|
82
|
+
두 대 이상이 함께 쓰는 상류만 나오고, 많은 설비를 덮을수록, 가까울수록 앞에 옵니다.
|
|
83
|
+
covers_all 이 true 이면 준 설비 전부가 그 상류를 씁니다.
|
|
84
|
+
"""
|
|
85
|
+
return graph.common_upstream(equipment_ids, max_depth, kinds)
|
|
86
|
+
|
|
87
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
88
|
+
def describe_plant() -> dict:
|
|
89
|
+
"""불러온 공장 데이터의 규모를 돌려줍니다: 설비 수, 연결 수, 설비 종류별 대수, 연결 종류별 개수."""
|
|
90
|
+
return graph.summary()
|
|
91
|
+
|
|
92
|
+
return mcp
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def main(argv: list[str] | None = None) -> None:
|
|
96
|
+
p = argparse.ArgumentParser(prog="factory-graph-mcp", description="설비 연결 그래프 MCP 서버")
|
|
97
|
+
p.add_argument("--data", type=Path, default=None, help="equipment.csv, connections.csv 가 든 폴더")
|
|
98
|
+
p.add_argument("--http", action="store_true", help="Streamable HTTP 로 띄운다 (기본은 stdio)")
|
|
99
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
100
|
+
p.add_argument("--port", type=int, default=8000)
|
|
101
|
+
p.add_argument("--check", action="store_true", help="데이터만 읽어 요약을 찍고 끝낸다")
|
|
102
|
+
args = p.parse_args(argv)
|
|
103
|
+
|
|
104
|
+
data_dir = args.data or default_data_dir()
|
|
105
|
+
try:
|
|
106
|
+
graph = FactoryGraph.from_dir(data_dir)
|
|
107
|
+
except DataError as e:
|
|
108
|
+
raise SystemExit(f"데이터를 읽지 못했습니다 ({data_dir}): {e}")
|
|
109
|
+
|
|
110
|
+
if args.check:
|
|
111
|
+
import json
|
|
112
|
+
print(json.dumps(graph.summary(), ensure_ascii=False, indent=2))
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
server = build_server(graph)
|
|
116
|
+
if args.http:
|
|
117
|
+
server.run("streamable-http", host=args.host, port=args.port, stateless_http=True)
|
|
118
|
+
else:
|
|
119
|
+
server.run("stdio")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
if __name__ == "__main__":
|
|
123
|
+
main()
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: factory-graph-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server that traces upstream equipment in a factory — find where to look first when a machine alarms.
|
|
5
|
+
Project-URL: Homepage, https://github.com/prag-ai/factory-graph-mcp
|
|
6
|
+
Project-URL: Blog, https://prag-ai.com
|
|
7
|
+
Author: prag-ai
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: factory,maintenance,manufacturing,mcp,root-cause,smart-factory
|
|
11
|
+
Classifier: Intended Audience :: Manufacturing
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: mcp<3,>=2.3
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# factory-graph-mcp
|
|
21
|
+
|
|
22
|
+
**설비에 알람이 떴을 때, 어디부터 봐야 하는지 짚어 주는 MCP 서버입니다.**
|
|
23
|
+
|
|
24
|
+

|
|
25
|
+
|
|
26
|
+
공장 설비는 혼자 돌지 않습니다. 가공기는 칠러에서 절삭유 냉각수를, 압축기에서 압축공기를, 분전반에서 전기를 받습니다. 그래서 알람이 뜬 설비가 원인이 아닐 때가 많습니다. 원인은 그 설비에 무언가를 공급하는 **상류** 설비에 있고, 상류 설비는 아직 자기 기준에 닿지 않아 **알람이 없을 수도** 있습니다.
|
|
27
|
+
|
|
28
|
+
`factory-graph-mcp`는 설비 대장과 연결 테이블(CSV 두 개)을 읽어, AI가 이 연결을 따라 올라갈 수 있게 도구로 줍니다. Claude, Codex, Cursor처럼 MCP를 지원하는 AI 앱에 붙이면 이렇게 물어볼 수 있습니다.
|
|
29
|
+
|
|
30
|
+
> 1호기랑 2호기에 동시에 스핀들 온도 알람이 떴어. 어디부터 봐야 해?
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
common_upstream(["1호기", "2호기"], kinds=["절삭유 냉각수", "냉각수", "순환수"])
|
|
34
|
+
|
|
35
|
+
CLT-01 절삭유 칠러 1호 두 대 모두 공급 1단계 위
|
|
36
|
+
CT-01 냉각탑 두 대 모두 공급 2단계 위
|
|
37
|
+
P-01 냉각탑 순환 펌프 두 대 모두 공급 3단계 위
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
두 대가 함께 쓰는 냉각 계통은 칠러 1호, 냉각탑, 순환 펌프입니다. 3·4호기가 멀쩡하다면 3·4호기와 함께 쓰는 냉각탑보다 **1·2호기만 쓰는 칠러 1호**를 먼저 보는 것이 맞습니다. 이런 판단은 AI가 이 결과와 현장 상황을 보고 합니다. 이 서버는 연결을 빠짐없이, 틀리지 않게 따라가는 일만 맡습니다.
|
|
41
|
+
|
|
42
|
+
### 알람이 없는 상류
|
|
43
|
+
|
|
44
|
+
상류 설비는 고장 나기 전에 먼저 약해집니다. 칠러의 응축기에 먼지가 끼면 열을 덜 내보내서 냉각수 온도가 천천히 오르지만, 칠러 자기 알람 기준에 닿기 전까지는 조용합니다. 그사이 기준이 더 촘촘한 가공기가 먼저 알람을 띄웁니다. 알람 목록만 보면 칠러는 보이지 않습니다.
|
|
45
|
+
|
|
46
|
+

|
|
47
|
+
|
|
48
|
+
그래서 알람이 뜬 설비만이 아니라, 그 설비에 무언가를 보내는 설비를 함께 봐야 합니다. 대개 아래 같은 공용 설비입니다.
|
|
49
|
+
|
|
50
|
+

|
|
51
|
+
|
|
52
|
+
## 도구
|
|
53
|
+
|
|
54
|
+
모든 도구는 읽기 전용입니다. 데이터 파일을 바꾸지 않습니다.
|
|
55
|
+
|
|
56
|
+
| 도구 | 하는 일 |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `find_equipment` | "1호기", "칠러1"처럼 현장에서 부르는 이름으로 설비 번호를 찾는다 |
|
|
59
|
+
| `get_equipment` | 설비 한 대의 정보와 바로 붙은 연결(받는 것, 주는 것) |
|
|
60
|
+
| `trace_upstream` | 한 설비에서 상류를 가까운 순서로 따라간다. 무엇이 어떤 길로 흘러오는지(`path`)까지 |
|
|
61
|
+
| `common_upstream` | 여러 설비에 동시에 이상이 있을 때 함께 쓰는 상류를 묶는다 |
|
|
62
|
+
| `describe_plant` | 불러온 공장의 규모(설비 수, 연결 종류) |
|
|
63
|
+
|
|
64
|
+
서로 주고받는 연결(예: 기계가 온도 조절기에 전원을 주고, 조절기가 기계에 온수를 주는 경우)이 있어도 끝없이 돌지 않습니다. 한 번 본 설비는 다시 따라가지 않고 `cycles_skipped`에 적어 둡니다.
|
|
65
|
+
|
|
66
|
+
### 한국어로 만든 첫 제조 설비 MCP 서버
|
|
67
|
+
|
|
68
|
+
**2026년 11월 24일 기준, 한국어로 만든 첫 제조 설비 MCP 서버입니다.** 해외에는 설비 값을 읽는 OPC UA 서버나 MES 연동 서버가 있지만, 한국어로 된 것은 없었습니다.
|
|
69
|
+
|
|
70
|
+
현장에서는 설비 번호 대신 "1호기", "칠러2", "콤프"라고 부릅니다. 설비 대장의 `aliases` 열에 이런 이름을 적어 두면 AI가 그 말로 설비를 찾습니다. 설비 이름, 연결 종류(전원, 냉각수, 압축공기 …), 도구 안내문까지 한국어로 만들었습니다. 다른 언어로 적은 데이터도 그대로 읽습니다.
|
|
71
|
+
|
|
72
|
+
설비끼리 무엇을 주고받는지, 현장에서 설비를 뭐라고 부르는지까지 담은 한국어 공장 데이터는 공개된 것을 찾기 어렵습니다. **그래서 바로 돌려 볼 수 있는 한국어 예제 공장 데이터를 함께 공개합니다.** MIT 라이선스이니 자기 공장 데이터를 만들 때 틀로 가져다 쓰셔도 됩니다.
|
|
73
|
+
|
|
74
|
+
## 설치와 실행
|
|
75
|
+
|
|
76
|
+
[uv](https://docs.astral.sh/uv/)가 있으면 설치 없이 바로 실행됩니다.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
uvx --from git+https://github.com/prag-ai/factory-graph-mcp factory-graph-mcp --check
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`--check`는 데이터를 읽어 요약만 찍고 끝냅니다. 처음에는 들어 있는 예제 공장(CNC 가공 공장, 설비 13대)을 읽습니다.
|
|
83
|
+
|
|
84
|
+
### Claude Desktop
|
|
85
|
+
|
|
86
|
+
`claude_desktop_config.json`에 넣습니다.
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{
|
|
90
|
+
"mcpServers": {
|
|
91
|
+
"factory-graph": {
|
|
92
|
+
"command": "uvx",
|
|
93
|
+
"args": ["--from", "git+https://github.com/prag-ai/factory-graph-mcp", "factory-graph-mcp"]
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
내 공장 데이터를 쓰려면 `args` 끝에 `"--data", "/내/공장/폴더"`를 붙입니다.
|
|
100
|
+
|
|
101
|
+
### Claude Code
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
claude mcp add factory-graph -- uvx --from git+https://github.com/prag-ai/factory-graph-mcp factory-graph-mcp
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Codex (OpenAI)
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
codex mcp add factory-graph -- uvx --from git+https://github.com/prag-ai/factory-graph-mcp factory-graph-mcp
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
명령 대신 `~/.codex/config.toml`에 직접 적어도 됩니다.
|
|
114
|
+
|
|
115
|
+
```toml
|
|
116
|
+
[mcp_servers.factory-graph]
|
|
117
|
+
command = "uvx"
|
|
118
|
+
args = ["--from", "git+https://github.com/prag-ai/factory-graph-mcp", "factory-graph-mcp"]
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Cursor
|
|
122
|
+
|
|
123
|
+
`.cursor/mcp.json`(프로젝트) 또는 `~/.cursor/mcp.json`(전체)에 Claude Desktop과 같은 형식으로 넣습니다.
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{
|
|
127
|
+
"mcpServers": {
|
|
128
|
+
"factory-graph": {
|
|
129
|
+
"command": "uvx",
|
|
130
|
+
"args": ["--from", "git+https://github.com/prag-ai/factory-graph-mcp", "factory-graph-mcp"]
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### 원격(HTTP)으로 띄우기
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
factory-graph-mcp --http --host 0.0.0.0 --port 8000 # 주소: http://<서버>:8000/mcp
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## 내 공장 데이터로 쓰기
|
|
143
|
+
|
|
144
|
+
CSV 두 개가 든 폴더를 `--data`로 주거나 환경 변수 `FACTORY_GRAPH_DATA`에 적습니다. 엑셀에서 「CSV UTF-8」로 저장하면 됩니다.
|
|
145
|
+
|
|
146
|
+
**equipment.csv** — 설비 대장. 한 대에 한 행.
|
|
147
|
+
|
|
148
|
+
| 열 | 필수 | 뜻 | 예 |
|
|
149
|
+
|---|---|---|---|
|
|
150
|
+
| `equipment_id` | ● | 설비 번호 | `CNC-01` |
|
|
151
|
+
| `name` | ● | 이름 | 머시닝 센터 1호기 |
|
|
152
|
+
| `type` | ● | 설비 종류 | 머시닝 센터 |
|
|
153
|
+
| `aliases` | | 현장에서 부르는 이름. `\|`로 여러 개 | `1호기\|머시닝1` |
|
|
154
|
+
| `location` | | 위치 | 가공동 A열 |
|
|
155
|
+
| `note` | | 메모 | |
|
|
156
|
+
|
|
157
|
+
**connections.csv** — 연결 테이블. 한 행이 화살표 하나입니다.
|
|
158
|
+
|
|
159
|
+
| 열 | 필수 | 뜻 | 예 |
|
|
160
|
+
|---|---|---|---|
|
|
161
|
+
| `from_id` | ● | 공급하는 설비 | `CLT-01` |
|
|
162
|
+
| `to_id` | ● | 공급받는 설비 | `CNC-01` |
|
|
163
|
+
| `kind` | ● | 무엇을 공급하는가 | 절삭유 냉각수 |
|
|
164
|
+
| `note` | | 메모 | |
|
|
165
|
+
|
|
166
|
+
`kind`는 자유롭게 적어도 됩니다(전원, 냉각수, 압축공기, 원료, 스팀 …). 같은 것은 같은 말로 적어야 `kinds`로 좁힐 때 걸립니다. 연결이 설비 대장에 없는 번호를 가리키면 서버가 어느 번호인지 알려 주고 시작하지 않습니다.
|
|
167
|
+
|
|
168
|
+
예제 데이터: [`src/factory_graph_mcp/sample/`](src/factory_graph_mcp/sample/)
|
|
169
|
+
|
|
170
|
+
## 이 서버가 하지 않는 일
|
|
171
|
+
|
|
172
|
+
- **원인을 정하지 않습니다.** 어디를 봐야 하는지만 알려 줍니다. 원인 판단과 조치 결정은 현장 확인을 거쳐 사람이 합니다.
|
|
173
|
+
- **설비를 조작하지 않습니다.** 설비나 PLC에 연결하지 않고 CSV만 읽습니다.
|
|
174
|
+
- **센서 값과 알람 이력은 읽지 않습니다.** 연결 구조만 다룹니다. 실시간 값을 읽는 일은 OPC UA 같은 다른 MCP 서버와 함께 쓰면 됩니다.
|
|
175
|
+
|
|
176
|
+
## 개발
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
uv venv && uv pip install -e ".[dev]"
|
|
180
|
+
.venv/bin/python -m pytest
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## 만든 곳
|
|
184
|
+
|
|
185
|
+
[prag-ai](https://prag-ai.com) — 제조 현장의 설비 장애 진단을 AI 에이전트로 만드는 일을 합니다.
|
|
186
|
+
|
|
187
|
+
이 저장소는 그 작업의 한 조각입니다. 전체 진단 시스템은 여러 에이전트가 나눠 맡아, 장애 신고 한 건을 받아 원인 후보와 조치안을 내고 재가동 승인 요청까지 갑니다. 이 시스템은 처음부터 한국어 데이터로 만들고 검증했습니다. 센서와 알람 기록, 정비 기록, 설비 매뉴얼, 사내 메일과 메신저, 현장 사진, 전기·배관 도면이 모두 한국어입니다.
|
|
188
|
+
|
|
189
|
+
진단 시스템과 우리 공장 데이터 적용은 [prag-ai.com](https://prag-ai.com)으로, 사내교육은 macro@prag-ai.com 으로 문의해 주세요.
|
|
190
|
+
|
|
191
|
+
## License
|
|
192
|
+
|
|
193
|
+
MIT
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
## English
|
|
198
|
+
|
|
199
|
+
**An MCP server that tells an AI where to look first when a machine alarms.**
|
|
200
|
+
|
|
201
|
+
Machines in a plant depend on each other: a machining center gets coolant from a chiller, compressed air from a compressor, and power from a panel. The machine that raises the alarm is often not the cause. The cause sits **upstream**, and the upstream machine may not have alarmed yet.
|
|
202
|
+
|
|
203
|
+
`factory-graph-mcp` reads two CSV files (an equipment list and a connection table) and gives an AI read-only tools to walk those connections: `find_equipment`, `get_equipment`, `trace_upstream`, `common_upstream`, `describe_plant`. Cycles are handled. A sample CNC machining plant (13 machines) is bundled.
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
uvx --from git+https://github.com/prag-ai/factory-graph-mcp factory-graph-mcp --check
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Korean-first — as of November 24, 2026, the first Korean-language manufacturing MCP server. Equipment names, shop-floor aliases ("1호기", "콤프"), tool descriptions, and the sample plant are in Korean; data in any other language works too. Use your own data with `--data <folder>` (columns are described above). It does not diagnose, control equipment, or read live sensor data — it narrows down where to look.
|
|
210
|
+
|
|
211
|
+
<!-- mcp-name: io.github.prag-ai/factory-graph-mcp -->
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
factory_graph_mcp/__init__.py,sha256=YWUiyw5Q4KZpg_4oAoCbsaio7Zm2AZ2UJW9Z8FsHnPI,65
|
|
2
|
+
factory_graph_mcp/__main__.py,sha256=3dYKHfmWsrdExFlTFlcR5a_icR9fAkn06Yh14TQkEd8,33
|
|
3
|
+
factory_graph_mcp/graph.py,sha256=j_oqqr311KUnvJ9zc_SZLmaclpePfh3V9-L1mOH8vb0,10051
|
|
4
|
+
factory_graph_mcp/server.py,sha256=M09YuwXvPbKQ6M79j2CTlYH02JTrZJ74pO_nhO7Rgtg,5635
|
|
5
|
+
factory_graph_mcp/sample/connections.csv,sha256=ic9vnyUGbRcKj20neaTqL6XcbV5rNSXyV_Wp52SGa4U,833
|
|
6
|
+
factory_graph_mcp/sample/equipment.csv,sha256=RPoTPw5hYvK3u8LG-WRVN3p9cjuFlknlZnhd2Ke-1-s,1129
|
|
7
|
+
factory_graph_mcp-0.1.0.dist-info/METADATA,sha256=aHwc_GlMM8k9_GHp4K-_yPo73YBLbIoHsTADMWoSWSI,11050
|
|
8
|
+
factory_graph_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
factory_graph_mcp-0.1.0.dist-info/entry_points.txt,sha256=UukK46Orhq1RlpYALcR0eo8QhFHrUs-rbYcWy3MY7gs,68
|
|
10
|
+
factory_graph_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=I0yfwUlwdzMhr0iX_tr6eY0pfBOOzPeaaAR78VM8GHQ,1064
|
|
11
|
+
factory_graph_mcp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 prag-ai
|
|
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.
|