9.2 KiB
9.2 KiB
CLAUDE.md - Imagen4 MCP 서버 개발 가이드
프로젝트 개요
Google Imagen4 API를 활용한 MCP(Model Context Protocol) 서버 구현체입니다. 모듈화된 아키텍처로 설계되어 있으며 한글 프롬프트와 UTF-8 인코딩을 완벽 지원합니다.
주요 특징
- Google Imagen4 API 연동을 통한 고품질 이미지 생성 (2048x2048 PNG)
- MCP 프로토콜 완전 지원으로 Claude Desktop과 원활한 연동
- 512x512 JPEG 미리보기 이미지를 base64로 제공하여 빠른 확인 가능
- Windows 환경에서 한글 프롬프트 완벽 지원 (UTF-8 강제 설정)
- 비동기 태스크 처리 및 백그라운드 워커 풀 지원
- 향상된 에러 처리 및 재시도 로직
- 메타데이터 JSON 저장으로 이미지 재생성 지원
프로젝트 구조
imagen4/
├── main.py # 통합 실행 파일 (서버 진입점)
├── requirements.txt # 의존성 패키지
├── .env # 환경변수 설정 (사용자 생성 필요)
├── run_utf8.bat # UTF-8 환경 서버 실행 스크립트
├── test_main.py # 기본 기능 테스트
├── claude_desktop_config.json # Claude Desktop MCP 설정
├── generated_images/ # 이미지 생성 결과 저장소
│ ├── *.png # 원본 이미지 (2048x2048)
│ └── *.json # 생성 메타데이터
└── src/
├── connector/ # Google Imagen4 API 연결
│ ├── config.py # 환경변수 및 설정 관리
│ ├── imagen4_client.py # API 클라이언트 (412라인)
│ └── utils.py # 유틸리티 함수
├── server/ # MCP 서버 구현
│ ├── models.py # 데이터 모델 및 도구 정의 (132라인)
│ ├── mcp_server.py # MCP 서버 메인 클래스
│ ├── handlers.py # 도구 핸들러 로직 (308라인)
│ └── enhanced_handlers.py # 향상된 핸들러 (344라인)
├── async_task/ # 비동기 작업 관리
│ ├── models.py # 태스크 모델
│ ├── task_manager.py # 태스크 매니저 (324라인)
│ └── worker_pool.py # 워커 풀 (258라인)
└── utils/ # 유틸리티 모듈
├── error_recovery.py # 에러 복구 및 재시도 (237라인)
├── image_utils.py # 이미지 처리 (107라인)
└── token_utils.py # 토큰 관리 (200라인)
설치 및 실행
1. 의존성 설치
pip install -r requirements.txt
필수 패키지:
google-genai>=0.2.0- Google Imagen4 APImcp>=1.0.0- MCP 프로토콜python-dotenv>=1.0.0- 환경변수 관리Pillow>=10.0.0- 이미지 처리pytest>=7.0.0- 테스트 프레임워크
2. 환경 설정
.env 파일 생성:
GOOGLE_APPLICATION_CREDENTIALS=path/to/your/service-account-key.json
PROJECT_ID=your-gcp-project-id
LOCATION=us-central1
OUTPUT_PATH=./generated_images
3. 서버 실행
Windows (권장):
run_utf8.bat
수동 실행:
# Windows
chcp 65001
set PYTHONIOENCODING=utf-8
set PYTHONUTF8=1
python main.py
# Linux/Mac
export PYTHONIOENCODING=utf-8
python main.py
4. Claude Desktop 연동
claude_desktop_config.json 내용을 Claude Desktop 설정에 추가:
{
"mcpServers": {
"imagen4": {
"command": "python",
"args": ["main.py"],
"cwd": "D:\\Project\\imagen4",
"env": {
"PYTHONPATH": "D:\\Project\\imagen4"
}
}
}
}
핵심 기능
1. 이미지 생성 (generate_image)
- 입력: 한글/영어 프롬프트, 시드값, 설정 옵션
- 출력: 2048x2048 PNG + 512x512 JPEG 미리보기 (base64)
- 지원 비율: 1:1, 9:16, 16:9, 3:4, 4:3
- 최대 생성: 2개 이미지 동시 생성
2. 랜덤 시드 생성 (generate_random_seed)
- 재현 가능한 이미지 생성을 위한 시드값 제공
3. JSON 기반 재생성 (regenerate_from_json)
- 저장된 메타데이터로 동일한 설정의 이미지 재생성
UTF-8 인코딩 지원
Windows cp949 오류 방지
증상:
'cp949' codec can't encode character '\U0001f4ad' in position 0: illegal multibyte sequence
해결책:
1. 자동 UTF-8 설정 (main.py 상단)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
# UTF-8 강제 설정
os.environ['PYTHONIOENCODING'] = 'utf-8'
os.environ['PYTHONUTF8'] = '1'
os.environ['LC_ALL'] = 'C.UTF-8'
# Windows UTF-8 콘솔 설정
if sys.platform.startswith('win'):
os.system('chcp 65001 >nul 2>&1')
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
2. 실행 스크립트 (run_utf8.bat)
@echo off
chcp 65001 >nul 2>&1
set PYTHONIOENCODING=utf-8
set PYTHONUTF8=1
set LC_ALL=C.UTF-8
python main.py
pause
3. 코딩 규칙
- 텍스트 라벨 사용:
[SUCCESS],[ERROR],[WARNING] - 파일 I/O 시
encoding='utf-8'필수 명시 - 모든 문자열 처리에
ensure_unicode_string()함수 활용
테스트
기본 테스트 실행
python test_main.py
단위 테스트
# 커넥터 테스트
pytest tests/test_connector.py
# 서버 테스트
pytest tests/test_server.py
# 전체 테스트
pytest tests/
개발 가이드
1. 새로운 도구 추가
models.py에 도구 정의 추가:
@staticmethod
def get_new_tool() -> Tool:
return Tool(
name="new_tool",
description="새로운 도구 설명",
inputSchema={
"type": "object",
"properties": {
"param": {"type": "string", "description": "매개변수"}
},
"required": ["param"]
}
)
handlers.py에 핸들러 구현:
async def handle_new_tool(self, args: Dict[str, Any]) -> List[TextContent]:
param = args.get("param")
# 도구 로직 구현
return [TextContent(type="text", text="결과")]
2. 에러 처리 패턴
from src.utils.error_recovery import with_retry, RetryConfig
from src.connector.imagen4_client import classify_api_error
@with_retry(RetryConfig(max_attempts=3))
async def api_call():
try:
result = await some_api_call()
return result
except Exception as e:
error_type, message = classify_api_error(e)
logger.error(f"API Error [{error_type.value}]: {message}")
raise
3. 로깅 설정
import logging
from src.connector.imagen4_client import ensure_unicode_string
logger = logging.getLogger(__name__)
# 안전한 유니코드 로깅
prompt = ensure_unicode_string(user_input)
logger.info(f"Processing prompt: {prompt}")
주요 클래스 및 함수
src.connector.imagen4_client
Imagen4Client: Google API 클라이언트 메인 클래스classify_api_error(): API 오류 분류 및 처리ensure_unicode_string(): UTF-8 문자열 안전 변환
src.server.handlers
ToolHandlers: MCP 도구 핸들러 컬렉션sanitize_args_for_logging(): 로깅용 인수 정리
src.async_task.task_manager
TaskManager: 비동기 작업 관리 (최대 10분 타임아웃)WorkerPool: 멀티 워커 지원
src.utils.image_utils
create_preview_image_b64(): JPEG 미리보기 생성get_image_info(): 이미지 메타데이터 추출
문제 해결
일반적인 오류
1. Google Cloud 인증 오류
# 서비스 계정 키 경로 확인
echo $GOOGLE_APPLICATION_CREDENTIALS
# 프로젝트 ID 확인
echo $PROJECT_ID
# Imagen API 활성화 확인
2. 메모리 부족
- 이미지 생성 개수를 1개로 제한
- 시스템 메모리 8GB 이상 권장
3. 한글 로깅 깨짐
# run_utf8.bat 사용 또는
chcp 65001
set PYTHONIOENCODING=utf-8
python main.py
4. MCP 연결 실패
- Claude Desktop 재시작
claude_desktop_config.json경로 확인- 서버 로그에서 오류 메시지 확인
로그 모니터링
서버 실행 시 상세 로그가 출력됩니다:
[UTF8-TEST] Test UTF-8: 한글 테스트 ✓
INFO - Imagen4 MCP Server starting...
INFO - Starting image generation: '아름다운 풍경...', Seed: 123456
INFO - Image generated successfully
성능 및 제한사항
API 제한
- Google Imagen4 API 할당량 준수
- 동시 요청 수 제한 (워커 풀 관리)
- 이미지 크기: 최대 2048x2048
메모리 사용
- PNG 원본: 8-15MB per image
- JPEG 미리보기: 50-200KB per image
- 메타데이터: <1KB per image
타임아웃
- 이미지 생성: 360초 (6분)
- 백그라운드 작업: 600초 (10분)
마지막 업데이트: 2025년 8월 25일 프로젝트 버전: 현재 안정 버전 사용 중 지원: 한글 프롬프트 완벽 지원, Windows/Linux/Mac 크로스 플랫폼