client.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import asyncio
  2. from typing import Optional
  3. from contextlib import AsyncExitStack
  4. from mcp import ClientSession
  5. from mcp.client.auth import OAuthClientProvider, TokenStorage
  6. from mcp.client.streamable_http import streamablehttp_client
  7. from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
  8. class MCPClient:
  9. def __init__(self):
  10. self.session: Optional[ClientSession] = None
  11. self.exit_stack = AsyncExitStack()
  12. async def connect(
  13. self, url: str, headers: Optional[dict] = None, auth: Optional[any] = None
  14. ):
  15. self._streams_context = streamablehttp_client(url, headers=headers, auth=auth)
  16. read_stream, write_stream, _ = (
  17. await self._streams_context.__aenter__()
  18. ) # pylint: disable=E1101
  19. self._session_context = ClientSession(
  20. read_stream, write_stream
  21. ) # pylint: disable=W0201
  22. self.session: ClientSession = (
  23. await self._session_context.__aenter__()
  24. ) # pylint: disable=C2801
  25. await self.session.initialize()
  26. async def list_tool_specs(self) -> Optional[dict]:
  27. if not self.session:
  28. raise RuntimeError("MCP client is not connected.")
  29. result = await self.session.list_tools()
  30. tools = result.tools
  31. tool_specs = []
  32. for tool in tools:
  33. name = tool.name
  34. description = tool.description
  35. inputSchema = tool.inputSchema
  36. # TODO: handle outputSchema if needed
  37. outputSchema = getattr(tool, "outputSchema", None)
  38. tool_specs.append(
  39. {"name": name, "description": description, "parameters": inputSchema}
  40. )
  41. return tool_specs
  42. async def call_tool(
  43. self, function_name: str, function_args: dict
  44. ) -> Optional[dict]:
  45. if not self.session:
  46. raise RuntimeError("MCP client is not connected.")
  47. result = await self.session.call_tool(function_name, function_args)
  48. if not result:
  49. raise Exception("No result returned from MCP tool call.")
  50. result_dict = result.model_dump()
  51. result_content = result_dict.get("content", {})
  52. if result.isError:
  53. raise Exception(result_content)
  54. else:
  55. return result_content
  56. async def list_resources(self, cursor: Optional[str] = None) -> Optional[dict]:
  57. if not self.session:
  58. raise RuntimeError("MCP client is not connected.")
  59. result = await self.session.list_resources(cursor=cursor)
  60. if not result:
  61. raise Exception("No result returned from MCP list_resources call.")
  62. result_dict = result.model_dump()
  63. resources = result_dict.get("resources", [])
  64. return resources
  65. async def read_resource(self, uri: str) -> Optional[dict]:
  66. if not self.session:
  67. raise RuntimeError("MCP client is not connected.")
  68. result = await self.session.read_resource(uri)
  69. if not result:
  70. raise Exception("No result returned from MCP read_resource call.")
  71. result_dict = result.model_dump()
  72. return result_dict
  73. async def disconnect(self):
  74. # Clean up and close the session
  75. if self.session:
  76. await self._session_context.__aexit__(
  77. None, None, None
  78. ) # pylint: disable=E1101
  79. if self._streams_context:
  80. await self._streams_context.__aexit__(
  81. None, None, None
  82. ) # pylint: disable=E1101
  83. self.session = None
  84. async def __aenter__(self):
  85. await self.exit_stack.__aenter__()
  86. return self
  87. async def __aexit__(self, exc_type, exc_value, traceback):
  88. await self.exit_stack.__aexit__(exc_type, exc_value, traceback)
  89. await self.disconnect()