|
| 1 | +# Copyright (C) 2024 Andrew Wason |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import typing as t |
| 5 | +from collections.abc import Callable |
| 6 | + |
| 7 | +import pydantic |
| 8 | +import pydantic_core |
| 9 | +from langchain_core.tools.base import BaseTool, BaseToolkit, InjectedToolArg, ToolException |
| 10 | +from mcp import ClientSession |
| 11 | + |
| 12 | + |
| 13 | +class MCPToolkit(BaseToolkit): |
| 14 | + """ |
| 15 | + MCP server toolkit |
| 16 | + """ |
| 17 | + |
| 18 | + session: ClientSession |
| 19 | + """The MCP session used to obtain the tools""" |
| 20 | + |
| 21 | + _initialized: bool = False |
| 22 | + |
| 23 | + model_config = pydantic.ConfigDict(arbitrary_types_allowed=True) |
| 24 | + |
| 25 | + async def get_tools(self) -> list[BaseTool]: |
| 26 | + if not self._initialized: |
| 27 | + await self.session.initialize() |
| 28 | + self._initialized = True |
| 29 | + |
| 30 | + return [ |
| 31 | + MCPTool( |
| 32 | + session=self.session, |
| 33 | + name=tool.name, |
| 34 | + description=tool.description, |
| 35 | + args_schema=create_schema_model(tool.inputSchema), |
| 36 | + ) |
| 37 | + # list_tools returns a PaginatedResult, but I don't see a way to pass the cursor to retrieve more tools |
| 38 | + for tool in (await self.session.list_tools()).tools |
| 39 | + ] |
| 40 | + |
| 41 | + |
| 42 | +def create_schema_model(schema: dict[str, t.Any]) -> type[pydantic.BaseModel]: |
| 43 | + # Create a new model class that returns our JSON schema. |
| 44 | + # LangChain requires a BaseModel class. |
| 45 | + class Schema(pydantic.BaseModel): |
| 46 | + model_config = pydantic.ConfigDict(extra="allow", arbitrary_types_allowed=True) |
| 47 | + |
| 48 | + @classmethod |
| 49 | + def model_json_schema( |
| 50 | + cls, |
| 51 | + by_alias: bool = True, |
| 52 | + ref_template: str = pydantic.json_schema.DEFAULT_REF_TEMPLATE, |
| 53 | + schema_generator: type[pydantic.json_schema.GenerateJsonSchema] = pydantic.json_schema.GenerateJsonSchema, |
| 54 | + mode: pydantic.json_schema.JsonSchemaMode = "validation", |
| 55 | + ) -> dict[str, t.Any]: |
| 56 | + return schema |
| 57 | + |
| 58 | + return Schema |
| 59 | + |
| 60 | + |
| 61 | +class MCPTool(BaseTool): |
| 62 | + """ |
| 63 | + MCP server tool |
| 64 | + """ |
| 65 | + |
| 66 | + session: ClientSession |
| 67 | + |
| 68 | + handle_tool_error: bool | str | Callable[[ToolException], str] | None = True |
| 69 | + |
| 70 | + def _run(self, *args: t.Any, **kwargs: t.Any) -> t.Any: |
| 71 | + raise NotImplementedError("Must invoke tool asynchronously") |
| 72 | + |
| 73 | + async def _arun(self, *args: t.Any, **kwargs: t.Any) -> t.Any: |
| 74 | + result = await self.session.call_tool(self.name, arguments=kwargs) |
| 75 | + content = pydantic_core.to_json(result.content).decode() |
| 76 | + if result.isError: |
| 77 | + raise ToolException(content) |
| 78 | + return content |
| 79 | + |
| 80 | + @property |
| 81 | + def tool_call_schema(self) -> type[pydantic.BaseModel]: |
| 82 | + return self.args_schema |
0 commit comments