Skip to content

Commit 27b34f1

Browse files
committed
Prevent MCPToolset GC during toolset add
1 parent 0f0cbe7 commit 27b34f1

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

integrations/mcp/src/haystack_integrations/tools/mcp/mcp_toolset.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,14 @@ def __init__(
145145
)
146146

147147
# This is a factory that creates the invocation function for the Tool
148-
def create_invoke_tool(mcp_client, tool_name, tool_timeout):
148+
def create_invoke_tool(owner_toolset, mcp_client, tool_name, tool_timeout):
149+
"""Return a closure that keeps a strong reference to *owner_toolset* alive."""
150+
149151
def invoke_tool(**kwargs) -> Any:
150-
"""Invoke a tool using the existing client and AsyncExecutor."""
151-
result = AsyncExecutor.get_instance().run(
152+
_ = owner_toolset # strong reference so GC can't collect the toolset too early
153+
return AsyncExecutor.get_instance().run(
152154
mcp_client.call_tool(tool_name, kwargs), timeout=tool_timeout
153155
)
154-
return result
155156

156157
return invoke_tool
157158

@@ -170,7 +171,7 @@ def invoke_tool(**kwargs) -> Any:
170171
name=tool_info.name,
171172
description=tool_info.description,
172173
parameters=tool_info.inputSchema,
173-
function=create_invoke_tool(client, tool_info.name, self.invocation_timeout),
174+
function=create_invoke_tool(self, client, tool_info.name, self.invocation_timeout),
174175
)
175176
haystack_tools.append(tool)
176177

0 commit comments

Comments
 (0)