SiddanthEmani commited on
Commit
0de0bef
·
1 Parent(s): 29808c7

Fixed MCP URL and cleanup process

Browse files
Files changed (2) hide show
  1. app.py +5 -2
  2. client.py +42 -14
app.py CHANGED
@@ -1,4 +1,7 @@
1
- from client import demo
2
 
3
  if __name__ == "__main__":
4
- demo.launch()
 
 
 
 
1
+ from client import demo, cleanup
2
 
3
  if __name__ == "__main__":
4
+ try:
5
+ demo.launch()
6
+ finally:
7
+ cleanup()
client.py CHANGED
@@ -1,20 +1,22 @@
1
  import gradio as gr
 
2
 
3
  from smolagents import CodeAgent, InferenceClientModel
4
  from smolagents.mcp_client import MCPClient
5
 
6
- try:
7
- mcp_client = MCPClient(
8
- {
9
- "url": "http://localhost:7860/gradio_api/mcp/sse",
10
- }
11
- )
12
- tools = mcp_client.get_tools()
13
- model = InferenceClientModel()
14
- agent = CodeAgent(tools=[*tools], model=model)
15
 
16
- demo = gr.ChatInterface(
17
- fn=lambda message, history: str(agent.run(message)),
 
 
18
  type="messages",
19
  examples=["What is the capital of France?"],
20
  title="Agent with Gradio and MCP",
@@ -23,6 +25,32 @@ try:
23
  theme="ocean"
24
  )
25
 
26
- demo.launch()
27
- finally:
28
- mcp_client.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
 
4
  from smolagents import CodeAgent, InferenceClientModel
5
  from smolagents.mcp_client import MCPClient
6
 
7
+ # Determine if we're running locally or on HF Spaces
8
+ is_spaces = os.environ.get('SPACE_ID') is not None
9
+
10
+ # Define the MCP URL based on environment
11
+ mcp_url = "/gradio_api/mcp/sse" if is_spaces else "http://localhost:7860/gradio_api/mcp/sse"
12
+
13
+ # Initialize the client outside the try block, but don't connect yet
14
+ mcp_client = None
 
15
 
16
+ def create_demo():
17
+ # Creating the chatbot interface
18
+ return gr.ChatInterface(
19
+ fn=lambda message, history: str(agent.run(message)) if agent else "Agent not connected",
20
  type="messages",
21
  examples=["What is the capital of France?"],
22
  title="Agent with Gradio and MCP",
 
25
  theme="ocean"
26
  )
27
 
28
+ # Initialize the demo outside of the try-except
29
+ demo = None
30
+
31
+ try:
32
+ # Create and connect the MCP client
33
+ mcp_client = MCPClient({"url": mcp_url})
34
+ tools = mcp_client.get_tools()
35
+ model = InferenceClientModel()
36
+ agent = CodeAgent(tools=[*tools], model=model)
37
+
38
+ # Create the chat interface
39
+ demo = create_demo()
40
+
41
+ except Exception as e:
42
+ # If client connection fails, create a demo that shows the error
43
+ print(f"Error connecting to MCP server: {e}")
44
+ agent = None
45
+ demo = create_demo()
46
+
47
+ # Only close the client if it was successfully created
48
+ def cleanup():
49
+ if mcp_client:
50
+ try:
51
+ mcp_client.close()
52
+ except:
53
+ pass
54
+
55
+ # In app.py, we only import the demo object,
56
+ # so we don't need to call launch() here