bstraehle commited on
Commit
19b980e
·
verified ·
1 Parent(s): 9a56b27

Create mcp/mcp_client.py

Browse files
Files changed (1) hide show
  1. agents/mcp/mcp_client.py +57 -0
agents/mcp/mcp_client.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from mcp.client.sse import sse_client
3
+ from mcp.client.session import ClientSession, DEFAULT_CLIENT_INFO
4
+ import anyio
5
+
6
+ MCP_SSE_URL = "https://bstraehle-mcp.hf.space/gradio_api/mcp/sse"
7
+ MCP_TOOL = "mcp_chess_analysis"
8
+
9
+ async def call_mcp_tool_async(mcp_url: str, tool_name: str, arguments: dict, timeout: int = 30) -> str:
10
+ """Call an MCP tool asynchronously.
11
+
12
+ Args:
13
+ mcp_url (str): The MCP SSE URL
14
+ tool_name (str): The name of the MCP tool to call
15
+ arguments (dict): The arguments to pass to the tool
16
+ timeout (int): Timeout in seconds (default: 30)
17
+
18
+ Returns:
19
+ str: The tool result as a string
20
+
21
+ Raises:
22
+ Exception: If the MCP call fails
23
+ """
24
+ try:
25
+ with anyio.fail_after(timeout):
26
+ async with sse_client(mcp_url) as (read, write):
27
+ async with ClientSession(read, write, client_info=DEFAULT_CLIENT_INFO) as session:
28
+ await session.initialize()
29
+ result = await session.call_tool(tool_name, arguments=arguments)
30
+
31
+ if result.content:
32
+ text_parts = [
33
+ item.text for item in result.content
34
+ if hasattr(item, 'text')
35
+ ]
36
+ return " ".join(text_parts)
37
+ return str(result)
38
+ except Exception as e:
39
+ raise
40
+
41
+
42
+ def call_mcp_tool(mcp_url: str, tool_name: str, arguments: dict, timeout: int = 30) -> str:
43
+ """Call an MCP tool synchronously.
44
+
45
+ Args:
46
+ mcp_url (str): The MCP SSE URL
47
+ tool_name (str): The name of the MCP tool to call
48
+ arguments (dict): The arguments to pass to the tool
49
+ timeout (int): Timeout in seconds (default: 30)
50
+
51
+ Returns:
52
+ str: The tool result as a string
53
+
54
+ Raises:
55
+ Exception: If the MCP call fails
56
+ """
57
+ return asyncio.run(call_mcp_tool_async(mcp_url, tool_name, arguments, timeout))