temporalio-microsoft-agent-framework 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,339 @@
1
+ """MCP tools for an agent, listed and called through ``temporalio-mcp`` Activities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from collections.abc import Callable, Collection
8
+ from datetime import timedelta
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from agent_framework import (
12
+ AgentSession,
13
+ Content,
14
+ ContextProvider,
15
+ FunctionTool,
16
+ SessionContext,
17
+ )
18
+ from agent_framework.exceptions import ToolExecutionException
19
+
20
+ from temporalio.common import Priority, RetryPolicy
21
+ from temporalio.microsoft_agent_framework.workflow import (
22
+ ApprovalMode,
23
+ MicrosoftAgentFrameworkWorkflowError,
24
+ _propagate_workflow_cancellation,
25
+ )
26
+ from temporalio.workflow import (
27
+ ActivityCancellationType,
28
+ ActivityConfig,
29
+ VersioningIntent,
30
+ )
31
+
32
+ if TYPE_CHECKING:
33
+ from mcp.types import CallToolResult, Tool
34
+
35
+ from temporalio.mcp import TemporalMCPClient
36
+
37
+
38
+ class _Unset:
39
+ """The type of ``_UNSET``: an option the caller did not give."""
40
+
41
+
42
+ _UNSET = _Unset()
43
+
44
+
45
+ class TemporalMCPToolProvider(ContextProvider):
46
+ """Gives an agent the tools of an MCP server registered on the worker.
47
+
48
+ Pass it as ``Agent(context_providers=[TemporalMCPToolProvider("github")])``.
49
+ ``server`` names an ``mcp.Client`` factory registered with
50
+ ``MicrosoftAgentFrameworkPlugin(mcp_clients=...)``; the factory, transport and
51
+ credentials stay on the worker. Before each run the provider lists the
52
+ server's tools with the ``temporalio.mcp.{server}.list-tools`` Activity and
53
+ contributes one ``FunctionTool`` per tool, with the server's full input
54
+ schema, whose call runs the ``temporalio.mcp.{server}.call-tool`` Activity.
55
+ Agent Framework's own loop decides when to call them, so middleware and
56
+ approvals apply as they do to any tool. A workflow cancelled during a call
57
+ stops: the cancelled Activity reaches the tool as ``asyncio.CancelledError``,
58
+ as with ``activity_as_tool``.
59
+
60
+ ``cache_tools=False`` (the default) lists on every run, so a server
61
+ restarted with different tools is picked up; ``True`` lists once per
62
+ provider instance. ``tool_name_prefix``, ``allowed_tools``,
63
+ ``approval_mode`` and ``parse_tool_results`` work as on the framework's
64
+ ``MCPTool``. Tool names are normalized the same way: a character outside
65
+ ``A-Za-z0-9_.-`` becomes ``-`` and the separators between the prefix and
66
+ the name are trimmed, so ``files/read`` reaches the model as ``files-read``
67
+ and prefix ``gh_`` gives ``gh_files-read``. ``allowed_tools`` matches the
68
+ server's own names, ``approval_mode`` is one mode for every tool of the
69
+ server (the per-tool mapping ``MCPTool`` also takes is rejected), and
70
+ ``parse_tool_results`` replaces the default mapping of a ``CallToolResult``
71
+ to content. Server prompts are not loaded, a result's ``_meta`` is not
72
+ carried, and there is no ``tool_result_content`` choice.
73
+
74
+ The activity options apply to every MCP Activity of this provider;
75
+ ``summary`` defaults to the server name. Without ``start_to_close_timeout``
76
+ or ``schedule_to_close_timeout`` the ``temporalio-mcp`` default of one
77
+ minute applies. ``heartbeat_timeout`` left unset means ``temporalio-mcp``'s
78
+ default of 10 seconds: the MCP Activities heartbeat at half the heartbeat
79
+ timeout while they run, which is how a cancel reaches a request already
80
+ running on a worker and how a lost worker is noticed before the
81
+ start-to-close timeout. Pass a ``timedelta`` to change it, or ``None`` to
82
+ turn heartbeats off.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ server: str,
88
+ *,
89
+ cache_tools: bool = False,
90
+ tool_name_prefix: str | None = None,
91
+ allowed_tools: Collection[str] | None = None,
92
+ approval_mode: ApprovalMode | None = None,
93
+ parse_tool_results: Callable[[CallToolResult], str | list[Content]]
94
+ | None = None,
95
+ task_queue: str | None = None,
96
+ schedule_to_close_timeout: timedelta | None = None,
97
+ schedule_to_start_timeout: timedelta | None = None,
98
+ start_to_close_timeout: timedelta | None = None,
99
+ heartbeat_timeout: timedelta | None | _Unset = _UNSET,
100
+ retry_policy: RetryPolicy | None = None,
101
+ cancellation_type: ActivityCancellationType = ActivityCancellationType.TRY_CANCEL,
102
+ versioning_intent: VersioningIntent | None = None,
103
+ summary: str | None = None,
104
+ priority: Priority = Priority.default,
105
+ ) -> None:
106
+ """Configure the server name, tool naming and filtering, and activity options.
107
+
108
+ Raises:
109
+ RuntimeError: If the ``mcp`` extra is not installed.
110
+ MicrosoftAgentFrameworkWorkflowError: If ``approval_mode`` is not
111
+ ``"always_require"``, ``"never_require"`` or ``None``.
112
+ """
113
+ try:
114
+ from temporalio.mcp import TemporalMCPClient
115
+ except ImportError as err:
116
+ raise RuntimeError(
117
+ "TemporalMCPToolProvider requires the 'mcp' extra and MCP Python SDK v2; "
118
+ "install temporalio-microsoft-agent-framework[mcp]"
119
+ ) from err
120
+ # Checked through Any: the annotation is a Literal, but MCPTool also
121
+ # takes a per-tool mapping here, which FunctionTool would keep as is
122
+ # with no tool asking for approval, so a dict is refused at runtime.
123
+ given_mode: Any = approval_mode
124
+ if given_mode is not None and given_mode not in (
125
+ "always_require",
126
+ "never_require",
127
+ ):
128
+ raise MicrosoftAgentFrameworkWorkflowError(
129
+ f"TemporalMCPToolProvider({server!r}) got approval_mode="
130
+ f"{approval_mode!r}; it takes 'always_require' or 'never_require' "
131
+ "for every tool of the server. For per-tool approval, split the "
132
+ "tools over two providers with different tool_name_prefix and "
133
+ "allowed_tools."
134
+ )
135
+ # Two providers of one server need different prefixes anyway, or their
136
+ # tool names collide; the prefix keeps their provider state apart too.
137
+ source_id = f"temporal_mcp:{server}"
138
+ if tool_name_prefix:
139
+ source_id += f":{tool_name_prefix}"
140
+ super().__init__(source_id)
141
+ self._server = server
142
+ self._cache_tools = cache_tools
143
+ self._prefix = tool_name_prefix
144
+ self._allowed_tools = set(allowed_tools) if allowed_tools is not None else None
145
+ self._approval_mode: ApprovalMode | None = approval_mode
146
+ self._parse_tool_results = parse_tool_results
147
+ self._tools: list[FunctionTool] | None = None
148
+ activity_config = ActivityConfig(
149
+ task_queue=task_queue,
150
+ schedule_to_close_timeout=schedule_to_close_timeout,
151
+ schedule_to_start_timeout=schedule_to_start_timeout,
152
+ start_to_close_timeout=start_to_close_timeout,
153
+ retry_policy=retry_policy,
154
+ cancellation_type=cancellation_type,
155
+ versioning_intent=versioning_intent,
156
+ summary=summary if summary is not None else server,
157
+ priority=priority,
158
+ )
159
+ if not isinstance(heartbeat_timeout, _Unset):
160
+ # temporalio-mcp applies its 10-second default when the key is
161
+ # absent and keeps an explicit None, which turns heartbeats off, so
162
+ # the key is set only when the caller chose a value.
163
+ activity_config["heartbeat_timeout"] = heartbeat_timeout
164
+ self._client: TemporalMCPClient = TemporalMCPClient(
165
+ server,
166
+ activity_config=activity_config,
167
+ # This provider decides when to list; the durable client never caches.
168
+ cache_tools_list=False,
169
+ )
170
+
171
+ @property
172
+ def server(self) -> str:
173
+ """The MCP server name registered on the worker."""
174
+ return self._server
175
+
176
+ async def before_run(
177
+ self,
178
+ *,
179
+ agent: Any,
180
+ session: AgentSession,
181
+ context: SessionContext,
182
+ state: dict[str, Any],
183
+ ) -> None:
184
+ """List the server's tools and add them to this run.
185
+
186
+ Tools passed to ``agent.run(tools=...)`` are merged after context
187
+ providers run, so a collision with one of those raises the framework's
188
+ own ``ValueError`` instead and fails the workflow task.
189
+
190
+ Raises:
191
+ MicrosoftAgentFrameworkWorkflowError: If a listed tool has the name of a
192
+ tool the agent already has, from its own ``tools`` or from
193
+ another provider, or the server lists one name twice.
194
+ """
195
+ tools = await self._load_tools()
196
+ self._check_names(agent, context, tools)
197
+ context.extend_tools(self.source_id, tools)
198
+
199
+ async def _load_tools(self) -> list[FunctionTool]:
200
+ if self._cache_tools and self._tools is not None:
201
+ return self._tools
202
+ listed = await self._client.list_tools()
203
+ tools = [
204
+ self._function_tool(tool)
205
+ for tool in listed.tools
206
+ if self._allowed_tools is None or tool.name in self._allowed_tools
207
+ ]
208
+ if self._cache_tools:
209
+ self._tools = tools
210
+ return tools
211
+
212
+ def _function_tool(self, tool: Tool) -> FunctionTool:
213
+ server_tool_name = tool.name
214
+ name = _exposed_name(_normalize_name(server_tool_name), self._prefix)
215
+
216
+ async def call(**arguments: Any) -> str | list[Content]:
217
+ with _propagate_workflow_cancellation():
218
+ result = await self._client.call_tool(server_tool_name, arguments)
219
+ return self._parse(result)
220
+
221
+ return FunctionTool(
222
+ name=name,
223
+ description=tool.description or "",
224
+ func=call,
225
+ input_model=dict(tool.input_schema),
226
+ approval_mode=self._approval_mode,
227
+ )
228
+
229
+ def _parse(self, result: CallToolResult) -> str | list[Content]:
230
+ parsed = (
231
+ self._parse_tool_results(result)
232
+ if self._parse_tool_results is not None
233
+ else _contents(result)
234
+ )
235
+ if result.is_error:
236
+ # The framework's MCPTool raises the same way, so the loop records
237
+ # a tool error for the model instead of a successful result.
238
+ text = (
239
+ "\n".join(c.text for c in parsed if c.type == "text" and c.text)
240
+ if isinstance(parsed, list)
241
+ else str(parsed)
242
+ )
243
+ raise ToolExecutionException(
244
+ f"MCP tool returned an error: {text or parsed!s}"
245
+ )
246
+ return parsed
247
+
248
+ def _check_names(
249
+ self, agent: Any, context: SessionContext, tools: list[FunctionTool]
250
+ ) -> None:
251
+ taken: dict[str, str] = {}
252
+ default_options = getattr(agent, "default_options", None)
253
+ agent_tools = (
254
+ default_options.get("tools") if isinstance(default_options, dict) else None
255
+ )
256
+ for name in _tool_names(agent_tools or []):
257
+ taken[name] = "the agent's own tools"
258
+ for name in _tool_names(context.tools):
259
+ taken.setdefault(name, "another context provider")
260
+ for tool in tools:
261
+ source = taken.get(tool.name)
262
+ if source is not None:
263
+ raise MicrosoftAgentFrameworkWorkflowError(
264
+ f"MCP server {self._server!r} lists a tool named {tool.name!r}, which the "
265
+ f"agent already has from {source}. Set tool_name_prefix or allowed_tools "
266
+ "on TemporalMCPToolProvider."
267
+ )
268
+ taken[tool.name] = f"MCP server {self._server!r}"
269
+
270
+
271
+ _NAME_OUTSIDE_SAFE_SET = re.compile(r"[^A-Za-z0-9_.-]")
272
+ _NAME_SEPARATORS = "_.-"
273
+
274
+
275
+ def _normalize_name(name: str) -> str:
276
+ """Replace the characters providers reject in a tool name, as ``MCPTool`` does."""
277
+ return _NAME_OUTSIDE_SAFE_SET.sub("-", name)
278
+
279
+
280
+ def _exposed_name(normalized: str, prefix: str | None) -> str:
281
+ """Join the prefix and the normalized name the way ``MCPTool`` does."""
282
+ if not prefix:
283
+ return normalized
284
+ normalized_prefix = _normalize_name(prefix).rstrip(_NAME_SEPARATORS)
285
+ if not normalized_prefix:
286
+ return normalized
287
+ trimmed = normalized.lstrip(_NAME_SEPARATORS)
288
+ return f"{normalized_prefix}_{trimmed}" if trimmed else normalized_prefix
289
+
290
+
291
+ def _tool_names(tools: Any) -> list[str]:
292
+ names: list[str] = []
293
+ for tool in tools:
294
+ name = getattr(tool, "name", None)
295
+ if isinstance(name, str):
296
+ names.append(name)
297
+ return names
298
+
299
+
300
+ def _contents(result: CallToolResult) -> list[Content]:
301
+ """Map a ``CallToolResult`` to content the way the framework's ``MCPTool`` does.
302
+
303
+ Structured content wins when the server returns it; otherwise text, image,
304
+ audio, resource links and embedded resources map to their content types.
305
+ """
306
+ from mcp import types
307
+
308
+ if result.structured_content is not None:
309
+ return [Content.from_text(json.dumps(result.structured_content, default=str))]
310
+ contents: list[Content] = []
311
+ for item in result.content:
312
+ if isinstance(item, types.TextContent):
313
+ contents.append(Content.from_text(item.text))
314
+ elif isinstance(item, (types.ImageContent, types.AudioContent)):
315
+ contents.append(
316
+ Content.from_uri(
317
+ uri=f"data:{item.mime_type};base64,{item.data}",
318
+ media_type=item.mime_type,
319
+ )
320
+ )
321
+ elif isinstance(item, types.ResourceLink):
322
+ contents.append(
323
+ Content.from_uri(uri=str(item.uri), media_type=item.mime_type)
324
+ )
325
+ elif isinstance(item, types.EmbeddedResource):
326
+ resource = item.resource
327
+ if isinstance(resource, types.TextResourceContents):
328
+ contents.append(Content.from_text(resource.text))
329
+ else:
330
+ mime = resource.mime_type or "application/octet-stream"
331
+ blob = resource.blob
332
+ if not blob.startswith("data:"):
333
+ blob = f"data:{mime};base64,{blob}"
334
+ contents.append(Content.from_uri(uri=blob, media_type=mime))
335
+ else:
336
+ contents.append(Content.from_text(str(item)))
337
+ if not contents:
338
+ contents.append(Content.from_text("null"))
339
+ return contents
@@ -0,0 +1,294 @@
1
+ """The plugin users add to ``plugins=[...]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.metadata
6
+ import inspect
7
+ import logging
8
+ import warnings
9
+ from collections.abc import Callable, Mapping, Sequence
10
+ from dataclasses import replace
11
+ from datetime import timedelta
12
+ from types import FrameType
13
+ from typing import TYPE_CHECKING, Any, cast
14
+
15
+ import opentelemetry.metrics
16
+ import opentelemetry.trace
17
+ from agent_framework.exceptions import AgentFrameworkException
18
+
19
+ from temporalio.contrib.pydantic import pydantic_data_converter
20
+ from temporalio.converter import DataConverter, DefaultPayloadConverter
21
+ from temporalio.exceptions import ApplicationError
22
+ from temporalio.microsoft_agent_framework._activities import (
23
+ MCP_CLIENT_FACTORY_ERROR_TYPE,
24
+ ChatClientActivities,
25
+ ChatClientFactory,
26
+ )
27
+ from temporalio.microsoft_agent_framework._serde import HostedMCPHeaders
28
+ from temporalio.microsoft_agent_framework._workflow_runtime import (
29
+ install_workflow_runtime,
30
+ )
31
+ from temporalio.microsoft_agent_framework.workflow import (
32
+ MicrosoftAgentFrameworkWorkflowError,
33
+ )
34
+ from temporalio.plugin import SimplePlugin
35
+ from temporalio.worker import ReplayerConfig, WorkerConfig, WorkflowRunner
36
+ from temporalio.worker.workflow_sandbox import SandboxedWorkflowRunner
37
+
38
+ if TYPE_CHECKING:
39
+ from mcp import Client
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ # What agent_framework core imports at module load, so workflow files that
44
+ # import it share one copy with the host instead of re-importing it per run.
45
+ _PASSTHROUGH_MODULES = (
46
+ # The framework itself: the agent, the loop, sessions and middleware.
47
+ "agent_framework",
48
+ # pydantic's compiled validation core; pydantic is already an SDK default.
49
+ "pydantic_core",
50
+ # pydantic's Annotated constraint helpers.
51
+ "annotated_types",
52
+ # The framework's msgspec serialization of sessions and messages.
53
+ "msgspec",
54
+ # pydantic's type introspection helpers.
55
+ "typing_inspection",
56
+ # The framework's telemetry layers import the OpenTelemetry API eagerly.
57
+ "opentelemetry",
58
+ # The framework's settings loader imports python-dotenv eagerly.
59
+ "dotenv",
60
+ # The MCP SDK types that TemporalMCPToolProvider and temporalio-mcp read.
61
+ "mcp",
62
+ "mcp_types",
63
+ )
64
+
65
+
66
+ class MicrosoftAgentFrameworkPlugin(SimplePlugin):
67
+ """Temporal plugin for Microsoft Agent Framework agents.
68
+
69
+ Add it to the ``Client`` (the Worker inherits it, and only there does the
70
+ plugin set the data converter), not to both. ``chat_clients`` maps a
71
+ model name to a worker-side factory that builds the provider's chat
72
+ client, for example ``{"gpt-4o": lambda: OpenAIChatClient(model="gpt-4o",
73
+ async_client=AsyncOpenAI(max_retries=0))}``; a workflow selects it with
74
+ ``TemporalChatClient("gpt-4o")``. Factories run on first use and are
75
+ cached for the worker's lifetime, so credentials stay on the worker. The
76
+ plugin registers the ``microsoft_agent_framework.invoke_model`` and
77
+ ``microsoft_agent_framework.invoke_model_streaming`` Activities.
78
+
79
+ ``mcp_clients`` maps a server name to a factory returning an ``mcp.Client``
80
+ (MCP Python SDK v2; needs the ``mcp`` extra) and registers the
81
+ ``temporalio.mcp.{server}.*`` Activities of a ``temporalio.mcp.MCPPlugin``
82
+ for each entry; a workflow uses ``TemporalMCPToolProvider("server")``. Do
83
+ not register the same server name through ``MCPPlugin`` on the same worker.
84
+ ``mcp_connection_idle_timeout`` is how long an idle worker-side MCP
85
+ connection stays open between Activities (default 5 minutes; ``None``
86
+ keeps it until shutdown, zero closes it after each Activity).
87
+
88
+ ``hosted_mcp_headers`` keeps the headers of hosted MCP tools (the
89
+ provider's ``get_mcp_tool(...)`` mappings) on the worker: a mapping from
90
+ the server's label or URL to its headers, or to a callable returning them,
91
+ which the model Activity adds to the tool before the provider call. For
92
+ an OpenAI connector (a mapping with ``connector_id``) an entry named
93
+ ``authorization`` is applied to the tool's ``authorization`` field, where
94
+ the Responses API takes a connector's OAuth token, and the rest stay
95
+ headers. A hosted MCP tool that carries ``headers`` or ``authorization`` in workflow
96
+ code fails the run with ``MicrosoftAgentFrameworkWorkflowError``, because
97
+ the tool mapping is recorded in workflow history.
98
+
99
+ The plugin also sets the Pydantic data converter unless the client has its
100
+ own payload converter, passes the framework's modules through the workflow
101
+ sandbox, installs workflow-aware clocks and id generators and the inline
102
+ run of synchronous tools for the framework's agent code, and registers ``MicrosoftAgentFrameworkWorkflowError`` and
103
+ the framework's ``AgentFrameworkException`` as workflow failure types.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ chat_clients: Mapping[str, ChatClientFactory] | None = None,
110
+ mcp_clients: Mapping[str, Callable[[], Client]] | None = None,
111
+ mcp_connection_idle_timeout: timedelta | None = timedelta(minutes=5),
112
+ hosted_mcp_headers: Mapping[str, HostedMCPHeaders] | None = None,
113
+ ) -> None:
114
+ """Build the plugin from the chat client and MCP client factories.
115
+
116
+ Raises:
117
+ RuntimeError: If ``mcp_clients`` is given without the ``mcp`` extra.
118
+ """
119
+ model_activities = ChatClientActivities(
120
+ chat_clients or {}, hosted_mcp_headers=hosted_mcp_headers
121
+ )
122
+ activities: list[Callable[..., Any]] = [
123
+ model_activities.invoke_model,
124
+ model_activities.invoke_model_streaming,
125
+ ]
126
+ mcp_plugin = None
127
+ if mcp_clients:
128
+ try:
129
+ from temporalio.mcp import MCPPlugin
130
+ except ImportError as err:
131
+ raise RuntimeError(
132
+ "mcp_clients requires the 'mcp' extra and MCP Python SDK v2; "
133
+ "install temporalio-microsoft-agent-framework[mcp]"
134
+ ) from err
135
+ mcp_plugin = MCPPlugin(
136
+ {
137
+ server: _mcp_client_factory(server, factory)
138
+ for server, factory in mcp_clients.items()
139
+ },
140
+ connection_idle_timeout=mcp_connection_idle_timeout,
141
+ )
142
+ activities.extend(cast(Sequence[Callable[..., Any]], mcp_plugin.activities))
143
+ super().__init__(
144
+ "microsoft.AgentFrameworkPlugin",
145
+ activities=activities,
146
+ data_converter=_data_converter,
147
+ workflow_runner=_workflow_runner,
148
+ # Every framework exception raised in workflow code is deterministic
149
+ # (model and MCP errors arrive as Activity failures), so retrying the
150
+ # workflow task cannot help; fail the workflow instead.
151
+ workflow_failure_exception_types=[
152
+ MicrosoftAgentFrameworkWorkflowError,
153
+ AgentFrameworkException,
154
+ ],
155
+ run_context=mcp_plugin.run_context if mcp_plugin else None,
156
+ )
157
+
158
+ def version(self) -> str:
159
+ """Return this package's version, which worker heartbeats report."""
160
+ try:
161
+ return importlib.metadata.version("temporalio-microsoft-agent-framework")
162
+ except importlib.metadata.PackageNotFoundError:
163
+ return ""
164
+
165
+ def configure_worker(self, config: WorkerConfig) -> WorkerConfig:
166
+ """See the base class; also warns when the global OpenTelemetry providers are not replay-safe."""
167
+ _warn_if_global_otel_providers_not_replay_safe()
168
+ return super().configure_worker(config)
169
+
170
+ def configure_replayer(self, config: ReplayerConfig) -> ReplayerConfig:
171
+ """See the base class; also warns when the global OpenTelemetry providers are not replay-safe."""
172
+ _warn_if_global_otel_providers_not_replay_safe()
173
+ return super().configure_replayer(config)
174
+
175
+
176
+ def _mcp_client_factory(
177
+ server: str, factory: Callable[[], Client]
178
+ ) -> Callable[[], Client]:
179
+ # MCPPlugin passes a factory argument to any factory with a positional
180
+ # parameter, even a defaulted one, so the wrapper takes none.
181
+ import mcp
182
+
183
+ def create() -> Client:
184
+ # Same policy as the chat client factories: a factory that raises may
185
+ # recover (a secret store, a token endpoint, one worker of many), so
186
+ # the attempt fails retryably and the retry policy bounds the wait; a
187
+ # factory that returns the wrong thing is wrong on every attempt.
188
+ try:
189
+ client = factory()
190
+ except Exception as err:
191
+ logger.error(
192
+ "MCP client factory for %r raised %s: %s",
193
+ server,
194
+ type(err).__name__,
195
+ err,
196
+ )
197
+ raise ApplicationError(
198
+ f"The MCP client factory for {server!r} raised "
199
+ f"{type(err).__name__}: {err}",
200
+ type=MCP_CLIENT_FACTORY_ERROR_TYPE,
201
+ non_retryable=False,
202
+ ) from err
203
+ if not isinstance(client, mcp.Client):
204
+ kind = type(client)
205
+ raise ApplicationError(
206
+ f"The MCP client factory for {server!r} returned "
207
+ f"{kind.__module__}.{kind.__qualname__}, not mcp.Client; "
208
+ "mcp_clients factories must return an mcp.Client",
209
+ type=MCP_CLIENT_FACTORY_ERROR_TYPE,
210
+ non_retryable=True,
211
+ )
212
+ return client
213
+
214
+ return create
215
+
216
+
217
+ def _workflow_runner(runner: WorkflowRunner | None) -> WorkflowRunner:
218
+ if runner is None:
219
+ raise ValueError("No WorkflowRunner provided to MicrosoftAgentFrameworkPlugin.")
220
+ # Workers and Replayers both pass through here, so both get the
221
+ # workflow-aware clocks and ids, and both fail early on an unsupported
222
+ # framework version.
223
+ install_workflow_runtime()
224
+ if isinstance(runner, SandboxedWorkflowRunner):
225
+ return replace(
226
+ runner,
227
+ restrictions=runner.restrictions.with_passthrough_modules(
228
+ *_PASSTHROUGH_MODULES
229
+ ),
230
+ )
231
+ return runner
232
+
233
+
234
+ def _data_converter(converter: DataConverter | None) -> DataConverter:
235
+ if converter is None:
236
+ return pydantic_data_converter
237
+ if converter.payload_converter_class is DefaultPayloadConverter:
238
+ # Keep the caller's codec and failure converter; only the payload
239
+ # converter changes, so Pydantic models cross the boundary.
240
+ return replace(
241
+ converter,
242
+ payload_converter_class=pydantic_data_converter.payload_converter_class,
243
+ )
244
+ return converter
245
+
246
+
247
+ def _stacklevel_outside_temporalio() -> int:
248
+ # Attribute the warning to the nearest frame outside temporalio, such as
249
+ # the user's Worker(...) or Replayer(...) call.
250
+ level = 1
251
+ own_frame: FrameType | None = inspect.currentframe()
252
+ frame = own_frame.f_back if own_frame is not None else None
253
+ while frame is not None:
254
+ module = frame.f_globals.get("__name__", "")
255
+ if module != "temporalio" and not module.startswith("temporalio."):
256
+ return level
257
+ frame = frame.f_back
258
+ level += 1
259
+ return 1
260
+
261
+
262
+ def _warn_if_global_otel_providers_not_replay_safe() -> None:
263
+ # Agent Framework records tool metrics and agent spans through the
264
+ # process-global OpenTelemetry providers from workflow code, so a provider
265
+ # that is not replay-safe re-emits them on every replay. Only an
266
+ # OpenTelemetry SDK provider used directly as the global is a sure case;
267
+ # unset, no-op and unknown providers stay silent.
268
+ try:
269
+ from opentelemetry.sdk.metrics import MeterProvider as SdkMeterProvider
270
+ from opentelemetry.sdk.trace import TracerProvider as SdkTracerProvider
271
+ except ImportError:
272
+ return
273
+ stacklevel = _stacklevel_outside_temporalio()
274
+ if isinstance(opentelemetry.metrics.get_meter_provider(), SdkMeterProvider):
275
+ warnings.warn(
276
+ "The global OpenTelemetry MeterProvider is not replay-safe: Agent Framework "
277
+ "records tool metrics from workflow code, so every workflow replay will "
278
+ "re-record them. Wrap your provider in "
279
+ "temporalio.contrib.opentelemetry.ReplaySafeMeterProvider and make it the "
280
+ "first and only global provider set: "
281
+ "opentelemetry.metrics.set_meter_provider(ReplaySafeMeterProvider(provider))",
282
+ UserWarning,
283
+ stacklevel=stacklevel,
284
+ )
285
+ if isinstance(opentelemetry.trace.get_tracer_provider(), SdkTracerProvider):
286
+ warnings.warn(
287
+ "The global OpenTelemetry TracerProvider is not replay-safe: Agent Framework "
288
+ "creates agent spans from workflow code, so every workflow replay will "
289
+ "re-emit them. Install a replay-safe provider: "
290
+ "opentelemetry.trace.set_tracer_provider("
291
+ "temporalio.contrib.opentelemetry.create_tracer_provider())",
292
+ UserWarning,
293
+ stacklevel=stacklevel,
294
+ )