59 lines
1.2 KiB
Python
59 lines
1.2 KiB
Python
import asyncio
|
|
|
|
from mcp.client.session import ClientSession
|
|
from mcp.client.streamable_http import streamablehttp_client
|
|
|
|
|
|
class MCPClient:
|
|
|
|
def __init__(self, base_url="http://localhost:8081"):
|
|
self.base_url = base_url
|
|
|
|
async def _run(self, tool, arguments=None):
|
|
|
|
if arguments is None:
|
|
arguments = {}
|
|
|
|
async with streamablehttp_client(f"{self.base_url}/mcp") as (
|
|
read,
|
|
write,
|
|
_,
|
|
):
|
|
|
|
async with ClientSession(read, write) as session:
|
|
|
|
await session.initialize()
|
|
|
|
result = await session.call_tool(
|
|
tool,
|
|
arguments=arguments,
|
|
)
|
|
|
|
return result
|
|
|
|
def call_tool(self, tool, arguments=None):
|
|
|
|
return asyncio.run(
|
|
self._run(tool, arguments)
|
|
)
|
|
async def _list_tools(self):
|
|
|
|
async with streamablehttp_client(f"{self.base_url}/mcp") as (
|
|
read,
|
|
write,
|
|
_,
|
|
):
|
|
|
|
async with ClientSession(read, write) as session:
|
|
|
|
await session.initialize()
|
|
|
|
return await session.list_tools()
|
|
|
|
|
|
def list_tools(self):
|
|
|
|
return asyncio.run(
|
|
self._list_tools()
|
|
)
|