Update app.py
Browse files
app.py
CHANGED
|
@@ -7,32 +7,20 @@ import aiohttp
|
|
| 7 |
from typing import Dict, Any, List, Tuple
|
| 8 |
from datetime import datetime
|
| 9 |
import os
|
|
|
|
|
|
|
| 10 |
|
| 11 |
class MCPClient:
|
| 12 |
"""MCP Client for communicating with the MCP server"""
|
| 13 |
|
| 14 |
def __init__(self, server_url: str):
|
| 15 |
self.server_url = server_url.rstrip('/')
|
| 16 |
-
self.session = None
|
| 17 |
|
| 18 |
-
|
| 19 |
-
"""
|
| 20 |
-
if not self.session:
|
| 21 |
-
self.session = aiohttp.ClientSession()
|
| 22 |
-
|
| 23 |
-
async def close_session(self):
|
| 24 |
-
"""Close aiohttp session"""
|
| 25 |
-
if self.session:
|
| 26 |
-
await self.session.close()
|
| 27 |
-
self.session = None
|
| 28 |
-
|
| 29 |
-
async def call_tool(self, tool_name: str, arguments: Dict[str, Any] = None) -> Dict[str, Any]:
|
| 30 |
-
"""Call a tool on the MCP server"""
|
| 31 |
if arguments is None:
|
| 32 |
arguments = {}
|
| 33 |
|
| 34 |
-
await self.initialize_session()
|
| 35 |
-
|
| 36 |
mcp_request = {
|
| 37 |
"jsonrpc": "2.0",
|
| 38 |
"id": 1,
|
|
@@ -44,7 +32,7 @@ class MCPClient:
|
|
| 44 |
}
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
f"{self.server_url}/mcp",
|
| 49 |
json=mcp_request,
|
| 50 |
headers={
|
|
@@ -52,28 +40,27 @@ class MCPClient:
|
|
| 52 |
"ngrok-skip-browser-warning": "true"
|
| 53 |
},
|
| 54 |
timeout=30
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
return
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
}
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
return {
|
| 69 |
"success": False,
|
| 70 |
"error": f"Connection error: {str(e)}"
|
| 71 |
}
|
| 72 |
|
| 73 |
-
|
| 74 |
-
"""
|
| 75 |
-
await self.initialize_session()
|
| 76 |
-
|
| 77 |
mcp_request = {
|
| 78 |
"jsonrpc": "2.0",
|
| 79 |
"id": 1,
|
|
@@ -81,7 +68,7 @@ class MCPClient:
|
|
| 81 |
}
|
| 82 |
|
| 83 |
try:
|
| 84 |
-
|
| 85 |
f"{self.server_url}/mcp",
|
| 86 |
json=mcp_request,
|
| 87 |
headers={
|
|
@@ -89,13 +76,14 @@ class MCPClient:
|
|
| 89 |
"ngrok-skip-browser-warning": "true"
|
| 90 |
},
|
| 91 |
timeout=30
|
| 92 |
-
)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
return []
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
-
print(f"Error listing tools: {str(e)}")
|
| 99 |
return []
|
| 100 |
|
| 101 |
class AIAssistant:
|
|
@@ -114,9 +102,9 @@ class AIAssistant:
|
|
| 114 |
self.mcp_client = mcp_client
|
| 115 |
self.available_tools = []
|
| 116 |
|
| 117 |
-
|
| 118 |
"""Initialize the assistant by fetching available tools"""
|
| 119 |
-
self.available_tools =
|
| 120 |
|
| 121 |
def get_system_prompt(self) -> str:
|
| 122 |
"""Generate system prompt with available tools"""
|
|
@@ -335,7 +323,7 @@ def test_connection(mcp_url):
|
|
| 335 |
except Exception as e:
|
| 336 |
return f"β Connection error: {str(e)}"
|
| 337 |
|
| 338 |
-
|
| 339 |
"""Initialize the AI assistant"""
|
| 340 |
global assistant, mcp_client
|
| 341 |
|
|
@@ -348,7 +336,7 @@ async def initialize_assistant(openai_key, mcp_url):
|
|
| 348 |
try:
|
| 349 |
mcp_client = MCPClient(mcp_url)
|
| 350 |
assistant = AIAssistant(openai_key, mcp_client)
|
| 351 |
-
|
| 352 |
return f"β
AI Assistant initialized with {len(assistant.available_tools)} tools available"
|
| 353 |
except Exception as e:
|
| 354 |
return f"β Failed to initialize: {str(e)}"
|
|
@@ -358,13 +346,13 @@ def chat_interface(message, history, openai_key, mcp_url):
|
|
| 358 |
global assistant
|
| 359 |
|
| 360 |
if not assistant:
|
| 361 |
-
init_result =
|
| 362 |
if "β" in init_result:
|
| 363 |
history.append([message, init_result])
|
| 364 |
return history, ""
|
| 365 |
|
| 366 |
try:
|
| 367 |
-
response, tool_info =
|
| 368 |
|
| 369 |
# Format response with tool info if available
|
| 370 |
if tool_info:
|
|
|
|
| 7 |
from typing import Dict, Any, List, Tuple
|
| 8 |
from datetime import datetime
|
| 9 |
import os
|
| 10 |
+
import threading
|
| 11 |
+
import concurrent.futures
|
| 12 |
|
| 13 |
class MCPClient:
|
| 14 |
"""MCP Client for communicating with the MCP server"""
|
| 15 |
|
| 16 |
def __init__(self, server_url: str):
|
| 17 |
self.server_url = server_url.rstrip('/')
|
|
|
|
| 18 |
|
| 19 |
+
def call_tool_sync(self, tool_name: str, arguments: Dict[str, Any] = None) -> Dict[str, Any]:
|
| 20 |
+
"""Synchronous tool call using requests instead of aiohttp"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
if arguments is None:
|
| 22 |
arguments = {}
|
| 23 |
|
|
|
|
|
|
|
| 24 |
mcp_request = {
|
| 25 |
"jsonrpc": "2.0",
|
| 26 |
"id": 1,
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
try:
|
| 35 |
+
response = requests.post(
|
| 36 |
f"{self.server_url}/mcp",
|
| 37 |
json=mcp_request,
|
| 38 |
headers={
|
|
|
|
| 40 |
"ngrok-skip-browser-warning": "true"
|
| 41 |
},
|
| 42 |
timeout=30
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if response.status_code == 200:
|
| 46 |
+
result = response.json()
|
| 47 |
+
if "result" in result and "content" in result["result"]:
|
| 48 |
+
content = result["result"]["content"][0]["text"]
|
| 49 |
+
return json.loads(content)
|
| 50 |
+
return result
|
| 51 |
+
else:
|
| 52 |
+
return {
|
| 53 |
+
"success": False,
|
| 54 |
+
"error": f"HTTP {response.status_code}: {response.text}"
|
| 55 |
+
}
|
| 56 |
except Exception as e:
|
| 57 |
return {
|
| 58 |
"success": False,
|
| 59 |
"error": f"Connection error: {str(e)}"
|
| 60 |
}
|
| 61 |
|
| 62 |
+
def list_tools_sync(self) -> List[Dict[str, Any]]:
|
| 63 |
+
"""Synchronous tool listing using requests"""
|
|
|
|
|
|
|
| 64 |
mcp_request = {
|
| 65 |
"jsonrpc": "2.0",
|
| 66 |
"id": 1,
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
try:
|
| 71 |
+
response = requests.post(
|
| 72 |
f"{self.server_url}/mcp",
|
| 73 |
json=mcp_request,
|
| 74 |
headers={
|
|
|
|
| 76 |
"ngrok-skip-browser-warning": "true"
|
| 77 |
},
|
| 78 |
timeout=30
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if response.status_code == 200:
|
| 82 |
+
result = response.json()
|
| 83 |
+
return result.get("result", {}).get("tools", [])
|
| 84 |
+
return []
|
| 85 |
except Exception as e:
|
| 86 |
+
print(f"Error listing tools: {str(e)}")
|
| 87 |
return []
|
| 88 |
|
| 89 |
class AIAssistant:
|
|
|
|
| 102 |
self.mcp_client = mcp_client
|
| 103 |
self.available_tools = []
|
| 104 |
|
| 105 |
+
def initialize(self):
|
| 106 |
"""Initialize the assistant by fetching available tools"""
|
| 107 |
+
self.available_tools = self.mcp_client.list_tools_sync()
|
| 108 |
|
| 109 |
def get_system_prompt(self) -> str:
|
| 110 |
"""Generate system prompt with available tools"""
|
|
|
|
| 323 |
except Exception as e:
|
| 324 |
return f"β Connection error: {str(e)}"
|
| 325 |
|
| 326 |
+
def initialize_assistant(openai_key, mcp_url):
|
| 327 |
"""Initialize the AI assistant"""
|
| 328 |
global assistant, mcp_client
|
| 329 |
|
|
|
|
| 336 |
try:
|
| 337 |
mcp_client = MCPClient(mcp_url)
|
| 338 |
assistant = AIAssistant(openai_key, mcp_client)
|
| 339 |
+
assistant.initialize()
|
| 340 |
return f"β
AI Assistant initialized with {len(assistant.available_tools)} tools available"
|
| 341 |
except Exception as e:
|
| 342 |
return f"β Failed to initialize: {str(e)}"
|
|
|
|
| 346 |
global assistant
|
| 347 |
|
| 348 |
if not assistant:
|
| 349 |
+
init_result = initialize_assistant(openai_key, mcp_url)
|
| 350 |
if "β" in init_result:
|
| 351 |
history.append([message, init_result])
|
| 352 |
return history, ""
|
| 353 |
|
| 354 |
try:
|
| 355 |
+
response, tool_info = assistant.process_message(message)
|
| 356 |
|
| 357 |
# Format response with tool info if available
|
| 358 |
if tool_info:
|