harvesthealth commited on
Commit
61d7ea4
·
verified ·
1 Parent(s): 6552277

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +34 -27
app.py CHANGED
@@ -73,6 +73,9 @@ huge_llm = ChatOpenAI(
73
  checkpointer = MemorySaver()
74
  long_term_store = InMemoryStore()
75
 
 
 
 
76
  # Schemas for Memory
77
  class UserPreferences(BaseModel):
78
  """Updated user preferences and project context."""
@@ -187,15 +190,14 @@ async def get_hf_logs(repo_id: str, log_type: Literal["build", "run"] = "run"):
187
  headers = {"Authorization": f"Bearer {token}"}
188
 
189
  try:
190
- # Since logs are SSE, we just take a snapshot of recent entries
191
- # In a real scenario, we might want to use a streaming client, but for tool use, a snippet is better.
192
  response = requests.get(url, headers=headers, timeout=10)
193
- # We only take the last 2000 characters to avoid context overflow
194
  return response.text[-2000:]
195
  except Exception as e:
196
  return f"Error fetching logs: {e}"
197
 
198
  async def get_all_tools():
 
199
  # 1. Custom Tools
200
  custom_tools = [
201
  Tool(
@@ -216,29 +218,33 @@ async def get_all_tools():
216
  ]
217
 
218
  # 2. MCP Tools using MultiServerMCPClient
219
- mcp_config = {
220
- "jules": {
221
- "transport": "stdio",
222
- "command": "python3",
223
- "args": ["mcp/mcp_jules.py"],
224
- "env": os.environ.copy()
225
- },
226
- "github": {
227
- "transport": "stdio",
228
- "command": "npx",
229
- "args": ["-y", "@modelcontextprotocol/server-github"],
230
- "env": os.environ.copy()
 
 
231
  }
232
- }
233
-
 
 
 
 
 
234
  try:
235
- logger.info("Connecting to MCP servers...")
236
- mcp_client = MultiServerMCPClient(mcp_config)
237
- mcp_tools = await mcp_client.get_tools()
238
- logger.info(f"Successfully loaded {len(mcp_tools)} tools from MCP servers.")
239
  return custom_tools + mcp_tools
240
  except Exception as e:
241
- logger.error(f"Failed to load MCP tools: {e}", exc_info=True)
242
  return custom_tools
243
 
244
  # LangGraph Nodes
@@ -611,8 +617,6 @@ async def handle_monitor_session(session_id):
611
  else: log_entries.append(f"[{t}] ACTIVITY: {json.dumps(act)[:100]}...")
612
  log_text = "\n\n".join(log_entries)
613
 
614
- # Simple stuck detection: if no activity in 15 mins (if we had actual timestamps to compare)
615
- # For now, just show status
616
  if status == "AWAITING_USER_FEEDBACK" or status == "AWAITING_PLAN_APPROVAL":
617
  status = f"⚠️ {status}"
618
 
@@ -651,7 +655,11 @@ async def handle_test():
651
  jules_list = next((t for t in tools if t.name == "list_sources"), None)
652
  if jules_list:
653
  j_res = await jules_list.ainvoke({})
654
- sources = j_res.get('sources', []) if isinstance(j_res, dict) else []
 
 
 
 
655
  results.append(f"Jules API (List Sources): OK (Found {len(sources)})")
656
  else: results.append("Jules API: Tool not found.")
657
  except Exception as e: results.append(f"MCP Servers: FAILED ({e})")
@@ -715,13 +723,12 @@ with gr.Blocks() as demo:
715
 
716
  nudge_output = gr.Textbox(label="Nudge Result")
717
 
718
- # Automated monitoring timer
719
  auto_timer = gr.Timer(value=30)
720
  auto_timer.tick(handle_monitor_session, inputs=[mon_session_id], outputs=[activity_log, session_state, last_activity])
721
 
722
  async def start_comm_and_monitor(repo, prof, space, sdk, deploy, token_var):
723
  res, sid = await handle_jules_comm(repo, prof, space, sdk, deploy, token_var)
724
- return res, sid, sid # Update comm_output, mon_session_id and its internal state
725
 
726
  comm_btn.click(start_comm_and_monitor, [repo_input, hf_profile_in, hf_space_in, hf_sdk_in, hf_deploy_check, hf_token_var_in], [comm_output, mon_session_id])
727
  refresh_btn.click(handle_monitor_session, inputs=[mon_session_id], outputs=[activity_log, session_state, last_activity])
 
73
  checkpointer = MemorySaver()
74
  long_term_store = InMemoryStore()
75
 
76
+ # Global MCP Client to avoid process leaks
77
+ GLOBAL_MCP_CLIENT = None
78
+
79
  # Schemas for Memory
80
  class UserPreferences(BaseModel):
81
  """Updated user preferences and project context."""
 
190
  headers = {"Authorization": f"Bearer {token}"}
191
 
192
  try:
193
+ # Snap snapshot of recent logs
 
194
  response = requests.get(url, headers=headers, timeout=10)
 
195
  return response.text[-2000:]
196
  except Exception as e:
197
  return f"Error fetching logs: {e}"
198
 
199
  async def get_all_tools():
200
+ global GLOBAL_MCP_CLIENT
201
  # 1. Custom Tools
202
  custom_tools = [
203
  Tool(
 
218
  ]
219
 
220
  # 2. MCP Tools using MultiServerMCPClient
221
+ if GLOBAL_MCP_CLIENT is None:
222
+ mcp_config = {
223
+ "jules": {
224
+ "transport": "stdio",
225
+ "command": "python3",
226
+ "args": ["mcp/mcp_jules.py"],
227
+ "env": os.environ.copy()
228
+ },
229
+ "github": {
230
+ "transport": "stdio",
231
+ "command": "npx",
232
+ "args": ["-y", "@modelcontextprotocol/server-github"],
233
+ "env": os.environ.copy()
234
+ }
235
  }
236
+ try:
237
+ logger.info("Initializing GLOBAL MCP client...")
238
+ GLOBAL_MCP_CLIENT = MultiServerMCPClient(mcp_config)
239
+ except Exception as e:
240
+ logger.error(f"Failed to initialize MCP client: {e}")
241
+ return custom_tools
242
+
243
  try:
244
+ mcp_tools = await GLOBAL_MCP_CLIENT.get_tools()
 
 
 
245
  return custom_tools + mcp_tools
246
  except Exception as e:
247
+ logger.error(f"Failed to load MCP tools: {e}")
248
  return custom_tools
249
 
250
  # LangGraph Nodes
 
617
  else: log_entries.append(f"[{t}] ACTIVITY: {json.dumps(act)[:100]}...")
618
  log_text = "\n\n".join(log_entries)
619
 
 
 
620
  if status == "AWAITING_USER_FEEDBACK" or status == "AWAITING_PLAN_APPROVAL":
621
  status = f"⚠️ {status}"
622
 
 
655
  jules_list = next((t for t in tools if t.name == "list_sources"), None)
656
  if jules_list:
657
  j_res = await jules_list.ainvoke({})
658
+ sources = []
659
+ if isinstance(j_res, dict): sources = j_res.get('sources', [])
660
+ elif isinstance(j_res, str):
661
+ try: sources = json.loads(j_res).get('sources', [])
662
+ except: pass
663
  results.append(f"Jules API (List Sources): OK (Found {len(sources)})")
664
  else: results.append("Jules API: Tool not found.")
665
  except Exception as e: results.append(f"MCP Servers: FAILED ({e})")
 
723
 
724
  nudge_output = gr.Textbox(label="Nudge Result")
725
 
 
726
  auto_timer = gr.Timer(value=30)
727
  auto_timer.tick(handle_monitor_session, inputs=[mon_session_id], outputs=[activity_log, session_state, last_activity])
728
 
729
  async def start_comm_and_monitor(repo, prof, space, sdk, deploy, token_var):
730
  res, sid = await handle_jules_comm(repo, prof, space, sdk, deploy, token_var)
731
+ return res, sid, sid
732
 
733
  comm_btn.click(start_comm_and_monitor, [repo_input, hf_profile_in, hf_space_in, hf_sdk_in, hf_deploy_check, hf_token_var_in], [comm_output, mon_session_id])
734
  refresh_btn.click(handle_monitor_session, inputs=[mon_session_id], outputs=[activity_log, session_state, last_activity])