MCP-서버 리팩토링 후 P&ID 추출 테스트전 다른 기능 확인 후 커밋

This commit is contained in:
windpacer
2026-05-04 10:35:13 +09:00
parent a0404b1fee
commit 15c17522c8
304 changed files with 5431877 additions and 0 deletions

View File

@@ -0,0 +1,122 @@
# 🔌 Graph Pipeline Phase 5: MCP 서버 통합 및 시스템 아키텍처 (MCP Integration)
이 문서는 앞서 설계한 1~4단계의 Graph Pipeline을 현재 프로젝트의 **Unified MCP Server (`mcp-server/server.py`)**에 통합하는 방안과 최종 프로그램 구조를 다룹니다. 이를 통해 C# 메인 서버와 LLM, 그리고 도면 분석 엔진이 하나의 생태계에서 유기적으로 동작하게 합니다.
---
## 🏗️ 1. 통합 아키텍처 설계
### 1.1 전체 데이터 흐름 (End-to-End Flow)
`Frontend (UI)` $\rightarrow$ `C# Server (API)` $\rightarrow$ `MCP Server (Python)` $\rightarrow$ `Graph Pipeline Engine` $\rightarrow$ `Experion DB/OPC UA`
1. **요청:** 사용자가 UI에서 "P-101 펌프의 영향도 분석" 요청.
2. **중계:** C# 서버가 `McpClient`를 통해 MCP 서버의 `analyze_pid_impact` 툴 호출.
3. **분석:** MCP 서버는 내부적으로 `NetworkX` 그래프를 로드하여 하류 노드를 계산.
4. **응답:** 분석 결과(노드 리스트)를 JSON으로 반환 $\rightarrow$ C# 서버 $\rightarrow$ UI 하이라이트.
### 1.2 MCP 서버 내 역할 분담
현재 `server.py`는 RAG, NL2SQL, 단순 태그 추출 기능을 가지고 있습니다. 여기에 **Graph Pipeline 전용 도구 세트**를 추가합니다.
| 기존 기능 | 추가될 Graph Pipeline 기능 | 역할 |
|---|---|---|
| `parse_pid_dxf` | `build_pid_graph` | DXF $\rightarrow$ 기하 추출 $\rightarrow$ 위상 그래프 생성 및 저장 |
| `match_pid_tags` | `resolve_graph_tags` | 그래프 맥락을 반영한 지능형 태그 매핑 |
| (신규) | `analyze_pid_impact` | 특정 노드 기준 영향도 분석 (Downstream 탐색) |
| (신규) | `get_graph_topology` | 시각화를 위한 노드-엣지 리스트 반환 |
---
## 💻 2. MCP 서버 통합 구현 가이드
### 2.1 MCP Tool 캡슐화 설계
`mcp-server/server.py`에 다음과 같은 형태로 툴을 추가합니다.
```python
# mcp-server/server.py 에 추가될 내용 (개념 코드)
@mcp.tool()
def build_pid_graph(filepath: str) -> str:
"""
P&ID 도면을 분석하여 위상 그래프를 생성하고 저장합니다.
Phase 1(기하 추출) + Phase 2(위상 모델링) 통합 실행.
"""
# 1. Phase 1: Geometric Extraction
extractor = PidGeometricExtractor(filepath)
geo_data = extractor.extract_all()
# 2. Phase 2: Topology Modeling
builder = PidTopologyBuilder(geo_data)
builder.build_graph()
# 3. 그래프 저장 (GraphML 또는 JSON)
graph_id = os.path.basename(filepath).replace(".dxf", "_graph.json")
nx.write_graphml(builder.G, f"storage/{graph_id}")
return json.dumps({"success": True, "graph_id": graph_id, "nodes": builder.G.number_of_nodes()})
@mcp.tool()
def analyze_pid_impact(graph_id: str, start_node_id: str) -> str:
"""
특정 설비의 장애 시 영향을 받는 하류 설비 리스트를 반환합니다.
"""
# 그래프 로드
G = nx.read_graphml(f"storage/{graph_id}")
# 영향도 분석 (Phase 4 로직)
impacted = nx.descendants(G, start_node_id)
return json.dumps({
"success": True,
"start_node": start_node_id,
"impacted_nodes": list(impacted)
})
```
### 2.2 C# 서버와의 인터페이스 (`McpClient` 활용)
C# 서버는 `src/Infrastructure/Mcp/McpClient.cs`를 통해 위 툴들을 호출합니다.
```csharp
// src/Core/Application/Services/PidGraphService.cs (신규 서비스)
public async Task<ImpactResult> GetImpactAnalysisAsync(string graphId, string nodeId)
{
var request = new McpToolRequest {
ToolName = "analyze_pid_impact",
Arguments = new { graph_id = graphId, start_node_id = nodeId }
};
var jsonResponse = await _mcpClient.CallToolAsync(request);
return JsonSerializer.Deserialize<ImpactResult>(jsonResponse);
}
```
---
## 🛠️ 3. 프로그램 구성 및 배포 전략
### 3.1 디렉토리 구조 확장
```text
mcp-server/
├── server.py # MCP 메인 서버 (툴 정의)
├── pipeline/ # Graph Pipeline 핵심 로직 (Phase 1~4)
│ ├── __init__.py
│ ├── extractor.py # Phase 1: Geometric Extraction
│ ├── topology.py # Phase 2: Topology Modeling
│ ├── mapper.py # Phase 3: Intelligent Mapping
│ └── analyzer.py # Phase 4: Impact Analysis
└── storage/ # 생성된 그래프 파일 (.graphml) 저장소
```
### 3.2 실행 프로세스
1. **MCP 서버 기동:** `python mcp-server/server.py --http` (포트 5001)
2. **C# 서버 기동:** `dotnet run` (포트 5000)
3. **통신:** C# 서버 $\xrightarrow{HTTP/JSON}$ MCP 서버 $\xrightarrow{Python\ Libs}$ 결과 반환.
---
## 🚀 4. 최종 완료 기준 (Definition of Done)
- [ ] `mcp-server/server.py``build_pid_graph`, `analyze_pid_impact` 등 핵심 툴이 정의되었는가?
- [ ] Phase 1~4의 Python 로직이 `mcp-server/pipeline/` 모듈로 구조화되어 통합되었는가?
- [ ] C# `McpClient`를 통해 MCP 서버의 그래프 분석 툴을 호출하고 결과를 수신할 수 있는가?
- [ ] 도면 업로드 $\rightarrow$ 그래프 생성 $\rightarrow$ 태그 매핑 $\rightarrow$ 영향도 분석으로 이어지는 **End-to-End 파이프라인**이 완성되었는가?
- [ ] 모든 과정이 `json_response=True``stateless_http=True` 설정 하에 안정적으로 동작하는가?