asmaa105 commited on
Commit
52e80b4
Β·
verified Β·
1 Parent(s): fb0d820

Update mcp_server.py

Browse files
Files changed (1) hide show
  1. mcp_server.py +185 -184
mcp_server.py CHANGED
@@ -1,184 +1,185 @@
1
- #!/usr/bin/env python3
2
- """
3
- Simplified MCP Server for HuggingFace Hub Tagging Operations using FastMCP
4
- """
5
-
6
- import os
7
- import json
8
- from fastmcp import FastMCP
9
- from huggingface_hub import HfApi, model_info, ModelCard, ModelCardData
10
- from huggingface_hub.utils import HfHubHTTPError
11
- from dotenv import load_dotenv
12
-
13
- load_dotenv()
14
-
15
- # Configuration
16
- HF_TOKEN = os.getenv("HF_TOKEN")
17
-
18
- # Initialize HF API client
19
- hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
20
-
21
- # Create the FastMCP server
22
- mcp = FastMCP("hf-tagging-bot")
23
-
24
-
25
- @mcp.tool()
26
- def get_current_tags(repo_id: str) -> str:
27
- """Get current tags from a HuggingFace model repository"""
28
- print(f"πŸ”§ get_current_tags called with repo_id: {repo_id}")
29
-
30
- if not hf_api:
31
- error_result = {"error": "HF token not configured"}
32
- json_str = json.dumps(error_result)
33
- print(f"❌ No HF API token - returning: {json_str}")
34
- return json_str
35
-
36
- try:
37
- print(f"πŸ“‘ Fetching model info for: {repo_id}")
38
- info = model_info(repo_id=repo_id, token=HF_TOKEN)
39
- current_tags = info.tags if info.tags else []
40
- print(f"🏷️ Found {len(current_tags)} tags: {current_tags}")
41
-
42
- result = {
43
- "status": "success",
44
- "repo_id": repo_id,
45
- "current_tags": current_tags,
46
- "count": len(current_tags),
47
- }
48
- json_str = json.dumps(result)
49
- print(f"βœ… get_current_tags returning: {json_str}")
50
- return json_str
51
-
52
- except Exception as e:
53
- print(f"❌ Error in get_current_tags: {str(e)}")
54
- error_result = {"status": "error", "repo_id": repo_id, "error": str(e)}
55
- json_str = json.dumps(error_result)
56
- print(f"❌ get_current_tags error returning: {json_str}")
57
- return json_str
58
-
59
-
60
- @mcp.tool()
61
- def add_new_tag(repo_id: str, new_tag: str) -> str:
62
- """Add a new tag to a HuggingFace model repository via PR"""
63
- print(f"πŸ”§ add_new_tag called with repo_id: {repo_id}, new_tag: {new_tag}")
64
-
65
- if not hf_api:
66
- error_result = {"error": "HF token not configured"}
67
- json_str = json.dumps(error_result)
68
- print(f"❌ No HF API token - returning: {json_str}")
69
- return json_str
70
-
71
- try:
72
- # Get current model info and tags
73
- print(f"πŸ“‘ Fetching current model info for: {repo_id}")
74
- info = model_info(repo_id=repo_id, token=HF_TOKEN)
75
- current_tags = info.tags if info.tags else []
76
- print(f"🏷️ Current tags: {current_tags}")
77
-
78
- # Check if tag already exists
79
- if new_tag in current_tags:
80
- print(f"⚠️ Tag '{new_tag}' already exists in {current_tags}")
81
- result = {
82
- "status": "already_exists",
83
- "repo_id": repo_id,
84
- "tag": new_tag,
85
- "message": f"Tag '{new_tag}' already exists",
86
- }
87
- json_str = json.dumps(result)
88
- print(f"🏷️ add_new_tag (already exists) returning: {json_str}")
89
- return json_str
90
-
91
- # Add the new tag to existing tags
92
- updated_tags = current_tags + [new_tag]
93
- print(f"πŸ†• Will update tags from {current_tags} to {updated_tags}")
94
-
95
- # Create model card content with updated tags
96
- try:
97
- # Load existing model card
98
- print(f"πŸ“„ Loading existing model card...")
99
- card = ModelCard.load(repo_id, token=HF_TOKEN)
100
- if not hasattr(card, "data") or card.data is None:
101
- card.data = ModelCardData()
102
- except HfHubHTTPError:
103
- # Create new model card if none exists
104
- print(f"πŸ“„ Creating new model card (none exists)")
105
- card = ModelCard("")
106
- card.data = ModelCardData()
107
-
108
- # Update tags - create new ModelCardData with updated tags
109
- card_dict = card.data.to_dict()
110
- card_dict["tags"] = updated_tags
111
- card.data = ModelCardData(**card_dict)
112
-
113
- # Create a pull request with the updated model card
114
- pr_title = f"Add '{new_tag}' tag"
115
- pr_description = f"""
116
- ## Add tag: {new_tag}
117
-
118
- This PR adds the `{new_tag}` tag to the model repository.
119
-
120
- **Changes:**
121
- - Added `{new_tag}` to model tags
122
- - Updated from {len(current_tags)} to {len(updated_tags)} tags
123
-
124
- **Current tags:** {", ".join(current_tags) if current_tags else "None"}
125
- **New tags:** {", ".join(updated_tags)}
126
- """
127
-
128
- print(f"πŸš€ Creating PR with title: {pr_title}")
129
-
130
- # Create commit with updated model card using CommitOperationAdd
131
- from huggingface_hub import CommitOperationAdd
132
-
133
- commit_info = hf_api.create_commit(
134
- repo_id=repo_id,
135
- operations=[
136
- CommitOperationAdd(
137
- path_in_repo="README.md", path_or_fileobj=str(card).encode("utf-8")
138
- )
139
- ],
140
- commit_message=pr_title,
141
- commit_description=pr_description,
142
- token=HF_TOKEN,
143
- create_pr=True,
144
- )
145
-
146
- # Extract PR URL from commit info
147
- pr_url_attr = commit_info.pr_url
148
- pr_url = pr_url_attr if hasattr(commit_info, "pr_url") else str(commit_info)
149
-
150
- print(f"βœ… PR created successfully! URL: {pr_url}")
151
-
152
- result = {
153
- "status": "success",
154
- "repo_id": repo_id,
155
- "tag": new_tag,
156
- "pr_url": pr_url,
157
- "previous_tags": current_tags,
158
- "new_tags": updated_tags,
159
- "message": f"Created PR to add tag '{new_tag}'",
160
- }
161
- json_str = json.dumps(result)
162
- print(f"βœ… add_new_tag success returning: {json_str}")
163
- return json_str
164
-
165
- except Exception as e:
166
- print(f"❌ Error in add_new_tag: {str(e)}")
167
- print(f"❌ Error type: {type(e)}")
168
- import traceback
169
-
170
- print(f"❌ Traceback: {traceback.format_exc()}")
171
-
172
- error_result = {
173
- "status": "error",
174
- "repo_id": repo_id,
175
- "tag": new_tag,
176
- "error": str(e),
177
- }
178
- json_str = json.dumps(error_result)
179
- print(f"❌ add_new_tag error returning: {json_str}")
180
- return json_str
181
-
182
-
183
- if __name__ == "__main__":
184
- mcp.run()
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Simplified MCP Server for HuggingFace Hub Tagging Operations using FastMCP
4
+ """
5
+
6
+ import os
7
+ import json
8
+ from fastmcp import FastMCP
9
+ from huggingface_hub import HfApi, model_info, ModelCard, ModelCardData
10
+ from huggingface_hub.utils import HfHubHTTPError
11
+ from dotenv import load_dotenv
12
+
13
+ load_dotenv()
14
+
15
+ # Configuration
16
+ HF_TOKEN = os.getenv("HF_TOKEN")
17
+ if HF_TOKEN:
18
+ HF_TOKEN = HF_TOKEN.strip()
19
+ # Initialize HF API client
20
+ hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
21
+
22
+ # Create the FastMCP server
23
+ mcp = FastMCP("hf-tagging-bot")
24
+
25
+
26
+ @mcp.tool()
27
+ def get_current_tags(repo_id: str) -> str:
28
+ """Get current tags from a HuggingFace model repository"""
29
+ print(f"πŸ”§ get_current_tags called with repo_id: {repo_id}")
30
+
31
+ if not hf_api:
32
+ error_result = {"error": "HF token not configured"}
33
+ json_str = json.dumps(error_result)
34
+ print(f"❌ No HF API token - returning: {json_str}")
35
+ return json_str
36
+
37
+ try:
38
+ print(f"πŸ“‘ Fetching model info for: {repo_id}")
39
+ info = model_info(repo_id=repo_id, token=HF_TOKEN)
40
+ current_tags = info.tags if info.tags else []
41
+ print(f"🏷️ Found {len(current_tags)} tags: {current_tags}")
42
+
43
+ result = {
44
+ "status": "success",
45
+ "repo_id": repo_id,
46
+ "current_tags": current_tags,
47
+ "count": len(current_tags),
48
+ }
49
+ json_str = json.dumps(result)
50
+ print(f"βœ… get_current_tags returning: {json_str}")
51
+ return json_str
52
+
53
+ except Exception as e:
54
+ print(f"❌ Error in get_current_tags: {str(e)}")
55
+ error_result = {"status": "error", "repo_id": repo_id, "error": str(e)}
56
+ json_str = json.dumps(error_result)
57
+ print(f"❌ get_current_tags error returning: {json_str}")
58
+ return json_str
59
+
60
+
61
+ @mcp.tool()
62
+ def add_new_tag(repo_id: str, new_tag: str) -> str:
63
+ """Add a new tag to a HuggingFace model repository via PR"""
64
+ print(f"πŸ”§ add_new_tag called with repo_id: {repo_id}, new_tag: {new_tag}")
65
+
66
+ if not hf_api:
67
+ error_result = {"error": "HF token not configured"}
68
+ json_str = json.dumps(error_result)
69
+ print(f"❌ No HF API token - returning: {json_str}")
70
+ return json_str
71
+
72
+ try:
73
+ # Get current model info and tags
74
+ print(f"πŸ“‘ Fetching current model info for: {repo_id}")
75
+ info = model_info(repo_id=repo_id, token=HF_TOKEN)
76
+ current_tags = info.tags if info.tags else []
77
+ print(f"🏷️ Current tags: {current_tags}")
78
+
79
+ # Check if tag already exists
80
+ if new_tag in current_tags:
81
+ print(f"⚠️ Tag '{new_tag}' already exists in {current_tags}")
82
+ result = {
83
+ "status": "already_exists",
84
+ "repo_id": repo_id,
85
+ "tag": new_tag,
86
+ "message": f"Tag '{new_tag}' already exists",
87
+ }
88
+ json_str = json.dumps(result)
89
+ print(f"🏷️ add_new_tag (already exists) returning: {json_str}")
90
+ return json_str
91
+
92
+ # Add the new tag to existing tags
93
+ updated_tags = current_tags + [new_tag]
94
+ print(f"πŸ†• Will update tags from {current_tags} to {updated_tags}")
95
+
96
+ # Create model card content with updated tags
97
+ try:
98
+ # Load existing model card
99
+ print(f"πŸ“„ Loading existing model card...")
100
+ card = ModelCard.load(repo_id, token=HF_TOKEN)
101
+ if not hasattr(card, "data") or card.data is None:
102
+ card.data = ModelCardData()
103
+ except HfHubHTTPError:
104
+ # Create new model card if none exists
105
+ print(f"πŸ“„ Creating new model card (none exists)")
106
+ card = ModelCard("")
107
+ card.data = ModelCardData()
108
+
109
+ # Update tags - create new ModelCardData with updated tags
110
+ card_dict = card.data.to_dict()
111
+ card_dict["tags"] = updated_tags
112
+ card.data = ModelCardData(**card_dict)
113
+
114
+ # Create a pull request with the updated model card
115
+ pr_title = f"Add '{new_tag}' tag"
116
+ pr_description = f"""
117
+ ## Add tag: {new_tag}
118
+
119
+ This PR adds the `{new_tag}` tag to the model repository.
120
+
121
+ **Changes:**
122
+ - Added `{new_tag}` to model tags
123
+ - Updated from {len(current_tags)} to {len(updated_tags)} tags
124
+
125
+ **Current tags:** {", ".join(current_tags) if current_tags else "None"}
126
+ **New tags:** {", ".join(updated_tags)}
127
+ """
128
+
129
+ print(f"πŸš€ Creating PR with title: {pr_title}")
130
+
131
+ # Create commit with updated model card using CommitOperationAdd
132
+ from huggingface_hub import CommitOperationAdd
133
+
134
+ commit_info = hf_api.create_commit(
135
+ repo_id=repo_id,
136
+ operations=[
137
+ CommitOperationAdd(
138
+ path_in_repo="README.md", path_or_fileobj=str(card).encode("utf-8")
139
+ )
140
+ ],
141
+ commit_message=pr_title,
142
+ commit_description=pr_description,
143
+ token=HF_TOKEN,
144
+ create_pr=True,
145
+ )
146
+
147
+ # Extract PR URL from commit info
148
+ pr_url_attr = commit_info.pr_url
149
+ pr_url = pr_url_attr if hasattr(commit_info, "pr_url") else str(commit_info)
150
+
151
+ print(f"βœ… PR created successfully! URL: {pr_url}")
152
+
153
+ result = {
154
+ "status": "success",
155
+ "repo_id": repo_id,
156
+ "tag": new_tag,
157
+ "pr_url": pr_url,
158
+ "previous_tags": current_tags,
159
+ "new_tags": updated_tags,
160
+ "message": f"Created PR to add tag '{new_tag}'",
161
+ }
162
+ json_str = json.dumps(result)
163
+ print(f"βœ… add_new_tag success returning: {json_str}")
164
+ return json_str
165
+
166
+ except Exception as e:
167
+ print(f"❌ Error in add_new_tag: {str(e)}")
168
+ print(f"❌ Error type: {type(e)}")
169
+ import traceback
170
+
171
+ print(f"❌ Traceback: {traceback.format_exc()}")
172
+
173
+ error_result = {
174
+ "status": "error",
175
+ "repo_id": repo_id,
176
+ "tag": new_tag,
177
+ "error": str(e),
178
+ }
179
+ json_str = json.dumps(error_result)
180
+ print(f"❌ add_new_tag error returning: {json_str}")
181
+ return json_str
182
+
183
+
184
+ if __name__ == "__main__":
185
+ mcp.run()