tianruci commited on
Commit
5e11091
·
verified ·
1 Parent(s): c8b6b7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -28
app.py CHANGED
@@ -1,20 +1,28 @@
1
  import os
2
- import time
3
  import requests
4
  from fastapi import FastAPI
5
  from datetime import datetime, timedelta
6
- from starlette.routing import Mount
7
  from fastmcp.server import FastMCP
8
  from contextlib import asynccontextmanager
9
 
10
  @asynccontextmanager
11
  async def lifespan(app: FastAPI):
12
- await fetch_github_trending() # 启动时初始化
13
  yield
14
 
15
  app = FastAPI(lifespan=lifespan)
16
 
17
- # 缓存最新获取的热门项目
 
 
 
 
 
 
 
 
 
18
  cached_trending = []
19
  last_updated = None
20
 
@@ -31,58 +39,55 @@ async def fetch_github_trending():
31
  }
32
 
33
  headers = {}
34
- github_token = os.getenv("GITHUB_TOKEN")
35
- if github_token:
36
  headers["Authorization"] = f"token {github_token}"
37
 
38
  try:
39
  response = requests.get(url, params=params, headers=headers)
40
  response.raise_for_status()
41
- items = response.json().get("items", [])
42
-
43
- # 简化项目信息
44
- trending_projects = []
45
- for item in items:
46
- trending_projects.append({
47
  "name": item["full_name"],
48
  "url": item["html_url"],
49
  "stars": item["stargazers_count"],
50
  "description": item["description"],
51
  "language": item["language"]
52
- })
53
-
54
- cached_trending = trending_projects
55
  last_updated = datetime.now()
56
- return trending_projects
57
  except Exception as e:
58
  print(f"Error fetching GitHub trending: {e}")
59
  return cached_trending if cached_trending else []
60
 
61
- # 定义MCP服务器和工具
62
- #mcp_server = FastMCP(name="GithubTrending", stateless_http=True)
63
- mcp_server = FastMCP(name="GithubTrending")
64
-
65
- app.mount("/mcp", mcp_server.http_app())
66
- #mcp_app = mcp_server.http_app(path='/mcp')
67
- #app.mount("/mcp", mcp_app)
68
 
69
  @mcp_server.tool()
70
  def get_trending_repos(num: int = 10) -> dict:
71
- """Tool to get top GitHub trending repositories with stars >1000"""
72
  if not last_updated or (datetime.now() - last_updated) > timedelta(minutes=5):
73
  fetch_github_trending()
74
  return {"trending": cached_trending[:num]}
75
 
 
 
 
76
  @app.get("/trending")
77
  async def get_trending():
78
- """获取GitHub热门项目"""
79
- # 如果缓存为空或超过5分钟未更新,则重新获取
80
  if not cached_trending or (datetime.now() - last_updated) > timedelta(minutes=5):
81
  await fetch_github_trending()
82
 
83
  return {
84
  "trending": cached_trending,
85
  "last_updated": last_updated.isoformat() if last_updated else None,
86
- "cache_expires_in": 300, # 告诉客户端缓存有效期(秒)
87
- "suggested_polling_interval": 60 # 建议客户端轮询间隔(秒)
88
  }
 
1
  import os
 
2
  import requests
3
  from fastapi import FastAPI
4
  from datetime import datetime, timedelta
5
+ from fastapi.middleware.cors import CORSMiddleware
6
  from fastmcp.server import FastMCP
7
  from contextlib import asynccontextmanager
8
 
9
  @asynccontextmanager
10
  async def lifespan(app: FastAPI):
11
+ await fetch_github_trending()
12
  yield
13
 
14
  app = FastAPI(lifespan=lifespan)
15
 
16
+ # 添加 CORS 支持
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=["*"],
20
+ allow_credentials=True,
21
+ allow_methods=["*"],
22
+ allow_headers=["*"],
23
+ )
24
+
25
+ # 缓存设置
26
  cached_trending = []
27
  last_updated = None
28
 
 
39
  }
40
 
41
  headers = {}
42
+ if github_token := os.getenv("GITHUB_TOKEN"):
 
43
  headers["Authorization"] = f"token {github_token}"
44
 
45
  try:
46
  response = requests.get(url, params=params, headers=headers)
47
  response.raise_for_status()
48
+ cached_trending = [
49
+ {
 
 
 
 
50
  "name": item["full_name"],
51
  "url": item["html_url"],
52
  "stars": item["stargazers_count"],
53
  "description": item["description"],
54
  "language": item["language"]
55
+ }
56
+ for item in response.json().get("items", [])
57
+ ]
58
  last_updated = datetime.now()
59
+ return cached_trending
60
  except Exception as e:
61
  print(f"Error fetching GitHub trending: {e}")
62
  return cached_trending if cached_trending else []
63
 
64
+ # 初始化 MCP 服务器
65
+ mcp_server = FastMCP(
66
+ name="GithubTrending",
67
+ stateless_http=True,
68
+ http_path="/mcp",
69
+ sse_path="/mcp/sse"
70
+ )
71
 
72
  @mcp_server.tool()
73
  def get_trending_repos(num: int = 10) -> dict:
74
+ """获取 GitHub 热门仓库"""
75
  if not last_updated or (datetime.now() - last_updated) > timedelta(minutes=5):
76
  fetch_github_trending()
77
  return {"trending": cached_trending[:num]}
78
 
79
+ # 挂载 MCP 应用
80
+ app.mount("/mcp", mcp_server.http_app())
81
+
82
  @app.get("/trending")
83
  async def get_trending():
84
+ """公开的 HTTP 端点"""
 
85
  if not cached_trending or (datetime.now() - last_updated) > timedelta(minutes=5):
86
  await fetch_github_trending()
87
 
88
  return {
89
  "trending": cached_trending,
90
  "last_updated": last_updated.isoformat() if last_updated else None,
91
+ "cache_expires_in": 300,
92
+ "suggested_polling_interval": 60
93
  }