JDWorlds/AI-Battery-Analysis-System-MCP
If you are the rightful owner of AI-Battery-Analysis-System-MCP and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
The AI Battery Analysis System MCP is a sophisticated platform leveraging FastMCP for advanced battery data analysis, recipe generation/validation, and pattern compression.
AI Battery Analysis System MCP
FastMCP 기반의 AI 배터리 분석 시스템으로, Model Context Protocol (MCP)을 통해 배터리 데이터 분석, 레시피 생성/검증, 패턴 압축 등의 고급 기능을 제공합니다.
📋 목차
🎯 시스템 개요
이 시스템은 3가지 핵심 도메인으로 구성되어 있습니다:
1️⃣ 배터리 데이터 분석 (Battery Data Analysis)
- AI 기반 분석 계획 자동 생성
- 대용량 배터리 테스트 데이터 조회 및 시각화
- 프론트엔드 Agent 쿼리 통합 처리
2️⃣ 배터리 레시피 생성 & 검증 (Recipe Generation & Validation)
- 모듈형 레시피 시스템 (FORMATION, HPPC, AGING 등)
- 종합적 레시피 검증 (JSON 스키마, 비즈니스 룰, 안전성)
- Chemistry별 동적 안전 한계 적용
3️⃣ 패턴 파일 처리 (Pattern File Processing)
- 대용량 패턴 데이터 자동 압축 (4가지 알고리즘)
- Excel/CSV 파일 자동 파싱 및 최적화
- 압축 프로파일 DB 관리 및 재사용
🚀 핵심 기능
📊 배터리 데이터 분석 도구
comprehensive_battery_analysis ⭐
완전한 배터리 분석 - 프론트엔드 데이터를 활용한 종합 분석
# 셀 데이터 분석 + 차트 생성 + 통계 계산 통합
comprehensive_battery_analysis(
request="셀 C001의 용량 변화 분석",
cells=["C001", "C002"],
metrics=["capacity", "resistance"],
cycle_range={"start": 1, "end": 100}
)
make_analysis_plan_tool
사용자 요청을 분석하여 단계별 실행 계획 자동 생성
fetch_cards / render_charts
데이터 조회 및 Plotly 기반 인터랙티브 차트 렌더링
process_query_normalized / process_frontend_agent_query
프론트엔드 Query Normalizer 및 Agent 출력 통합 처리
analyze_battery_performance
고수준 배터리 성능 분석 (종합, 특정 메트릭 집중 등)
get_analysis_statistics
시스템 health 체크 및 분석 통계
🧪 배터리 레시피 생성 & 검증 도구
validate_battery_recipe_comprehensive 🔬
배터리 테스트 레시피의 완전 검증
- JSON 스키마 검증
- Chemistry별 안전 한계 확인 (NCM, LFP, LCO, NCA, LMO)
- Step 타입별 필수 cutoffs 검증
- 순환 참조 및 Dead-end 검출
- Agent 친화적 피드백 제공
반환값:
{
"valid": true/false,
"errors": ["치명적 오류들"],
"warnings": ["주의 사항들"],
"suggestions": ["개선 제안들"],
"details": {
"risk_level": "MINIMAL|LOW|MEDIUM|HIGH|CRITICAL",
"total_issues": 0,
"llm_feedback": "Agent가 이해하기 쉬운 구조화된 피드백"
}
}
expand_modular_recipe 🔧
미리 정의된 모듈 템플릿을 완전한 레시피로 확장
# 모듈 조합 → 실행 가능한 레시피 변환
expand_modular_recipe(
template_id="FORMATION_HPPC_CAPACITY",
chemistry="NCM",
capacity_ah=2.5,
temperature=25
)
사용 가능한 템플릿:
FORMATION_HPPC_CAPACITY: 신규 배터리 완전 특성화AGING_WITH_MONITORING: 수명 평가 + 주기적 모니터링PERFORMANCE_CHARACTERIZATION: Rate & 온도 성능 매핑QUICK_VALIDATION: 빠른 검증 테스트
expand_single_module 🧩
개별 배터리 테스트 모듈을 사이클로 확장
사용 가능한 모듈:
FORMATION: 배터리 활성화 공정HPPC: 하이브리드 펄스 전력 특성화CAPACITY_CHECK: 용량 측정AGING_CYCLE: 수명 사이클 테스트TEMPERATURE_SWEEP: 온도별 성능 평가RATE_CAPABILITY: C-rate별 성능 평가
get_available_modules 📚
데이터베이스에 정의된 배터리 테스트 모듈 목록 조회
📦 패턴 파일 처리 도구
compress_pattern 🗜️
대용량 패턴 데이터 자동 압축 및 최적화
4가지 압축 알고리즘:
- auto: 데이터 특성 분석 후 자동 선택 (권장)
- rdp: Ramer-Douglas-Peucker - 범용적, 안정적
- piecewise_linear: 구간별 선형 회귀 - 선형 구간이 많은 데이터
- bezier: 베지어 곡선 - 부드러운 곡선
- polynomial: 다항식 피팅 - 단순한 형태
# 방법 1: 파일에서 직접 압축
compress_pattern(
file_path="hppc_pulse.csv",
time_column="time",
value_column="current",
method="auto",
target_error_percent=1.0, # 목표 오차율 1%
save_to_db=True,
profile_name="HPPC_Pulse_Profile",
data_type="current",
tags=["hppc", "ncm", "pulse"]
)
# 방법 2: 배열 데이터 압축
compress_pattern(
time_data=[0, 1, 2, 3, ...],
value_data=[0, 2.5, 5.0, 2.5, ...],
method="auto",
target_error_percent=1.0
)
반환값:
{
"status": "success",
"profile_id": "550e8400-...",
"compression_result": {
"method": "rdp",
"compressed_points": 150,
"compression_ratio": 95.2,
"max_error_percent": 0.8,
"mean_error_percent": 0.3
},
"recommendation": "최적 알고리즘 추천 정보",
"data_characteristics": "데이터 특성 분석 결과"
}
read_pattern_file 📂
Excel/CSV 파일 자동 파싱 (URL 다운로드 지원, 20,000+ 행 처리)
read_pattern_file(
file_path="https://example.com/data.xlsx",
time_column="Time(s)",
value_column="Current(A)",
skip_rows=1,
sheet_name="Sheet1"
)
get_pattern_profiles 📚
저장된 압축 프로파일 검색 및 조회
# ID로 검색
get_pattern_profiles(profile_id="550e8400-...")
# 이름으로 검색
get_pattern_profiles(profile_name="HPPC")
# 필터 조합
get_pattern_profiles(
compression_method="rdp",
data_type="current",
min_compression_ratio=90.0,
tags=["hppc", "ncm"],
limit=50
)
insert_pattern_to_recipe 🔌
레시피 내 pattern_profile_id를 실제 패턴 데이터로 자동 변환
# 레시피 내부의 모든 pattern_profile_id를 자동 발견하여 변환
result = insert_pattern_to_recipe(recipe_json=base_recipe)
updated_recipe = result["updated_recipe"]
🔍 디버깅 도구
debug_list_all_tool_schemas
등록된 모든 MCP 도구의 스키마 조회 (파라미터, 타입 정보)
📁 프로젝트 아키텍처
Battery_MCP_Server/
├── fastmcp_server_claude.py # Claude Desktop용 (stdio transport)
├── fastmcp_server_clean_copy.py # HTTP 모드용 (n8n 연동) ⭐
├── mcp_prompts.py # MCP 프롬프트 정의 (DB 로딩)
├── mcp_resources.py # MCP 리소스 등록 (DB 로딩)
├── requirements.txt # Python 의존성
│
├── handlers/ # MCP 도구 핸들러 (비즈니스 로직)
│ ├── plan.py # 분석 계획 수립
│ ├── cards.py # 데이터 카드 조회
│ ├── charts.py # 차트 렌더링
│ ├── recipe_validation.py # 레시피 검증 로직
│ ├── pattern_handler.py # 패턴 압축/조회/삽입
│ ├── comprehensive_analysis.py # 종합 분석
│ └── postgresql_manager.py # PostgreSQL 관리
│
├── services/ # 공통 서비스 레이어
│ ├── db_env.py # DB 환경 설정 (ensure_pg_env)
│ ├── db_utils.py # DB 매니저 (db_manager)
│ ├── analysis_decorator.py # 분석 로깅 데코레이터
│ ├── module_expander.py # 모듈 → 레시피 확장
│ ├── pattern_compression.py # 패턴 압축 알고리즘
│ ├── pattern_compression_logger.py # 패턴 압축 로깅
│ ├── recipe_validation_service.py # 레시피 검증 서비스
│ ├── recipe_validation_logger.py # 레시피 검증 로깅
│ └── reference_loader.py # 참조 데이터 로더
│
├── schemas/ # Pydantic 스키마 정의
│ ├── cards.py
│ ├── charts.py
│ ├── plan.py
│ ├── shared.py
│ └── sql_ops.py
│
├── prompts/ # 시스템 프롬프트 (버전별)
│ ├── battery_recipe_agent_v12.1.md
│ ├── battery_chat_agent_v1.0.md
│ ├── pattern_recipe_guide.md
│ └── [various version files]
│
└── docs/ # 문서 및 테스트 데이터
├── TEST_SCENARIOS.md
└── test_data/
├── formation_premium.csv
├── hppc_multi_pulse.csv
└── rate_*.csv
핵심 아키텍처 특징
1. Modular Handler Pattern
- 각 도메인별 핸들러 분리 (plan, cards, charts, recipe, pattern)
- 단일 책임 원칙 (SRP) 준수
2. Service Layer
- DB 연결 관리 (
db_env,db_utils) - 공통 로직 재사용 (
module_expander,pattern_compression) - 로깅 서비스 (
analysis_decorator,*_logger)
3. Database-Driven Configuration
- MCP 프롬프트: DB 우선, 폴백 파일 시스템
- MCP 리소스: DB 우선, 폴백 하드코딩
- 동적 업데이트 가능
4. Dual Transport Support
- stdio: Claude Desktop 통합 (
fastmcp_server_claude.py) - HTTP: n8n 워크플로우 통합 (
fastmcp_server_clean_copy.py)
🔧 설치 방법
1. 저장소 클론
git clone https://github.com/JDWorlds/AI-Battery-Analysis-System-MCP.git
cd AI-Battery-Analysis-System-MCP
2. Python 가상환경 생성 (권장)
python3 -m venv .venv
source .venv/bin/activate # macOS/Linux
# .venv\Scripts\activate # Windows
3. 의존성 설치
pip install -r requirements.txt
4. 데이터베이스 설정
PostgreSQL 데이터베이스 연결을 위한 환경 변수 설정:
export POSTGRES_HOST=localhost
export POSTGRES_PORT=5432
export POSTGRES_DB=chat_memory
export POSTGRES_USER=n8n_user
export POSTGRES_PASSWORD=your_password
또는 .env 파일 생성:
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=chat_memory
POSTGRES_USER=n8n_user
POSTGRES_PASSWORD=your_password
🚀 실행 방법
옵션 1: Claude Desktop 통합 (stdio)
~/.claude.json 파일에 다음 설정 추가:
{
"mcpServers": {
"battery-mcp": {
"command": "fastmcp",
"args": [
"run",
"/path/to/AI-Battery-Analysis-System-MCP/fastmcp_server_claude.py"
],
"env": {
"POSTGRES_HOST": "localhost",
"POSTGRES_PORT": "5432",
"POSTGRES_DB": "chat_memory",
"POSTGRES_USER": "n8n_user",
"POSTGRES_PASSWORD": "your_password"
}
}
}
}
또는 Python 직접 실행:
{
"mcpServers": {
"battery-mcp": {
"command": "python3",
"args": [
"/path/to/AI-Battery-Analysis-System-MCP/fastmcp_server_claude.py"
],
"env": {
"POSTGRES_HOST": "localhost",
"POSTGRES_PORT": "5432",
"POSTGRES_DB": "chat_memory",
"POSTGRES_USER": "n8n_user",
"POSTGRES_PASSWORD": "your_password"
}
}
}
}
설정 후 Claude Desktop 재시작.
옵션 2: HTTP 서버 모드 (n8n 연동)
# 기본 포트 3001로 실행
python3 fastmcp_server_clean_copy.py
# 또는 커스텀 포트
python3 fastmcp_server_clean_copy.py --port 8080
또는 fastmcp CLI 사용:
fastmcp run fastmcp_server_clean_copy.py --transport httpstream --port 3001
서버 시작 시 출력:
🚀 Starting FastMCP Battery Analysis Server...
====================================================================
📊 BATTERY DATA ANALYSIS TOOLS
====================================================================
- comprehensive_battery_analysis: Complete analysis utilizing all frontend data ⭐
- process_query_normalized: Process Query Normalizer JSON payloads
- make_analysis_plan_tool: Generate battery analysis plans
...
✅ FastMCP Server ready on HTTP port 3001
🔗 Uses FastMCP framework for simplified MCP protocol handling
🔨 MCP 도구 카탈로그
📊 배터리 데이터 분석 (8개 도구)
| 도구명 | 설명 | 주요 파라미터 |
|---|---|---|
comprehensive_battery_analysis ⭐ | 완전한 배터리 분석 | request, cells, metrics, cycle_range |
process_query_normalized | Query Normalizer JSON 처리 | json_payload |
make_analysis_plan_tool | 분석 계획 생성 | request, context |
fetch_cards | 데이터 카드 조회 | cells, metrics, filters |
render_charts | 차트 렌더링 | chart_config, data |
process_frontend_agent_query | 프론트엔드 Agent 출력 처리 | payload |
analyze_battery_performance | 고수준 성능 분석 | analysis_type, cells, cycles |
get_analysis_statistics | 시스템 통계 조회 | - |
🧪 배터리 레시피 생성 & 검증 (4개 도구)
| 도구명 | 설명 | 주요 파라미터 |
|---|---|---|
validate_battery_recipe_comprehensive 🔬 | 레시피 완전 검증 | recipe_json |
expand_modular_recipe 🔧 | 모듈 템플릿 확장 | template_id, chemistry, capacity_ah |
expand_single_module 🧩 | 단일 모듈 확장 | module_id, parameters, chemistry |
get_available_modules 📚 | 사용 가능한 모듈 조회 | priority_level |
📦 패턴 파일 처리 (4개 도구)
| 도구명 | 설명 | 주요 파라미터 |
|---|---|---|
read_pattern_file 📂 | Excel/CSV 파일 읽기 | file_path, time_column, value_column |
compress_pattern 🗜️ | 패턴 데이터 압축 | time_data, value_data, method, target_error_percent |
get_pattern_profiles 📚 | 압축 프로파일 조회 | profile_id, profile_name, tags |
insert_pattern_to_recipe 🔌 | 패턴을 레시피에 삽입 | recipe_json |
🔍 디버깅 (1개 도구)
| 도구명 | 설명 | 주요 파라미터 |
|---|---|---|
debug_list_all_tool_schemas | 모든 도구 스키마 조회 | tool_name (optional) |
📚 MCP 리소스 & 프롬프트
MCP Resources (battery:// URI)
FastMCP는 리소스를 통해 참조 데이터를 제공합니다:
| 리소스 URI | 설명 |
|---|---|
battery://modules ⭐ | 배터리 테스트 모듈 & 모듈형 템플릿 |
battery://recipe-templates | 레시피 템플릿 메타데이터 |
battery://recipe-schema | JSON 스키마 명세 |
battery://recipe-examples | 예제 레시피 및 패턴 |
battery://recipe-safety | 안전 가이드라인 및 한계값 |
battery://pattern-profiles ⭐ | 압축된 패턴 프로파일 카탈로그 |
battery://metrics | 사용 가능한 메트릭 정의 |
battery://cells | 셀 정보 및 스펙 |
MCP Prompts
시스템 프롬프트는 데이터베이스에서 동적으로 로딩됩니다:
| 프롬프트명 | 설명 |
|---|---|
battery_analysis_guide | 배터리 분석 워크플로우 가이드 |
query_builder | 복잡한 쿼리 작성 도움말 |
analysis_interpretation | 결과 해석 가이드 |
recipe_validation_guide | 레시피 검증 체크리스트 |
experiment_planner | 종합 실험 계획 수립 |
n8n_agent_assistant | N8N 통합 지원 |
pattern_recipe_guide ⭐ | 패턴 파일 기반 레시피 생성 가이드 |
💡 사용 예시
1. Claude Desktop에서 배터리 분석
User: "셀 C001과 C002의 용량 변화를 비교 분석해줘. 사이클 1-100까지"
Claude: (자동으로 comprehensive_battery_analysis 호출)
- 분석 계획 수립
- 데이터 조회
- 차트 생성
- 결과 해석 제공
2. 모듈형 레시피 생성
# 1. 사용 가능한 모듈 확인
modules = get_available_modules()
# 2. 템플릿으로 레시피 생성
recipe = expand_modular_recipe(
template_id="FORMATION_HPPC_CAPACITY",
chemistry="NCM",
capacity_ah=2.5,
temperature=25
)
# 3. 레시피 검증
validation = validate_battery_recipe_comprehensive(
recipe_json=recipe["expanded_recipe"]
)
if validation["valid"]:
print("✅ 레시피 검증 통과!")
else:
print(f"❌ 오류: {validation['errors']}")
3. 패턴 파일 압축 및 레시피 삽입
# 1. 패턴 파일 압축
compression_result = compress_pattern(
file_path="hppc_pulse.csv",
time_column="time",
value_column="current",
method="auto",
target_error_percent=1.0,
save_to_db=True,
profile_name="HPPC_Pulse_NCM",
tags=["hppc", "ncm", "pulse"]
)
profile_id = compression_result["profile_id"]
print(f"압축률: {compression_result['compression_result']['compression_ratio']}%")
# 2. 레시피에 pattern_profile_id 포함
base_recipe = {
"cycles": [{
"steps": [{
"type": "pattern",
"parameters": {
"setpoints": {
"pattern_profile_id": profile_id
}
}
}]
}]
}
# 3. 패턴을 레시피에 자동 삽입
final_recipe = insert_pattern_to_recipe(recipe_json=base_recipe)
print(f"처리된 패턴 수: {final_recipe['total_patterns_processed']}")
4. n8n 워크플로우 통합
// n8n HTTP Request Node
{
"method": "POST",
"url": "http://localhost:3001/tools/compress_pattern",
"body": {
"file_path": "https://example.com/data.csv",
"method": "auto",
"save_to_db": true,
"profile_name": "My_Pattern"
}
}
🐛 트러블슈팅
MCP 서버가 Claude Desktop에서 인식되지 않는 경우
~/.claude.json경로가 올바른지 확인- Python 경로가 절대 경로인지 확인
- 환경 변수가 올바르게 설정되었는지 확인
- Claude Desktop을 완전히 종료 후 재시작
- 터미널에서 직접 실행하여 에러 확인:
fastmcp run fastmcp_server_claude.py
데이터베이스 연결 오류
- PostgreSQL이 실행 중인지 확인:
pg_isready -h localhost -p 5432 - 데이터베이스 접속 정보가 올바른지 확인
- 방화벽 설정 확인
- 연결 테스트:
psql -h localhost -U n8n_user -d chat_memory
모듈을 찾을 수 없다는 오류
# Python path에 현재 디렉토리 추가
export PYTHONPATH="${PYTHONPATH}:$(pwd)"
# 또는 서버 시작 시
cd /path/to/AI-Battery-Analysis-System-MCP
python3 fastmcp_server_clean_copy.py
패턴 압축 실패
- 파일 형식 확인 (Excel: .xlsx/.xls, CSV: .csv)
- 컬럼명이 정확한지 확인
- 데이터 포인트가 충분한지 확인 (최소 10개 이상)
- 로그 파일 확인:
services/logs/pattern_*.log
HTTP 서버 포트 충돌
# 다른 포트 사용
python3 fastmcp_server_clean_copy.py --port 8080
# 또는 기존 프로세스 종료
lsof -ti:3001 | xargs kill -9
🗄️ 데이터베이스 스키마
서버는 다음 PostgreSQL 테이블을 사용합니다:
Recipe System
recipe_system.recipe_templates- 레시피 템플릿recipe_system.recipe_catalogs- 레시피 카탈로그recipe_system.battery_modules- 배터리 테스트 모듈recipe_system.modular_recipe_templates- 모듈형 템플릿
Pattern System
recipe_system.pattern_profiles- 압축된 패턴 프로파일
MCP Configuration
llm_prompt_templates- MCP 프롬프트 템플릿mcp_resources- MCP 리소스 정의
Battery Analysis
battery_analysis.*- 배터리 분석 데이터 (구조는 프로젝트별 상이)
📄 라이선스
이 프로젝트는 MIT 라이선스 하에 배포됩니다.
🤝 기여
버그 리포트, 기능 제안, Pull Request를 환영합니다!
기여 방법
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📧 연락처
문의사항이 있으시면 GitHub Issues에 등록해주세요: https://github.com/JDWorlds/AI-Battery-Analysis-System-MCP/issues
Made with ❤️ for Battery Testing Automation