jarvis_mcp/client.py aktualisiert
This commit is contained in:
+25
-10
@@ -1,30 +1,45 @@
|
|||||||
|
# jarvis_mcp/client.py (oder wo du sie hast)
|
||||||
|
|
||||||
from mcp import ClientSession
|
from mcp import ClientSession
|
||||||
from mcp.client.streamable_http import streamable_http_client
|
from mcp.client.streamable_http import streamablehttp_client # wichtig: streamablehttp_client (ohne _)
|
||||||
|
|
||||||
|
|
||||||
class MCPClient:
|
class MCPClient:
|
||||||
def __init__(self, url: str):
|
def __init__(self, url: str):
|
||||||
self.url = url
|
self.url = url
|
||||||
self.session = None
|
self.session = None
|
||||||
self._client = None
|
self._client_context = None # Context Manager
|
||||||
|
|
||||||
async def connect(self):
|
async def connect(self):
|
||||||
self._client = streamable_http_client(self.url)
|
if self.session:
|
||||||
read, write = await self._client.__aenter__()
|
return
|
||||||
|
|
||||||
|
# Neuer Streamable HTTP Client (gibt 3 Werte zurück)
|
||||||
|
self._client_context = streamablehttp_client(
|
||||||
|
self.url,
|
||||||
|
terminate_on_close=False # wichtig für langlebige Verbindungen
|
||||||
|
)
|
||||||
|
|
||||||
|
read, write, _ = await self._client_context.__aenter__()
|
||||||
|
|
||||||
self.session = ClientSession(read, write)
|
self.session = ClientSession(read, write)
|
||||||
await self.session.initialize()
|
await self.session.initialize()
|
||||||
|
|
||||||
|
print("✅ MCP Verbindung hergestellt")
|
||||||
|
|
||||||
async def list_tools(self):
|
async def list_tools(self):
|
||||||
if not self.session:
|
await self.connect()
|
||||||
await self.connect()
|
|
||||||
return await self.session.list_tools()
|
return await self.session.list_tools()
|
||||||
|
|
||||||
async def call_tool(self, name: str, arguments: dict):
|
async def call_tool(self, name: str, arguments: dict):
|
||||||
if not self.session:
|
await self.connect()
|
||||||
await self.connect()
|
|
||||||
return await self.session.call_tool(name, arguments)
|
return await self.session.call_tool(name, arguments)
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
if self._client:
|
if self._client_context:
|
||||||
await self._client.__aexit__(None, None, None)
|
await self._client_context.__aexit__(None, None, None)
|
||||||
|
self._client_context = None
|
||||||
|
if self.session:
|
||||||
|
# Session schließen falls nötig
|
||||||
|
await self.session.close()
|
||||||
|
self.session = None
|
||||||
Reference in New Issue
Block a user