|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from collections.abc import Callable |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import Any, Literal |
| 7 | + |
| 8 | +from pydantic import ConfigDict, with_config |
| 9 | +from temporalio import activity, workflow |
| 10 | +from temporalio.workflow import ActivityConfig |
| 11 | +from typing_extensions import Self |
| 12 | + |
| 13 | +from pydantic_ai import ToolsetTool |
| 14 | +from pydantic_ai.exceptions import UserError |
| 15 | +from pydantic_ai.tools import AgentDepsT, RunContext, ToolDefinition |
| 16 | +from pydantic_ai.toolsets import AbstractToolset |
| 17 | + |
| 18 | +from ._run_context import TemporalRunContext |
| 19 | +from ._toolset import ( |
| 20 | + CallToolParams, |
| 21 | + CallToolResult, |
| 22 | + TemporalWrapperToolset, |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +@dataclass |
| 27 | +@with_config(ConfigDict(arbitrary_types_allowed=True)) |
| 28 | +class _GetToolsParams: |
| 29 | + serialized_run_context: Any |
| 30 | + |
| 31 | + |
| 32 | +class TemporalMCPToolset(TemporalWrapperToolset[AgentDepsT], ABC): |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + toolset: AbstractToolset[AgentDepsT], |
| 36 | + *, |
| 37 | + activity_name_prefix: str, |
| 38 | + activity_config: ActivityConfig, |
| 39 | + tool_activity_config: dict[str, ActivityConfig | Literal[False]], |
| 40 | + deps_type: type[AgentDepsT], |
| 41 | + run_context_type: type[TemporalRunContext[AgentDepsT]] = TemporalRunContext[AgentDepsT], |
| 42 | + ): |
| 43 | + super().__init__(toolset) |
| 44 | + self.activity_config = activity_config |
| 45 | + |
| 46 | + self.tool_activity_config: dict[str, ActivityConfig] = {} |
| 47 | + for tool_name, tool_config in tool_activity_config.items(): |
| 48 | + if tool_config is False: |
| 49 | + raise UserError( |
| 50 | + f'Temporal activity config for MCP tool {tool_name!r} has been explicitly set to `False` (activity disabled), ' |
| 51 | + 'but MCP tools require the use of IO and so cannot be run outside of an activity.' |
| 52 | + ) |
| 53 | + self.tool_activity_config[tool_name] = tool_config |
| 54 | + |
| 55 | + self.run_context_type = run_context_type |
| 56 | + |
| 57 | + async def get_tools_activity(params: _GetToolsParams, deps: AgentDepsT) -> dict[str, ToolDefinition]: |
| 58 | + run_context = self.run_context_type.deserialize_run_context(params.serialized_run_context, deps=deps) |
| 59 | + tools = await self.wrapped.get_tools(run_context) |
| 60 | + # ToolsetTool is not serializable as it holds a SchemaValidator (which is also the same for every MCP tool so unnecessary to pass along the wire every time), |
| 61 | + # so we just return the ToolDefinitions and wrap them in ToolsetTool outside of the activity. |
| 62 | + return {name: tool.tool_def for name, tool in tools.items()} |
| 63 | + |
| 64 | + # Set type hint explicitly so that Temporal can take care of serialization and deserialization |
| 65 | + get_tools_activity.__annotations__['deps'] = deps_type |
| 66 | + |
| 67 | + self.get_tools_activity = activity.defn(name=f'{activity_name_prefix}__mcp_server__{self.id}__get_tools')( |
| 68 | + get_tools_activity |
| 69 | + ) |
| 70 | + |
| 71 | + async def call_tool_activity(params: CallToolParams, deps: AgentDepsT) -> CallToolResult: |
| 72 | + run_context = self.run_context_type.deserialize_run_context(params.serialized_run_context, deps=deps) |
| 73 | + assert isinstance(params.tool_def, ToolDefinition) |
| 74 | + return await self._wrap_call_tool_result( |
| 75 | + self.wrapped.call_tool( |
| 76 | + params.name, |
| 77 | + params.tool_args, |
| 78 | + run_context, |
| 79 | + self.tool_for_tool_def(params.tool_def), |
| 80 | + ) |
| 81 | + ) |
| 82 | + |
| 83 | + # Set type hint explicitly so that Temporal can take care of serialization and deserialization |
| 84 | + call_tool_activity.__annotations__['deps'] = deps_type |
| 85 | + |
| 86 | + self.call_tool_activity = activity.defn(name=f'{activity_name_prefix}__mcp_server__{self.id}__call_tool')( |
| 87 | + call_tool_activity |
| 88 | + ) |
| 89 | + |
| 90 | + @abstractmethod |
| 91 | + def tool_for_tool_def(self, tool_def: ToolDefinition) -> ToolsetTool[AgentDepsT]: |
| 92 | + raise NotImplementedError |
| 93 | + |
| 94 | + @property |
| 95 | + def temporal_activities(self) -> list[Callable[..., Any]]: |
| 96 | + return [self.get_tools_activity, self.call_tool_activity] |
| 97 | + |
| 98 | + async def __aenter__(self) -> Self: |
| 99 | + # The wrapped MCPServer enters itself around listing and calling tools |
| 100 | + # so we don't need to enter it here (nor could we because we're not inside a Temporal activity). |
| 101 | + return self |
| 102 | + |
| 103 | + async def __aexit__(self, *args: Any) -> bool | None: |
| 104 | + return None |
| 105 | + |
| 106 | + async def get_tools(self, ctx: RunContext[AgentDepsT]) -> dict[str, ToolsetTool[AgentDepsT]]: |
| 107 | + if not workflow.in_workflow(): |
| 108 | + return await super().get_tools(ctx) |
| 109 | + |
| 110 | + serialized_run_context = self.run_context_type.serialize_run_context(ctx) |
| 111 | + tool_defs = await workflow.execute_activity( # pyright: ignore[reportUnknownMemberType] |
| 112 | + activity=self.get_tools_activity, |
| 113 | + args=[ |
| 114 | + _GetToolsParams(serialized_run_context=serialized_run_context), |
| 115 | + ctx.deps, |
| 116 | + ], |
| 117 | + **self.activity_config, |
| 118 | + ) |
| 119 | + return {name: self.tool_for_tool_def(tool_def) for name, tool_def in tool_defs.items()} |
| 120 | + |
| 121 | + async def call_tool( |
| 122 | + self, |
| 123 | + name: str, |
| 124 | + tool_args: dict[str, Any], |
| 125 | + ctx: RunContext[AgentDepsT], |
| 126 | + tool: ToolsetTool[AgentDepsT], |
| 127 | + ) -> CallToolResult: |
| 128 | + if not workflow.in_workflow(): |
| 129 | + return await super().call_tool(name, tool_args, ctx, tool) |
| 130 | + |
| 131 | + tool_activity_config = self.activity_config | self.tool_activity_config.get(name, {}) |
| 132 | + serialized_run_context = self.run_context_type.serialize_run_context(ctx) |
| 133 | + return self._unwrap_call_tool_result( |
| 134 | + await workflow.execute_activity( # pyright: ignore[reportUnknownMemberType] |
| 135 | + activity=self.call_tool_activity, |
| 136 | + args=[ |
| 137 | + CallToolParams( |
| 138 | + name=name, |
| 139 | + tool_args=tool_args, |
| 140 | + serialized_run_context=serialized_run_context, |
| 141 | + tool_def=tool.tool_def, |
| 142 | + ), |
| 143 | + ctx.deps, |
| 144 | + ], |
| 145 | + **tool_activity_config, |
| 146 | + ) |
| 147 | + ) |
0 commit comments