LiamKhoaLe commited on
Commit
ffcfd50
·
1 Parent(s): c67b4e7

Debug MCP #2

Browse files
Files changed (9) hide show
  1. app.py +28 -3
  2. client.py +247 -0
  3. indexing.py +1 -1
  4. mcp.py +57 -10
  5. reasoning.py +1 -1
  6. search.py +1 -1
  7. supervisor.py +12 -6
  8. utils.py +1 -1
  9. voice.py +1 -1
app.py CHANGED
@@ -6,7 +6,7 @@ from logger import logger
6
  from config import DEFAULT_MEDICAL_MODEL
7
  import config
8
  from models import initialize_medical_model, initialize_tts_model
9
- from mcp import MCP_AVAILABLE
10
  from ui import create_demo
11
 
12
  if __name__ == "__main__":
@@ -27,9 +27,34 @@ if __name__ == "__main__":
27
 
28
  # Check Gemini MCP availability
29
  if MCP_AVAILABLE:
30
- logger.info("✅ Gemini MCP is available for translation, summarization, document parsing, and transcription")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  else:
32
- logger.info("ℹ️ Gemini MCP not available - app will use fallback methods (direct API calls)")
33
  logger.info(" This is normal and the app will continue to work. MCP is optional.")
34
 
35
  logger.info("Model preloading complete!")
 
6
  from config import DEFAULT_MEDICAL_MODEL
7
  import config
8
  from models import initialize_medical_model, initialize_tts_model
9
+ from client import MCP_AVAILABLE
10
  from ui import create_demo
11
 
12
  if __name__ == "__main__":
 
27
 
28
  # Check Gemini MCP availability
29
  if MCP_AVAILABLE:
30
+ logger.info("✅ Gemini MCP SDK is available")
31
+ if config.GEMINI_API_KEY:
32
+ logger.info(f"✅ GEMINI_API_KEY is set: {config.GEMINI_API_KEY[:10]}...{config.GEMINI_API_KEY[-4:]}")
33
+ # Test MCP connection asynchronously (don't block startup)
34
+ try:
35
+ import asyncio
36
+ from client import test_mcp_connection
37
+ try:
38
+ loop = asyncio.get_event_loop()
39
+ if loop.is_running():
40
+ # If loop is running, schedule test in background
41
+ logger.info("ℹ️ Testing MCP connection in background...")
42
+ else:
43
+ # Test synchronously
44
+ result = loop.run_until_complete(test_mcp_connection())
45
+ if result:
46
+ logger.info("✅ MCP connection test passed - Gemini MCP is ready!")
47
+ else:
48
+ logger.warning("⚠️ MCP connection test failed - will use fallback methods")
49
+ except Exception as e:
50
+ logger.warning(f"Could not test MCP connection: {e}")
51
+ except Exception as e:
52
+ logger.debug(f"MCP connection test skipped: {e}")
53
+ else:
54
+ logger.warning("⚠️ GEMINI_API_KEY not set - Gemini MCP features will not work")
55
+ logger.warning(" Set it in Hugging Face Space secrets or environment variables")
56
  else:
57
+ logger.info("ℹ️ Gemini MCP SDK not available - app will use fallback methods (direct API calls)")
58
  logger.info(" This is normal and the app will continue to work. MCP is optional.")
59
 
60
  logger.info("Model preloading complete!")
client.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP session management and tool caching"""
2
+ import os
3
+ import time
4
+ import asyncio
5
+ from logger import logger
6
+ import config
7
+
8
+ # MCP imports
9
+ MCP_CLIENT_INFO = None
10
+ MCP_AVAILABLE = False
11
+ try:
12
+ from mcp import ClientSession, StdioServerParameters
13
+ from mcp import types as mcp_types
14
+ from mcp.client.stdio import stdio_client
15
+ MCP_AVAILABLE = True
16
+ try:
17
+ import nest_asyncio
18
+ nest_asyncio.apply()
19
+ except ImportError:
20
+ pass
21
+ MCP_CLIENT_INFO = mcp_types.Implementation(
22
+ name="MedLLM-Agent",
23
+ version=os.environ.get("SPACE_VERSION", "local"),
24
+ )
25
+ logger.info("✅ MCP SDK imported successfully")
26
+ except ImportError as e:
27
+ logger.warning(f"❌ MCP SDK import failed: {e}")
28
+ logger.info(" Install with: pip install mcp>=0.1.0")
29
+ logger.info(" The app will continue to work with fallback functionality (direct API calls)")
30
+ MCP_AVAILABLE = False
31
+ MCP_CLIENT_INFO = None
32
+ except Exception as e:
33
+ logger.error(f"❌ Unexpected error initializing MCP: {type(e).__name__}: {e}")
34
+ logger.info(" The app will continue to work with fallback functionality")
35
+ MCP_AVAILABLE = False
36
+ MCP_CLIENT_INFO = None
37
+
38
+
39
+ async def get_mcp_session():
40
+ """Get or create MCP client session with proper context management"""
41
+ if not MCP_AVAILABLE:
42
+ logger.warning("MCP not available - SDK not installed")
43
+ return None
44
+
45
+ if config.global_mcp_session is not None:
46
+ return config.global_mcp_session
47
+
48
+ try:
49
+ mcp_env = os.environ.copy()
50
+ if config.GEMINI_API_KEY:
51
+ mcp_env["GEMINI_API_KEY"] = config.GEMINI_API_KEY
52
+ logger.info(f"✅ GEMINI_API_KEY found: {config.GEMINI_API_KEY[:10]}...{config.GEMINI_API_KEY[-4:]}")
53
+ else:
54
+ logger.warning("❌ GEMINI_API_KEY not set in environment. Gemini MCP features will not work.")
55
+ logger.warning(" Set it with: export GEMINI_API_KEY='your-api-key'")
56
+ return None
57
+
58
+ if os.environ.get("GEMINI_MODEL"):
59
+ mcp_env["GEMINI_MODEL"] = os.environ.get("GEMINI_MODEL")
60
+ if os.environ.get("GEMINI_TIMEOUT"):
61
+ mcp_env["GEMINI_TIMEOUT"] = os.environ.get("GEMINI_TIMEOUT")
62
+ if os.environ.get("GEMINI_MAX_OUTPUT_TOKENS"):
63
+ mcp_env["GEMINI_MAX_OUTPUT_TOKENS"] = os.environ.get("GEMINI_MAX_OUTPUT_TOKENS")
64
+ if os.environ.get("GEMINI_TEMPERATURE"):
65
+ mcp_env["GEMINI_TEMPERATURE"] = os.environ.get("GEMINI_TEMPERATURE")
66
+
67
+ logger.info(f"Creating MCP client session... (command: {config.MCP_SERVER_COMMAND} {config.MCP_SERVER_ARGS})")
68
+
69
+ server_params = StdioServerParameters(
70
+ command=config.MCP_SERVER_COMMAND,
71
+ args=config.MCP_SERVER_ARGS,
72
+ env=mcp_env
73
+ )
74
+
75
+ stdio_ctx = stdio_client(server_params)
76
+ read, write = await stdio_ctx.__aenter__()
77
+
78
+ session = ClientSession(
79
+ read,
80
+ write,
81
+ client_info=MCP_CLIENT_INFO,
82
+ )
83
+
84
+ try:
85
+ await session.__aenter__()
86
+ init_result = await session.initialize()
87
+ server_info = getattr(init_result, "serverInfo", None)
88
+ server_name = getattr(server_info, "name", "unknown")
89
+ server_version = getattr(server_info, "version", "unknown")
90
+ logger.info(f"✅ MCP session initialized successfully (server={server_name} v{server_version})")
91
+ except Exception as e:
92
+ error_msg = str(e)
93
+ error_type = type(e).__name__
94
+ logger.error(f"❌ MCP session initialization failed: {error_type}: {error_msg}")
95
+ logger.error(f" This might be due to:")
96
+ logger.error(f" - Invalid GEMINI_API_KEY")
97
+ logger.error(f" - agent.py server not starting correctly")
98
+ logger.error(f" - Network/firewall issues")
99
+ import traceback
100
+ logger.debug(f" Full traceback: {traceback.format_exc()}")
101
+ try:
102
+ await session.__aexit__(None, None, None)
103
+ except Exception:
104
+ pass
105
+ try:
106
+ await stdio_ctx.__aexit__(None, None, None)
107
+ except Exception:
108
+ pass
109
+ return None
110
+
111
+ config.global_mcp_session = session
112
+ config.global_mcp_stdio_ctx = stdio_ctx
113
+ logger.info("✅ MCP client session created successfully")
114
+ return session
115
+ except Exception as e:
116
+ error_type = type(e).__name__
117
+ error_msg = str(e)
118
+ logger.error(f"❌ Failed to create MCP client session: {error_type}: {error_msg}")
119
+ config.global_mcp_session = None
120
+ config.global_mcp_stdio_ctx = None
121
+ return None
122
+
123
+
124
+ def invalidate_mcp_tools_cache():
125
+ """Invalidate cached MCP tool metadata"""
126
+ config.global_mcp_tools_cache = {"timestamp": 0.0, "tools": None}
127
+
128
+
129
+ async def get_cached_mcp_tools(force_refresh: bool = False):
130
+ """Return cached MCP tools list to avoid repeated list_tools calls"""
131
+ if not MCP_AVAILABLE:
132
+ return []
133
+
134
+ now = time.time()
135
+ if (
136
+ not force_refresh
137
+ and config.global_mcp_tools_cache["tools"]
138
+ and now - config.global_mcp_tools_cache["timestamp"] < config.MCP_TOOLS_CACHE_TTL
139
+ ):
140
+ return config.global_mcp_tools_cache["tools"]
141
+
142
+ session = await get_mcp_session()
143
+ if session is None:
144
+ return []
145
+
146
+ try:
147
+ tools_resp = await session.list_tools()
148
+ tools_list = list(getattr(tools_resp, "tools", []) or [])
149
+ config.global_mcp_tools_cache = {"timestamp": now, "tools": tools_list}
150
+ return tools_list
151
+ except Exception as e:
152
+ logger.error(f"Failed to refresh MCP tools: {e}")
153
+ invalidate_mcp_tools_cache()
154
+ return []
155
+
156
+
157
+ async def test_mcp_connection() -> bool:
158
+ """Test MCP connection and return True if successful"""
159
+ if not MCP_AVAILABLE:
160
+ logger.warning("Cannot test MCP: SDK not available")
161
+ return False
162
+
163
+ if not config.GEMINI_API_KEY:
164
+ logger.warning("Cannot test MCP: GEMINI_API_KEY not set")
165
+ return False
166
+
167
+ try:
168
+ session = await get_mcp_session()
169
+ if session is None:
170
+ logger.warning("MCP connection test failed: Could not create session")
171
+ return False
172
+
173
+ # Try to list tools as a connectivity test
174
+ tools = await get_cached_mcp_tools()
175
+ if tools:
176
+ logger.info(f"✅ MCP connection test successful! Found {len(tools)} tools")
177
+ return True
178
+ else:
179
+ logger.warning("MCP connection test: Session created but no tools found")
180
+ return False
181
+ except Exception as e:
182
+ logger.error(f"MCP connection test failed: {type(e).__name__}: {e}")
183
+ return False
184
+
185
+
186
+ async def call_agent(user_prompt: str, system_prompt: str = None, files: list = None, model: str = None, temperature: float = 0.2) -> str:
187
+ """Call Gemini MCP generate_content tool"""
188
+ if not MCP_AVAILABLE:
189
+ logger.debug("MCP not available for Gemini call")
190
+ return ""
191
+
192
+ if not config.GEMINI_API_KEY:
193
+ logger.warning("GEMINI_API_KEY not set - cannot use Gemini MCP")
194
+ return ""
195
+
196
+ try:
197
+ session = await get_mcp_session()
198
+ if session is None:
199
+ logger.warning("Failed to get MCP session for Gemini call - check GEMINI_API_KEY and agent.py")
200
+ # Invalidate session to force retry on next call
201
+ config.global_mcp_session = None
202
+ return ""
203
+
204
+ tools = await get_cached_mcp_tools()
205
+ if not tools:
206
+ tools = await get_cached_mcp_tools(force_refresh=True)
207
+ if not tools:
208
+ logger.error("Unable to obtain MCP tool catalog for Gemini calls")
209
+ return ""
210
+
211
+ generate_tool = None
212
+ for tool in tools:
213
+ if tool.name == "generate_content" or "generate_content" in tool.name.lower():
214
+ generate_tool = tool
215
+ logger.info(f"Found Gemini MCP tool: {tool.name}")
216
+ break
217
+
218
+ if not generate_tool:
219
+ logger.warning(f"Gemini MCP generate_content tool not found. Available tools: {[t.name for t in tools]}")
220
+ invalidate_mcp_tools_cache()
221
+ return ""
222
+
223
+ arguments = {
224
+ "user_prompt": user_prompt
225
+ }
226
+ if system_prompt:
227
+ arguments["system_prompt"] = system_prompt
228
+ if files:
229
+ arguments["files"] = files
230
+ if model:
231
+ arguments["model"] = model
232
+ if temperature is not None:
233
+ arguments["temperature"] = temperature
234
+
235
+ result = await session.call_tool(generate_tool.name, arguments=arguments)
236
+
237
+ if hasattr(result, 'content') and result.content:
238
+ for item in result.content:
239
+ if hasattr(item, 'text'):
240
+ response_text = item.text.strip()
241
+ return response_text
242
+ logger.warning("⚠️ Gemini MCP returned empty or invalid result")
243
+ return ""
244
+ except Exception as e:
245
+ logger.error(f"Gemini MCP call error: {e}")
246
+ return ""
247
+
indexing.py CHANGED
@@ -21,7 +21,7 @@ from llama_index.core.node_parser import (
21
  from llama_index.core.storage.docstore import SimpleDocumentStore
22
  from tqdm import tqdm
23
  from logger import logger
24
- from mcp import MCP_AVAILABLE, call_agent
25
  import config
26
  from models import get_llm_for_rag, get_or_create_embed_model
27
 
 
21
  from llama_index.core.storage.docstore import SimpleDocumentStore
22
  from tqdm import tqdm
23
  from logger import logger
24
+ from client import MCP_AVAILABLE, call_agent
25
  import config
26
  from models import get_llm_for_rag, get_or_create_embed_model
27
 
mcp.py CHANGED
@@ -7,28 +7,31 @@ import config
7
 
8
  # MCP imports
9
  MCP_CLIENT_INFO = None
 
10
  try:
11
  from mcp import ClientSession, StdioServerParameters
12
  from mcp import types as mcp_types
13
  from mcp.client.stdio import stdio_client
 
14
  try:
15
  import nest_asyncio
16
  nest_asyncio.apply()
17
  except ImportError:
18
  pass
19
- MCP_AVAILABLE = True
20
  MCP_CLIENT_INFO = mcp_types.Implementation(
21
  name="MedLLM-Agent",
22
  version=os.environ.get("SPACE_VERSION", "local"),
23
  )
 
24
  except ImportError as e:
25
- logger.warning(f"MCP SDK not available: {e}")
26
- logger.info("The app will continue to work with fallback functionality (direct API calls)")
 
27
  MCP_AVAILABLE = False
28
  MCP_CLIENT_INFO = None
29
  except Exception as e:
30
- logger.error(f"Unexpected error initializing MCP: {e}")
31
- logger.info("The app will continue to work with fallback functionality")
32
  MCP_AVAILABLE = False
33
  MCP_CLIENT_INFO = None
34
 
@@ -46,8 +49,11 @@ async def get_mcp_session():
46
  mcp_env = os.environ.copy()
47
  if config.GEMINI_API_KEY:
48
  mcp_env["GEMINI_API_KEY"] = config.GEMINI_API_KEY
 
49
  else:
50
- logger.warning("GEMINI_API_KEY not set in environment. Gemini MCP features may not work.")
 
 
51
 
52
  if os.environ.get("GEMINI_MODEL"):
53
  mcp_env["GEMINI_MODEL"] = os.environ.get("GEMINI_MODEL")
@@ -58,7 +64,7 @@ async def get_mcp_session():
58
  if os.environ.get("GEMINI_TEMPERATURE"):
59
  mcp_env["GEMINI_TEMPERATURE"] = os.environ.get("GEMINI_TEMPERATURE")
60
 
61
- logger.info("Creating MCP client session...")
62
 
63
  server_params = StdioServerParameters(
64
  command=config.MCP_SERVER_COMMAND,
@@ -81,11 +87,17 @@ async def get_mcp_session():
81
  server_info = getattr(init_result, "serverInfo", None)
82
  server_name = getattr(server_info, "name", "unknown")
83
  server_version = getattr(server_info, "version", "unknown")
84
- logger.info(f"✅ MCP session initialized (server={server_name} v{server_version})")
85
  except Exception as e:
86
  error_msg = str(e)
87
  error_type = type(e).__name__
88
  logger.error(f"❌ MCP session initialization failed: {error_type}: {error_msg}")
 
 
 
 
 
 
89
  try:
90
  await session.__aexit__(None, None, None)
91
  except Exception:
@@ -142,16 +154,51 @@ async def get_cached_mcp_tools(force_refresh: bool = False):
142
  return []
143
 
144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  async def call_agent(user_prompt: str, system_prompt: str = None, files: list = None, model: str = None, temperature: float = 0.2) -> str:
146
  """Call Gemini MCP generate_content tool"""
147
  if not MCP_AVAILABLE:
148
- logger.warning("MCP not available for Gemini call")
 
 
 
 
149
  return ""
150
 
151
  try:
152
  session = await get_mcp_session()
153
  if session is None:
154
- logger.warning("Failed to get MCP session for Gemini call")
 
 
155
  return ""
156
 
157
  tools = await get_cached_mcp_tools()
 
7
 
8
  # MCP imports
9
  MCP_CLIENT_INFO = None
10
+ MCP_AVAILABLE = False
11
  try:
12
  from mcp import ClientSession, StdioServerParameters
13
  from mcp import types as mcp_types
14
  from mcp.client.stdio import stdio_client
15
+ MCP_AVAILABLE = True
16
  try:
17
  import nest_asyncio
18
  nest_asyncio.apply()
19
  except ImportError:
20
  pass
 
21
  MCP_CLIENT_INFO = mcp_types.Implementation(
22
  name="MedLLM-Agent",
23
  version=os.environ.get("SPACE_VERSION", "local"),
24
  )
25
+ logger.info("✅ MCP SDK imported successfully")
26
  except ImportError as e:
27
+ logger.warning(f"MCP SDK import failed: {e}")
28
+ logger.info(" Install with: pip install mcp>=0.1.0")
29
+ logger.info(" The app will continue to work with fallback functionality (direct API calls)")
30
  MCP_AVAILABLE = False
31
  MCP_CLIENT_INFO = None
32
  except Exception as e:
33
+ logger.error(f"Unexpected error initializing MCP: {type(e).__name__}: {e}")
34
+ logger.info(" The app will continue to work with fallback functionality")
35
  MCP_AVAILABLE = False
36
  MCP_CLIENT_INFO = None
37
 
 
49
  mcp_env = os.environ.copy()
50
  if config.GEMINI_API_KEY:
51
  mcp_env["GEMINI_API_KEY"] = config.GEMINI_API_KEY
52
+ logger.info(f"✅ GEMINI_API_KEY found: {config.GEMINI_API_KEY[:10]}...{config.GEMINI_API_KEY[-4:]}")
53
  else:
54
+ logger.warning("GEMINI_API_KEY not set in environment. Gemini MCP features will not work.")
55
+ logger.warning(" Set it with: export GEMINI_API_KEY='your-api-key'")
56
+ return None
57
 
58
  if os.environ.get("GEMINI_MODEL"):
59
  mcp_env["GEMINI_MODEL"] = os.environ.get("GEMINI_MODEL")
 
64
  if os.environ.get("GEMINI_TEMPERATURE"):
65
  mcp_env["GEMINI_TEMPERATURE"] = os.environ.get("GEMINI_TEMPERATURE")
66
 
67
+ logger.info(f"Creating MCP client session... (command: {config.MCP_SERVER_COMMAND} {config.MCP_SERVER_ARGS})")
68
 
69
  server_params = StdioServerParameters(
70
  command=config.MCP_SERVER_COMMAND,
 
87
  server_info = getattr(init_result, "serverInfo", None)
88
  server_name = getattr(server_info, "name", "unknown")
89
  server_version = getattr(server_info, "version", "unknown")
90
+ logger.info(f"✅ MCP session initialized successfully (server={server_name} v{server_version})")
91
  except Exception as e:
92
  error_msg = str(e)
93
  error_type = type(e).__name__
94
  logger.error(f"❌ MCP session initialization failed: {error_type}: {error_msg}")
95
+ logger.error(f" This might be due to:")
96
+ logger.error(f" - Invalid GEMINI_API_KEY")
97
+ logger.error(f" - agent.py server not starting correctly")
98
+ logger.error(f" - Network/firewall issues")
99
+ import traceback
100
+ logger.debug(f" Full traceback: {traceback.format_exc()}")
101
  try:
102
  await session.__aexit__(None, None, None)
103
  except Exception:
 
154
  return []
155
 
156
 
157
+ async def test_mcp_connection() -> bool:
158
+ """Test MCP connection and return True if successful"""
159
+ if not MCP_AVAILABLE:
160
+ logger.warning("Cannot test MCP: SDK not available")
161
+ return False
162
+
163
+ if not config.GEMINI_API_KEY:
164
+ logger.warning("Cannot test MCP: GEMINI_API_KEY not set")
165
+ return False
166
+
167
+ try:
168
+ session = await get_mcp_session()
169
+ if session is None:
170
+ logger.warning("MCP connection test failed: Could not create session")
171
+ return False
172
+
173
+ # Try to list tools as a connectivity test
174
+ tools = await get_cached_mcp_tools()
175
+ if tools:
176
+ logger.info(f"✅ MCP connection test successful! Found {len(tools)} tools")
177
+ return True
178
+ else:
179
+ logger.warning("MCP connection test: Session created but no tools found")
180
+ return False
181
+ except Exception as e:
182
+ logger.error(f"MCP connection test failed: {type(e).__name__}: {e}")
183
+ return False
184
+
185
+
186
  async def call_agent(user_prompt: str, system_prompt: str = None, files: list = None, model: str = None, temperature: float = 0.2) -> str:
187
  """Call Gemini MCP generate_content tool"""
188
  if not MCP_AVAILABLE:
189
+ logger.debug("MCP not available for Gemini call")
190
+ return ""
191
+
192
+ if not config.GEMINI_API_KEY:
193
+ logger.warning("GEMINI_API_KEY not set - cannot use Gemini MCP")
194
  return ""
195
 
196
  try:
197
  session = await get_mcp_session()
198
  if session is None:
199
+ logger.warning("Failed to get MCP session for Gemini call - check GEMINI_API_KEY and agent.py")
200
+ # Invalidate session to force retry on next call
201
+ config.global_mcp_session = None
202
  return ""
203
 
204
  tools = await get_cached_mcp_tools()
reasoning.py CHANGED
@@ -2,7 +2,7 @@
2
  import json
3
  import asyncio
4
  from logger import logger
5
- from mcp import MCP_AVAILABLE, call_agent
6
  from config import GEMINI_MODEL
7
 
8
  try:
 
2
  import json
3
  import asyncio
4
  from logger import logger
5
+ from client import MCP_AVAILABLE, call_agent
6
  from config import GEMINI_MODEL
7
 
8
  try:
search.py CHANGED
@@ -3,7 +3,7 @@ import json
3
  import asyncio
4
  import concurrent.futures
5
  from logger import logger
6
- from mcp import MCP_AVAILABLE, get_mcp_session, get_cached_mcp_tools, call_agent
7
  from config import GEMINI_MODEL
8
 
9
  try:
 
3
  import asyncio
4
  import concurrent.futures
5
  from logger import logger
6
+ from client import MCP_AVAILABLE, get_mcp_session, get_cached_mcp_tools, call_agent
7
  from config import GEMINI_MODEL
8
 
9
  try:
supervisor.py CHANGED
@@ -4,7 +4,7 @@ import asyncio
4
  import torch
5
  import spaces
6
  from logger import logger
7
- from mcp import MCP_AVAILABLE, call_agent
8
  from config import GEMINI_MODEL, GEMINI_MODEL_LITE
9
  from utils import format_prompt_manually
10
 
@@ -206,7 +206,7 @@ Keep contexts brief and factual. Avoid redundancy."""
206
  def gemini_supervisor_breakdown(query: str, use_rag: bool, use_web_search: bool, time_elapsed: float, max_duration: int = 120) -> dict:
207
  """Wrapper to obtain supervisor breakdown synchronously"""
208
  if not MCP_AVAILABLE:
209
- logger.warning("[GEMINI SUPERVISOR] MCP unavailable, using fallback breakdown")
210
  return {
211
  "sub_topics": [
212
  {"id": 1, "topic": "Core Question", "instruction": "Address the main medical question", "expected_tokens": 200, "priority": "high", "approach": "direct answer"},
@@ -220,16 +220,22 @@ def gemini_supervisor_breakdown(query: str, use_rag: bool, use_web_search: bool,
220
  loop = asyncio.get_event_loop()
221
  if loop.is_running():
222
  if nest_asyncio:
223
- return nest_asyncio.run(
224
- gemini_supervisor_breakdown_async(query, use_rag, use_web_search, time_elapsed, max_duration)
225
- )
 
 
 
 
226
  else:
227
  logger.error("[GEMINI SUPERVISOR] Nested breakdown execution failed: nest_asyncio not available")
 
228
  return loop.run_until_complete(
229
  gemini_supervisor_breakdown_async(query, use_rag, use_web_search, time_elapsed, max_duration)
230
  )
231
  except Exception as exc:
232
- logger.error(f"[GEMINI SUPERVISOR] Breakdown request failed: {exc}")
 
233
  return {
234
  "sub_topics": [
235
  {"id": 1, "topic": "Core Question", "instruction": "Address the main medical question", "expected_tokens": 200, "priority": "high", "approach": "direct answer"},
 
4
  import torch
5
  import spaces
6
  from logger import logger
7
+ from client import MCP_AVAILABLE, call_agent
8
  from config import GEMINI_MODEL, GEMINI_MODEL_LITE
9
  from utils import format_prompt_manually
10
 
 
206
  def gemini_supervisor_breakdown(query: str, use_rag: bool, use_web_search: bool, time_elapsed: float, max_duration: int = 120) -> dict:
207
  """Wrapper to obtain supervisor breakdown synchronously"""
208
  if not MCP_AVAILABLE:
209
+ logger.warning("[GEMINI SUPERVISOR] MCP SDK unavailable, using fallback breakdown")
210
  return {
211
  "sub_topics": [
212
  {"id": 1, "topic": "Core Question", "instruction": "Address the main medical question", "expected_tokens": 200, "priority": "high", "approach": "direct answer"},
 
220
  loop = asyncio.get_event_loop()
221
  if loop.is_running():
222
  if nest_asyncio:
223
+ try:
224
+ return nest_asyncio.run(
225
+ gemini_supervisor_breakdown_async(query, use_rag, use_web_search, time_elapsed, max_duration)
226
+ )
227
+ except Exception as e:
228
+ logger.error(f"[GEMINI SUPERVISOR] Async breakdown failed: {e}")
229
+ raise
230
  else:
231
  logger.error("[GEMINI SUPERVISOR] Nested breakdown execution failed: nest_asyncio not available")
232
+ raise RuntimeError("nest_asyncio not available")
233
  return loop.run_until_complete(
234
  gemini_supervisor_breakdown_async(query, use_rag, use_web_search, time_elapsed, max_duration)
235
  )
236
  except Exception as exc:
237
+ logger.error(f"[GEMINI SUPERVISOR] Breakdown request failed: {type(exc).__name__}: {exc}")
238
+ logger.warning("[GEMINI SUPERVISOR] Falling back to default breakdown")
239
  return {
240
  "sub_topics": [
241
  {"id": 1, "topic": "Core Question", "instruction": "Address the main medical question", "expected_tokens": 200, "priority": "high", "approach": "direct answer"},
utils.py CHANGED
@@ -2,7 +2,7 @@
2
  import asyncio
3
  from langdetect import detect, LangDetectException
4
  from logger import logger
5
- from mcp import MCP_AVAILABLE, call_agent
6
  from config import GEMINI_MODEL_LITE
7
 
8
  try:
 
2
  import asyncio
3
  from langdetect import detect, LangDetectException
4
  from logger import logger
5
+ from client import MCP_AVAILABLE, call_agent
6
  from config import GEMINI_MODEL_LITE
7
 
8
  try:
voice.py CHANGED
@@ -4,7 +4,7 @@ import asyncio
4
  import tempfile
5
  import soundfile as sf
6
  from logger import logger
7
- from mcp import MCP_AVAILABLE, call_agent, get_mcp_session, get_cached_mcp_tools
8
  import config
9
  from models import TTS_AVAILABLE, initialize_tts_model
10
 
 
4
  import tempfile
5
  import soundfile as sf
6
  from logger import logger
7
+ from client import MCP_AVAILABLE, call_agent, get_mcp_session, get_cached_mcp_tools
8
  import config
9
  from models import TTS_AVAILABLE, initialize_tts_model
10