addition of debug print messages, bug in adapter, initializing sessions, line 113
This commit is contained in:
parent
4e0d3a7438
commit
88c647a428
@ -20,6 +20,7 @@ import os
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import asyncio
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import httpx
|
import httpx
|
||||||
@ -29,6 +30,9 @@ from backend.agent.mcp_server_adapter import MCPToolAdapter
|
|||||||
|
|
||||||
# ── mcp server initialization ────────────────────────────────────────────────────────────────
|
# ── mcp server initialization ────────────────────────────────────────────────────────────────
|
||||||
adapter = MCPToolAdapter()
|
adapter = MCPToolAdapter()
|
||||||
|
print("MCPToolAdapter created. Listing all tools from servers...")
|
||||||
|
asyncio.run(adapter.initialize_all_servers())
|
||||||
|
print("listed tools from all servers")
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
@ -197,10 +201,11 @@ MAX_HISTORY_CHARS = 80_000
|
|||||||
def build_all_tool_description() -> str:
|
def build_all_tool_description() -> str:
|
||||||
"""Get relevant tools from the MCP servers based on the query."""
|
"""Get relevant tools from the MCP servers based on the query."""
|
||||||
|
|
||||||
relevant_tools = adapter.get_all_tools()
|
all_tools = adapter.get_all_tools()
|
||||||
|
print(f"Building tool description for {len(all_tools)} tools.")
|
||||||
|
|
||||||
descriptions = []
|
descriptions = []
|
||||||
for tool in relevant_tools:
|
for tool in all_tools:
|
||||||
params = tool.inputSchema.get("properties", {})
|
params = tool.inputSchema.get("properties", {})
|
||||||
if params:
|
if params:
|
||||||
param_lines = []
|
param_lines = []
|
||||||
|
|||||||
@ -9,8 +9,8 @@ from mcp.client.stdio import stdio_client
|
|||||||
class MCPToolAdapter:
|
class MCPToolAdapter:
|
||||||
def __init__(self, config_path: str = "mcp_server_config.json"):
|
def __init__(self, config_path: str = "mcp_server_config.json"):
|
||||||
self.config_path = config_path
|
self.config_path = config_path
|
||||||
self.sessions: Dict[str, ClientSession] = {}
|
self.servers: Dict[str, Dict] = {}
|
||||||
self.exit_stack: Dict[str, Any] = {}
|
#self.exit_stack: Dict[str, Any] = {}
|
||||||
self.tool_registry: List[Dict[str, Any]] = []
|
self.tool_registry: List[Dict[str, Any]] = []
|
||||||
|
|
||||||
def _load_config(self) -> Dict[str, Any]:
|
def _load_config(self) -> Dict[str, Any]:
|
||||||
@ -27,46 +27,62 @@ class MCPToolAdapter:
|
|||||||
print(f"Error decoding JSON config: {e}")
|
print(f"Error decoding JSON config: {e}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
async def initialize_all_sessions(self):
|
async def initialize_all_servers(self):
|
||||||
"""Initialisiert alle konfigurierten MCP-Sessions und registriert die Tools."""
|
"""Lädt die Konfiguration und fragt alle Server ab, um die Tools zu registrieren."""
|
||||||
|
print("Initializing MCP sessions...")
|
||||||
config = self._load_config()
|
config = self._load_config()
|
||||||
|
print(f"Loaded config for servers: {list(config.keys())}")
|
||||||
|
|
||||||
for server_name, params in config.items():
|
for server_name, params in config.items():
|
||||||
print(f"Initializing session for {server_name}...")
|
print(f"Testing connection to {server_name}...")
|
||||||
|
|
||||||
|
self.servers[server_name] = params
|
||||||
|
|
||||||
server_params = StdioServerParameters(
|
server_params = StdioServerParameters(
|
||||||
command=params["command"],
|
command=params["command"],
|
||||||
args=params.get("args", []),
|
args=params.get("args", [])
|
||||||
env=params.get("env", None),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Verbindung aufbauen
|
# Verbindung aufbauen
|
||||||
transport_gen = stdio_client(server_params)
|
async with stdio_client(server_params) as (read_stream, write_stream):
|
||||||
read, write = await transport_gen.__aenter__()
|
print(f"Connected to {server_name}. Initializing session...")
|
||||||
session = ClientSession(read, write)
|
#print(f"read_stream: {read_stream}\nwrite_stream: {write_stream}")
|
||||||
await session.__aenter__()
|
async with ClientSession(read_stream, write_stream) as session:
|
||||||
await session.initialize()
|
await session.initialize()
|
||||||
|
print(f"Session initialized for {server_name}. Requesting tools...")
|
||||||
self.sessions[server_name] = session
|
result = await session.list_tools()
|
||||||
# Speichern für den Shutdown
|
print(f"Tools received from {server_name}: {result}")
|
||||||
self.exit_stack[server_name] = (transport_gen, session)
|
tools = result.tools
|
||||||
|
print(f"Tools received from {server_name}: {result}")
|
||||||
# Tools abrufen und registrieren
|
#tools = getattr(result, 'tools', [])
|
||||||
result = await session.list_tools()
|
|
||||||
# result ist oft ein Objekt, wir greifen auf das .tools Attribut zu
|
|
||||||
tools = getattr(result, 'tools', [])
|
|
||||||
|
|
||||||
for tool in tools:
|
for tool in tools:
|
||||||
# 'tool' ist hier meist ein Tool-Objekt vom MCP SDK
|
t_params = tool.inputSchema.get("properties", {})
|
||||||
|
if t_params:
|
||||||
|
param_lines = []
|
||||||
|
for pname, pinfo in params.items():
|
||||||
|
ptype = pinfo.get("type", "any")
|
||||||
|
pdesc = pinfo.get("description", "")
|
||||||
|
param_lines.append(f" - {pname} ({ptype}): {pdesc}")
|
||||||
|
param_str = "\n".join(param_lines)
|
||||||
|
else:
|
||||||
|
param_str = " (none)"
|
||||||
|
|
||||||
|
t_definition = f"- {tool.name}: {tool.description}\nParameters:\n{param_str}"
|
||||||
|
|
||||||
|
|
||||||
self.tool_registry.append({
|
self.tool_registry.append({
|
||||||
"server": server_name,
|
"server": server_name,
|
||||||
"name": tool.name,
|
"tool_name": tool.name,
|
||||||
"definition": tool
|
"tool_description": t_definition
|
||||||
})
|
})
|
||||||
|
|
||||||
|
print(f"Registered tool '{tool.name}' from {server_name}.")
|
||||||
|
|
||||||
print(f"Session for {server_name} ready. {len(tools)} tools found.")
|
print(f"Session for {server_name} ready. {len(tools)} tools found.")
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Failed to initialize {server_name}: {e}")
|
print(f"Failed to initialize {server_name}: {e}")
|
||||||
|
|
||||||
@ -83,11 +99,19 @@ class MCPToolAdapter:
|
|||||||
return f"Error: Tool '{tool_name}' not found in registry."
|
return f"Error: Tool '{tool_name}' not found in registry."
|
||||||
|
|
||||||
server_name = tool_entry["server"]
|
server_name = tool_entry["server"]
|
||||||
session = self.sessions.get(server_name)
|
server = self.servers.get(server_name)
|
||||||
|
|
||||||
|
if server:
|
||||||
|
server_params = StdioServerParameters(
|
||||||
|
command=server["command"],
|
||||||
|
args=server.get("args", [])
|
||||||
|
)
|
||||||
|
|
||||||
if session:
|
|
||||||
try:
|
try:
|
||||||
result = await session.call_tool(tool_name, arguments)
|
async with stdio_client(server_params) as (read_stream, write_stream):
|
||||||
|
async with ClientSession(read_stream, write_stream) as session:
|
||||||
|
await session.initialize()
|
||||||
|
result = await session.call_tool(tool_name, arguments)
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Error calling tool '{tool_name}' on server '{server_name}': {str(e)}"
|
return f"Error calling tool '{tool_name}' on server '{server_name}': {str(e)}"
|
||||||
@ -102,4 +126,15 @@ class MCPToolAdapter:
|
|||||||
await transport_gen.__aexit__(None, None, None)
|
await transport_gen.__aexit__(None, None, None)
|
||||||
print(f"Session for {server_name} shut down.")
|
print(f"Session for {server_name} shut down.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error during shutdown of {server_name}: {e}")
|
print(f"Error during shutdown of {server_name}: {e}")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
adapter = MCPToolAdapter()
|
||||||
|
asyncio.run(adapter.initialize_all_servers())
|
||||||
|
print("All servers initialized. Registered tools:")
|
||||||
|
for tool in adapter.get_all_tools():
|
||||||
|
print(f"- {tool['name']} (from {tool['server']})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@ -1,10 +1,10 @@
|
|||||||
{"FileSearchServer": {
|
{"FileSearchServer": {
|
||||||
"command": "python",
|
"command": "python3",
|
||||||
"args": ["servers/mcp_server_file_search.py"]
|
"args": ["servers/mcp_server_file_search.py"]
|
||||||
},
|
},
|
||||||
|
|
||||||
"WebSearchServer": {
|
"WebSearchServer": {
|
||||||
"command": "python",
|
"command": "python3",
|
||||||
"args": ["servers/mcp_server_web_search.py"],
|
"args": ["servers/mcp_server_web_search.py"],
|
||||||
"env": {
|
"env": {
|
||||||
"DDGS_API_KEY": "your_ddgs_api_key_here"
|
"DDGS_API_KEY": "your_ddgs_api_key_here"
|
||||||
@ -12,7 +12,7 @@
|
|||||||
},
|
},
|
||||||
|
|
||||||
"CodeExecutionServer": {
|
"CodeExecutionServer": {
|
||||||
"command": "python",
|
"command": "python3",
|
||||||
"args": ["servers/mcp_server_code_execution.py"]
|
"args": ["servers/mcp_server_code_execution.py"]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user