test_mcp_commit.py•6.09 kB
#!/usr/bin/env python3
"""
MCP GitHub 서버의 write 도구들을 직접 호출하여 커밋과 푸시를 진행하는 테스트 스크립트
"""
import asyncio
import os
import sys
from pathlib import Path
# 프로젝트 루트를 Python 경로에 추가
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from mcp_github.tools_write import (
create_or_update_file,
create_branch,
get_repository_status
)
async def test_github_operations():
"""GitHub 작업 테스트"""
# GitHub 저장소 정보
owner = "J-nowcow" # 실제 GitHub 사용자명으로 변경
repo = "github-MCP-practice" # 실제 저장소명으로 변경
print(f"🎯 GitHub 저장소: {owner}/{repo}")
print("=" * 50)
try:
# 1. 현재 저장소 상태 확인
print("📊 1. 저장소 상태 확인 중...")
status = await get_repository_status(owner, repo)
if status["success"]:
print(f"✅ 현재 브랜치: {status['data']['branch']}")
print(f"✅ 최신 커밋: {status['data']['commit_sha'][:8]}")
print(f"✅ 커밋 메시지: {status['data']['commit_message']}")
else:
print(f"❌ 상태 확인 실패: {status['error']}")
return
print()
# 2. 새 브랜치 생성
new_branch = "mcp-test-branch"
print(f"🌿 2. 새 브랜치 '{new_branch}' 생성 중...")
branch_result = await create_branch(owner, repo, new_branch)
if branch_result["success"]:
print(f"✅ 브랜치 생성 성공: {new_branch}")
else:
print(f"❌ 브랜치 생성 실패: {branch_result['error']}")
# 기존 브랜치가 있을 수 있으므로 계속 진행
print()
# 3. 새 파일 생성
test_file_path = "mcp_test/hello_mcp.md"
test_content = """# Hello MCP! 🚀
이 파일은 **GitHub MCP 서버**를 통해 자동으로 생성되었습니다.
## 생성된 기능들:
- ✅ 파일 생성/수정 (`createOrUpdateFile`)
- ✅ 파일 삭제 (`deleteFile`)
- ✅ 브랜치 생성 (`createBranch`)
- ✅ 다중 파일 커밋 (`createCommitWithMultipleFiles`)
- ✅ 저장소 상태 조회 (`getRepositoryStatus`)
## 사용법:
```python
from mcp_github.tools_write import create_or_update_file
result = await create_or_update_file(
owner="your_username",
repo="your_repo",
path="path/to/file.md",
content="# Hello World",
message="Add new file via MCP"
)
```
---
*Generated by GitHub MCP Server*
"""
print(f"📝 3. 새 파일 생성 중: {test_file_path}")
file_result = await create_or_update_file(
owner=owner,
repo=repo,
path=test_file_path,
content=test_content,
message="🎉 MCP 서버로 새 파일 생성 테스트",
branch=new_branch,
committer_name="MCP Bot",
committer_email="mcp@example.com"
)
if file_result["success"]:
print(f"✅ 파일 생성 성공!")
print(f" 📍 경로: {file_result['data']['path']}")
print(f" 🔗 URL: {file_result['data']['url']}")
print(f" 🆔 커밋 SHA: {file_result['data']['commit_sha'][:8]}")
else:
print(f"❌ 파일 생성 실패: {file_result['error']}")
print(f" 📋 전체 결과: {file_result}")
return
print()
# 4. 파일 수정
updated_content = test_content + "\n\n## 추가된 내용 🆕\n\n이 내용은 나중에 추가되었습니다!"
print(f"✏️ 4. 파일 수정 중: {test_file_path}")
update_result = await create_or_update_file(
owner=owner,
repo=repo,
path=test_file_path,
content=updated_content,
message="📝 MCP 서버로 파일 수정 테스트",
branch=new_branch,
committer_name="MCP Bot",
committer_email="mcp@example.com"
)
if update_result["success"]:
print(f"✅ 파일 수정 성공!")
print(f" 🔄 작업: {update_result['data']['operation']}")
print(f" 🆔 커밋 SHA: {update_result['data']['commit_sha'][:8]}")
else:
print(f"❌ 파일 수정 실패: {update_result['error']}")
print()
# 5. 최종 상태 확인
print("📊 5. 최종 저장소 상태 확인 중...")
final_status = await get_repository_status(owner, repo, new_branch)
if final_status["success"]:
print(f"✅ 최종 상태:")
print(f" 🌿 브랜치: {final_status['data']['branch']}")
print(f" 🆔 커밋 SHA: {final_status['data']['commit_sha'][:8]}")
print(f" 📝 커밋 메시지: {final_status['data']['commit_message']}")
print(f" 📅 커밋 날짜: {final_status['data']['commit_date']}")
else:
print(f"❌ 최종 상태 확인 실패: {final_status['error']}")
print()
print("🎉 MCP GitHub 테스트 완료!")
print(f"🔗 저장소: https://github.com/{owner}/{repo}")
print(f"🌿 새 브랜치: {new_branch}")
except Exception as e:
print(f"❌ 오류 발생: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
# 환경변수 로드
from dotenv import load_dotenv
load_dotenv()
# GitHub 토큰 확인
if not os.getenv("GITHUB_TOKEN"):
print("❌ GITHUB_TOKEN 환경변수가 설정되지 않았습니다.")
print(" .env 파일에 GITHUB_TOKEN=your_token_here 를 추가하세요.")
sys.exit(1)
print("🚀 MCP GitHub 서버 테스트 시작")
print("=" * 50)
# 비동기 실행
asyncio.run(test_github_operations())