|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from mcp import ListPromptsResult, ListResourcesResult, ListToolsResult, types |
| 5 | +from mcp.server.fastmcp import FastMCP |
| 6 | + |
| 7 | +from easymcp.client.sessions.GenericSession import ( |
| 8 | + BaseSessionProtocol, |
| 9 | + PromptsCompatible, |
| 10 | + ResourcesCompatible, |
| 11 | + ToolsCompatible, |
| 12 | +) |
| 13 | +from easymcp.client.sessions.fastmcp.parameters import FastMcpParameters |
| 14 | + |
| 15 | + |
| 16 | +class FastMCPSession( |
| 17 | + BaseSessionProtocol, ToolsCompatible, ResourcesCompatible, PromptsCompatible |
| 18 | +): |
| 19 | + """ASGI style fastmcp session""" |
| 20 | + |
| 21 | + params: FastMcpParameters |
| 22 | + session: FastMCP |
| 23 | + |
| 24 | + def __init__(self, params: FastMcpParameters): |
| 25 | + self.params = params |
| 26 | + |
| 27 | + async def init(self) -> None: |
| 28 | + """Initialize the session""" |
| 29 | + moduleName, identifier = self.params.module.rsplit(":", 1) |
| 30 | + |
| 31 | + originalEnv = os.environ |
| 32 | + originalArgv = sys.argv.copy() |
| 33 | + |
| 34 | + mcpEnv = os.environ.copy() |
| 35 | + mcpEnv.update(self.params.env) |
| 36 | + mcpArgv = [ |
| 37 | + "uvx", |
| 38 | + ] |
| 39 | + mcpArgv.extend(self.params.argv) |
| 40 | + |
| 41 | + os.environ = mcpEnv # type: ignore |
| 42 | + sys.argv = mcpArgv |
| 43 | + |
| 44 | + try: |
| 45 | + module = importlib.import_module(moduleName) |
| 46 | + |
| 47 | + cls = getattr(module, identifier) |
| 48 | + if self.params.factory: |
| 49 | + self.session = cls() |
| 50 | + else: |
| 51 | + self.session = cls |
| 52 | + |
| 53 | + except ModuleNotFoundError as e: |
| 54 | + raise ImportError(f"Module {moduleName} not found") from e |
| 55 | + |
| 56 | + except AttributeError as e: |
| 57 | + raise ImportError( |
| 58 | + f"Module {moduleName} does not contain {identifier}" |
| 59 | + ) from e |
| 60 | + |
| 61 | + except ImportError as e: |
| 62 | + raise ImportError(f"Error importing {moduleName}") from e |
| 63 | + |
| 64 | + finally: |
| 65 | + os.environ = originalEnv |
| 66 | + sys.argv = originalArgv |
| 67 | + |
| 68 | + assert isinstance(self.session, FastMCP), "Session must be a FastMCP instance" |
| 69 | + |
| 70 | + async def list_prompts(self, force: bool = False) -> ListPromptsResult: |
| 71 | + """List all prompts""" |
| 72 | + return ListPromptsResult(prompts=await self.session.list_prompts()) |
| 73 | + |
| 74 | + async def list_resources(self, force: bool = False) -> ListResourcesResult: |
| 75 | + """List all responses""" |
| 76 | + return ListResourcesResult(resources=await self.session.list_resources()) |
| 77 | + |
| 78 | + async def list_tools(self, force: bool = False) -> ListToolsResult: |
| 79 | + """List all tools""" |
| 80 | + return ListToolsResult(tools=await self.session.list_tools()) |
| 81 | + |
| 82 | + async def read_prompt(self, prompt_name: str, args: dict) -> types.GetPromptResult: |
| 83 | + """Read a prompt""" |
| 84 | + return await self.session.get_prompt(prompt_name, args) |
| 85 | + |
| 86 | + async def read_resource(self, resource_name: str) -> types.ReadResourceResult: |
| 87 | + """Read a resource""" |
| 88 | + content = await self.session.read_resource(resource_name) |
| 89 | + data = [ |
| 90 | + { |
| 91 | + "mimeType": c.mime_type, |
| 92 | + "text": c.content, |
| 93 | + "uri": resource_name, |
| 94 | + } |
| 95 | + for c in content |
| 96 | + ] |
| 97 | + result = { |
| 98 | + "contents": data, |
| 99 | + } |
| 100 | + return types.ReadResourceResult.model_validate(result) |
| 101 | + |
| 102 | + async def call_tool(self, tool_name: str, args: dict) -> types.CallToolResult: |
| 103 | + """Call a tool""" |
| 104 | + content = await self.session.call_tool(tool_name, args) |
| 105 | + return types.CallToolResult(content=list(content)) |
0 commit comments