-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.py
More file actions
124 lines (102 loc) · 3.75 KB
/
main2.py
File metadata and controls
124 lines (102 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import os
import asyncio
import sys
import json
import base64
from urllib.parse import urlparse
from dotenv import load_dotenv
try:
from spoon_ai.tools.mcp_tool import MCPTool
except ImportError:
print("❌ MCPTool을 import할 수 없습니다.")
sys.exit(1)
load_dotenv()
def parse_github_url(url):
"""
GitHub URL에서 owner와 repo 이름을 추출합니다.
"""
path = urlparse(url).path.strip("/")
parts = path.split("/")
if len(parts) >= 2:
owner = parts[0]
repo = parts[1].replace(".git", "")
return owner, repo
return None, None
async def read_readme_final(repo_owner, repo_name):
"""
SpoonOS MCPTool로 README.md를 읽어옵니다 - 진짜 최종!
"""
print("\n" + "="*60)
print("📖 README.md 읽기 - 진짜 최종 버전!")
print("="*60)
# 1. GitHub 토큰
github_token = os.getenv("GITHUB_TOKEN")
if not github_token:
print("❌ .env 파일에 GITHUB_TOKEN이 필요합니다.")
return
print(f"✅ GitHub 토큰 확인 완료")
# 2. MCP 도구 생성
npx_path = r"C:\Program Files\nodejs\npx.cmd" if sys.platform.startswith('win') else "npx"
print("\n🔧 GitHub MCP 서버 연결 중...")
github_tool = MCPTool(
name="github_mcp",
description="GitHub MCP 서버",
mcp_config={
"command": npx_path,
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": github_token
}
}
)
print("✅ MCPTool 생성 완료")
# 3. README.md 읽기
print(f"\n📖 {repo_owner}/{repo_name} README.md 읽기 중...")
file_path = "README.md"
try:
# call_mcp_tool(tool_name: str, **kwargs)
result = await github_tool.call_mcp_tool(
"get_file_contents", # tool_name (문자열)
owner=repo_owner, # **kwargs
repo=repo_name,
path=file_path
)
print("\n" + "="*60)
print("✅ 성공! README.md 읽기 완료")
print("="*60)
print(f"\n결과 타입: {type(result)}")
print(f"\n📄 내용:\n")
print(result)
print("\n" + "="*60)
# 🎁 보너스: base64 디코딩해서 실제 내용 보기
try:
data = json.loads(result)
if data.get('content') and data.get('encoding') == 'base64':
# Base64 에러 방지를 위해 공백/줄바꿈 제거
clean_content = "".join(data['content'].split())
decoded_content = base64.b64decode(clean_content).decode('utf-8')
print("\n" + "="*60)
print("📝 디코딩된 README 내용:")
print("="*60)
print(decoded_content[:500]) # 처음 500자만
print("\n... (전체 내용은 위 JSON의 content 필드에 base64로 인코딩되어 있음)")
print("="*60)
except Exception as e:
print(f"⚠️ 디코딩 중 오류 발생: {e}")
return result
except Exception as e:
print(f"\n❌ 에러: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# URL 입력 받기
print("GitHub 저장소 주소를 입력해주세요.")
repo_url = input("🔗 URL: ").strip()
owner, repo = parse_github_url(repo_url)
if owner and repo:
# 분석 실행
asyncio.run(read_readme_final(owner, repo))
else:
print("❌ 유효한 GitHub URL이 아닙니다.")