SURIAPRAKASH1 commited on
Commit
1cb60f3
Β·
1 Parent(s): ffc60b1

after 2days struggle -> fix import error

Browse files
Files changed (1) hide show
  1. server.py +31 -33
server.py CHANGED
@@ -1,43 +1,48 @@
1
- from mcp.server.fastmcp import FastMCP
2
- import httpx
3
-
4
  from pathlib import Path
5
  import subprocess
6
- from typing import Any, Literal, Optional
7
- from bs4 import BeautifulSoup
8
- import logging, os, json, sys
9
  from dotenv import load_dotenv
10
- load_dotenv()
11
 
12
  # -----------
13
  # Logging
14
  # ------------
15
- logger = logging.getLogger(__name__)
16
- logger.setLevel("DEBUG")
17
-
18
- # formatter
19
- fmt = logging.Formatter("%(asctime)s -- %(name)s -- %(levelname)s -- %(message)s")
20
 
21
- # handler
22
- file_handler = logging.FileHandler(filename= "multitools-server.log")
23
- file_handler.setFormatter(fmt)
24
 
25
- # add to logger
26
  logger.addHandler(file_handler)
27
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # -------------------------
29
  # Initiating FastMCP server
30
  # -------------------------
31
  mcp = FastMCP("multitools-server")
32
 
33
-
34
  # --------------
35
  # Configuration
36
  #---------------
37
- BASE_CRICKET_URL = os.environ.get("BASE_CRICKET_URI", "False")
 
38
 
39
- # PR template directory (shared across all modules)
40
  TEMPLATES_DIR = Path(__file__).parent / "templates"
 
41
 
42
  # Default PR templates
43
  DEFAULT_TEMPLATES = {
@@ -81,18 +86,15 @@ async def cricket_source(mode: str, want: str) -> str:
81
  url = f"{BASE_CRICKET_URL}/cricket-match/live-scores/upcoming-matches"
82
  else:
83
  error = f"Not Implemented: Currently there's no implementation to handle {mode}. Only handels live, upcomming"
84
- logger.error(msg= error)
85
  return json.dumps({"error": error})
86
 
87
  try:
88
  async with httpx.AsyncClient(timeout= 10.0) as client:
89
  response = await client.get(url= url)
90
- response.raise_for_status() # if not 2xx it will raise HTTP error
91
  except httpx.HTTPError as e:
92
- logger.error("\n%s", e)
93
  return json.dumps({'error': str(e)})
94
  except Exception as e:
95
- logger.error("\n%s", e)
96
  return json.dumps({'error': str(e)})
97
 
98
  if response:
@@ -115,8 +117,8 @@ async def cricket_source(mode: str, want: str) -> str:
115
  return json.dumps({"error": "No Available details right now!"})
116
 
117
  @mcp.tool()
118
- async def fetch_live_cricket_details(mode: Literal["live", "upcomming"])-> str:
119
- """ Get cricket live or upcomming match details
120
  Args:
121
  mode : Either "live" or "upcomming"
122
  """
@@ -137,7 +139,7 @@ async def live_cricket_scorecard(herf: str)-> str:
137
  (e.g, herf = "/live-cricket-scorecard/119495/cd-vs-hbh-7th-match-global-super-league-2025")
138
 
139
  Args:
140
- herf (str): herf for scorescard endpoint
141
  """
142
  scorecard_url = f"{BASE_CRICKET_URL}{herf}"
143
 
@@ -146,17 +148,15 @@ async def live_cricket_scorecard(herf: str)-> str:
146
  response = await client.get(url = scorecard_url)
147
  response.raise_for_status()
148
  except httpx.HTTPError as e:
149
- logger.error("\n%s", e)
150
  return json.dumps({"error": str(e)})
151
  except Exception as e:
152
- logger.error("\n%s", e)
153
  return json.dumps({'error': str(e)})
154
 
155
  # extract html container
156
  if response:
157
  html = BeautifulSoup(response.content, "html.parser")
158
  live_scorecard = html.find("div", timeout = "30000")
159
- details = live_scorecard.get_text(separator="\n", strip=True)
160
  return json.dumps({'output': str(details)})
161
  else:
162
  return json.dumps({'error': "No Available details right now"})
@@ -330,7 +330,5 @@ async def suggest_template(changes_summary: str, change_type: str) -> str:
330
  return json.dumps(suggestion, indent=2)
331
 
332
  if __name__ == "__main__":
333
- print("multitools-server is running πŸš€πŸš€πŸš€", file = sys.stderr)
334
- mcp.run(transport = 'stdio')
335
-
336
-
 
1
+ import logging, os, json, sys
2
+ from typing import Any, Literal, Optional
 
3
  from pathlib import Path
4
  import subprocess
 
 
 
5
  from dotenv import load_dotenv
6
+ load_dotenv()
7
 
8
  # -----------
9
  # Logging
10
  # ------------
11
+ logger = logging.getLogger(__name__)
12
+ logger.setLevel(logging.DEBUG)
 
 
 
13
 
14
+ fmt = "%(asctime)s -- %(levelname)s -- %(name)s -- %(message)s"
15
+ file_handler = logging.FileHandler("multitools-server.log")
16
+ file_handler.setFormatter(logging.Formatter(fmt))
17
 
 
18
  logger.addHandler(file_handler)
19
 
20
+ # Now import neccessary Packages
21
+ try:
22
+ from mcp.server.fastmcp import FastMCP
23
+ from bs4 import BeautifulSoup
24
+ import httpx
25
+ except ImportError as e:
26
+ logger.error("Got Error when Importing Packages: \n%s", e)
27
+ sys.exit(1)
28
+ except Exception as e:
29
+ logger.error("Got UnExcepted Error when Importing Packages: \n%s", e)
30
+ sys.exit(1)
31
+
32
  # -------------------------
33
  # Initiating FastMCP server
34
  # -------------------------
35
  mcp = FastMCP("multitools-server")
36
 
 
37
  # --------------
38
  # Configuration
39
  #---------------
40
+ BASE_CRICKET_URL = os.environ.get("BASE_CRICKET_URL")
41
+ logger.warning("Env variable BASE_CRICKET_URL Not-Found may cause error...") if not BASE_CRICKET_URL else logger.info("")
42
 
43
+ # PR template directory
44
  TEMPLATES_DIR = Path(__file__).parent / "templates"
45
+ logger.warning("TEMPLATES_DIR Not-Found may cause Error...") if not TEMPLATES_DIR else logger.info("TEMPLATES_DIR: \n%s", TEMPLATES_DIR)
46
 
47
  # Default PR templates
48
  DEFAULT_TEMPLATES = {
 
86
  url = f"{BASE_CRICKET_URL}/cricket-match/live-scores/upcoming-matches"
87
  else:
88
  error = f"Not Implemented: Currently there's no implementation to handle {mode}. Only handels live, upcomming"
 
89
  return json.dumps({"error": error})
90
 
91
  try:
92
  async with httpx.AsyncClient(timeout= 10.0) as client:
93
  response = await client.get(url= url)
94
+ response.raise_for_status() # if ain't 2xx it will raise HTTP error
95
  except httpx.HTTPError as e:
 
96
  return json.dumps({'error': str(e)})
97
  except Exception as e:
 
98
  return json.dumps({'error': str(e)})
99
 
100
  if response:
 
117
  return json.dumps({"error": "No Available details right now!"})
118
 
119
  @mcp.tool()
120
+ async def fetch_cricket_details(mode: Literal["live", "upcomming"])-> str:
121
+ """ Get cricket Live or Upcomming match details
122
  Args:
123
  mode : Either "live" or "upcomming"
124
  """
 
139
  (e.g, herf = "/live-cricket-scorecard/119495/cd-vs-hbh-7th-match-global-super-league-2025")
140
 
141
  Args:
142
+ herf: live cricket match scorecard endpoint
143
  """
144
  scorecard_url = f"{BASE_CRICKET_URL}{herf}"
145
 
 
148
  response = await client.get(url = scorecard_url)
149
  response.raise_for_status()
150
  except httpx.HTTPError as e:
 
151
  return json.dumps({"error": str(e)})
152
  except Exception as e:
 
153
  return json.dumps({'error': str(e)})
154
 
155
  # extract html container
156
  if response:
157
  html = BeautifulSoup(response.content, "html.parser")
158
  live_scorecard = html.find("div", timeout = "30000")
159
+ details = live_scorecard.get_text(separator=" ", strip=True)
160
  return json.dumps({'output': str(details)})
161
  else:
162
  return json.dumps({'error': "No Available details right now"})
 
330
  return json.dumps(suggestion, indent=2)
331
 
332
  if __name__ == "__main__":
333
+ logger.info("multitools-server is started πŸš€πŸš€πŸš€")
334
+ mcp.run(transport = 'stdio')