mcp-haystack 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,27 @@
1
+ from .mcp_tool import (
2
+ MCPClient,
3
+ MCPConnectionError,
4
+ MCPError,
5
+ MCPInvocationError,
6
+ MCPServerInfo,
7
+ MCPTool,
8
+ MCPToolNotFoundError,
9
+ SSEClient,
10
+ SSEServerInfo,
11
+ StdioClient,
12
+ StdioServerInfo,
13
+ )
14
+
15
+ __all__ = [
16
+ "MCPClient",
17
+ "MCPConnectionError",
18
+ "MCPError",
19
+ "MCPInvocationError",
20
+ "MCPServerInfo",
21
+ "MCPTool",
22
+ "MCPToolNotFoundError",
23
+ "SSEClient",
24
+ "SSEServerInfo",
25
+ "StdioClient",
26
+ "StdioServerInfo",
27
+ ]
@@ -0,0 +1,663 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import asyncio
6
+ from abc import ABC, abstractmethod
7
+ from collections.abc import Coroutine
8
+ from contextlib import AsyncExitStack
9
+ from dataclasses import dataclass, fields
10
+ from typing import Any, cast
11
+
12
+ from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
13
+ from haystack import logging
14
+ from haystack.core.serialization import generate_qualified_class_name, import_class_by_name
15
+ from haystack.tools import Tool
16
+ from haystack.tools.errors import ToolInvocationError
17
+
18
+ from mcp import ClientSession, StdioServerParameters, types
19
+ from mcp.client.sse import sse_client
20
+ from mcp.client.stdio import stdio_client
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class MCPError(Exception):
26
+ """Base class for MCP-related errors."""
27
+
28
+ def __init__(self, message: str) -> None:
29
+ """
30
+ Initialize the MCPError.
31
+
32
+ :param message: Descriptive error message
33
+ """
34
+ super().__init__(message)
35
+ self.message = message
36
+
37
+
38
+ class MCPConnectionError(MCPError):
39
+ """Error connecting to MCP server."""
40
+
41
+ def __init__(self, message: str, server_info: "MCPServerInfo | None" = None, operation: str | None = None) -> None:
42
+ """
43
+ Initialize the MCPConnectionError.
44
+
45
+ :param message: Descriptive error message
46
+ :param server_info: Server connection information that was used
47
+ :param operation: Name of the operation that was being attempted
48
+ """
49
+ super().__init__(message)
50
+ self.server_info = server_info
51
+ self.operation = operation
52
+
53
+
54
+ class MCPToolNotFoundError(MCPError):
55
+ """Error when a tool is not found on the server."""
56
+
57
+ def __init__(self, message: str, tool_name: str, available_tools: list[str] | None = None) -> None:
58
+ """
59
+ Initialize the MCPToolNotFoundError.
60
+
61
+ :param message: Descriptive error message
62
+ :param tool_name: Name of the tool that was requested but not found
63
+ :param available_tools: List of available tool names, if known
64
+ """
65
+ super().__init__(message)
66
+ self.tool_name = tool_name
67
+ self.available_tools = available_tools or []
68
+
69
+
70
+ class MCPResponseTypeError(MCPError):
71
+ """Error when response content type is not supported."""
72
+
73
+ def __init__(self, message: str, response: Any, tool_name: str | None = None) -> None:
74
+ """
75
+ Initialize the MCPResponseTypeError.
76
+
77
+ :param message: Descriptive error message
78
+ :param response: The response that had the wrong type
79
+ :param tool_name: Name of the tool that produced the response
80
+ """
81
+ super().__init__(message)
82
+ self.response = response
83
+ self.tool_name = tool_name
84
+
85
+
86
+ class MCPInvocationError(ToolInvocationError):
87
+ """Error during tool invocation."""
88
+
89
+ def __init__(self, message: str, tool_name: str, tool_args: dict[str, Any] | None = None) -> None:
90
+ """
91
+ Initialize the MCPInvocationError.
92
+
93
+ :param message: Descriptive error message
94
+ :param tool_name: Name of the tool that was being invoked
95
+ :param tool_args: Arguments that were passed to the tool
96
+ """
97
+ super().__init__(message)
98
+ self.tool_name = tool_name
99
+ self.tool_args = tool_args or {}
100
+
101
+
102
+ class MCPClient(ABC):
103
+ """
104
+ Abstract base class for MCP clients.
105
+
106
+ This class defines the common interface and shared functionality for all MCP clients,
107
+ regardless of the transport mechanism used.
108
+ """
109
+
110
+ def __init__(self) -> None:
111
+ self.session: ClientSession | None = None
112
+ self.exit_stack: AsyncExitStack = AsyncExitStack()
113
+ self.stdio: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception] | None = None
114
+ self.write: MemoryObjectSendStream[types.JSONRPCMessage] | None = None
115
+
116
+ @abstractmethod
117
+ async def connect(self) -> list[Tool]:
118
+ """
119
+ Connect to an MCP server.
120
+
121
+ :returns: List of available tools on the server
122
+ :raises MCPConnectionError: If connection to the server fails
123
+ """
124
+ pass
125
+
126
+ async def call_tool(self, tool_name: str, tool_args: dict[str, Any]) -> Any:
127
+ """
128
+ Call a tool on the connected MCP server.
129
+
130
+ :param tool_name: Name of the tool to call
131
+ :param tool_args: Arguments to pass to the tool
132
+ :returns: Result of the tool invocation
133
+ :raises MCPConnectionError: If not connected to an MCP server
134
+ :raises MCPInvocationError: If the tool invocation fails
135
+ :raises MCPResponseTypeError: If response type is not TextContent
136
+ """
137
+ if not self.session:
138
+ message = "Not connected to an MCP server"
139
+ raise MCPConnectionError(message=message, operation="call_tool")
140
+
141
+ try:
142
+ result = await self.session.call_tool(tool_name, tool_args)
143
+ validated_result = self._validate_response(tool_name, result)
144
+ return validated_result
145
+ except MCPError:
146
+ # Re-raise specific MCP errors directly
147
+ raise
148
+ except Exception as e:
149
+ # Wrap other exceptions with context about which tool failed
150
+ message = f"Failed to invoke tool '{tool_name}'"
151
+ raise MCPInvocationError(message, tool_name, tool_args) from e
152
+
153
+ def _validate_response(self, tool_name: str, result: types.CallToolResult) -> types.CallToolResult:
154
+ """
155
+ Validate response from an MCP tool call, accepting only TextContent.
156
+
157
+ :param tool_name: Name of the called tool (for error messages)
158
+ :param result: CallToolResult from MCP tool call
159
+ :returns: The original CallToolResult object
160
+ :raises MCPResponseTypeError: If content type is not TextContent
161
+ :raises MCPInvocationError: If the tool call resulted in an error
162
+ """
163
+
164
+ # Check for error response
165
+ if result.isError:
166
+ if len(result.content) > 0 and isinstance(result.content[0], types.TextContent):
167
+ # Get the error message from the first item
168
+ first_item = result.content[0]
169
+ message = f"Tool '{tool_name}' returned an error: {first_item.text}"
170
+ else:
171
+ message = f"Tool '{tool_name}' returned an error: {result.content!s}"
172
+ raise MCPInvocationError(
173
+ message=message,
174
+ tool_name=tool_name,
175
+ )
176
+
177
+ # Validate content types - only allow TextContent for now
178
+ if result.content:
179
+ for item in result.content:
180
+ if not isinstance(item, types.TextContent):
181
+ # Reject any non-TextContent
182
+ message = (
183
+ f"Unsupported content type in response from tool '{tool_name}'. "
184
+ f"Only TextContent is currently supported."
185
+ )
186
+ raise MCPResponseTypeError(message, result, tool_name)
187
+
188
+ # Return the original result object
189
+ return result
190
+
191
+ async def close(self) -> None:
192
+ """
193
+ Close the connection and clean up resources.
194
+
195
+ This method ensures all resources are properly released, even if errors occur.
196
+ """
197
+ if not self.exit_stack:
198
+ return
199
+
200
+ try:
201
+ await self.exit_stack.aclose()
202
+ except Exception as e:
203
+ logger.warning(f"Error during MCP client cleanup: {e}")
204
+ finally:
205
+ # Ensure all references are cleared even if cleanup fails
206
+ self.session = None
207
+ self.stdio = None
208
+ self.write = None
209
+
210
+ async def _initialize_session_with_transport(
211
+ self,
212
+ transport_tuple: tuple[
213
+ MemoryObjectReceiveStream[types.JSONRPCMessage | Exception], MemoryObjectSendStream[types.JSONRPCMessage]
214
+ ],
215
+ connection_type: str,
216
+ ) -> list[Tool]:
217
+ """
218
+ Common session initialization logic for all transports.
219
+
220
+ :param transport_tuple: Tuple containing (stdio, write) from the transport
221
+ :param connection_type: String describing the connection type for error messages
222
+ :returns: List of available tools on the server
223
+ :raises MCPConnectionError: If connection to the server fails
224
+ """
225
+ try:
226
+ self.stdio, self.write = transport_tuple
227
+ self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
228
+
229
+ # Now session is guaranteed to be a ClientSession, not None
230
+ session = cast(ClientSession, self.session) # Tell mypy the type is now known
231
+ await session.initialize()
232
+
233
+ # List available tools
234
+ response = await session.list_tools()
235
+ return response.tools
236
+
237
+ except Exception as e:
238
+ await self.close()
239
+ message = f"Failed to connect to {connection_type}: {e}"
240
+ raise MCPConnectionError(message=message, operation="connect") from e
241
+
242
+
243
+ class StdioClient(MCPClient):
244
+ """
245
+ MCP client that connects to servers using stdio transport.
246
+ """
247
+
248
+ def __init__(self, command: str, args: list[str] | None = None, env: dict[str, str] | None = None) -> None:
249
+ """
250
+ Initialize a stdio MCP client.
251
+
252
+ :param command: Command to run (e.g., "python", "node")
253
+ :param args: Arguments to pass to the command
254
+ :param env: Environment variables for the command
255
+ """
256
+ super().__init__()
257
+ self.command: str = command
258
+ self.args: list[str] = args or []
259
+ self.env: dict[str, str] | None = env
260
+
261
+ async def connect(self) -> list[Tool]:
262
+ """
263
+ Connect to an MCP server using stdio transport.
264
+
265
+ :returns: List of available tools on the server
266
+ :raises MCPConnectionError: If connection to the server fails
267
+ """
268
+ server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env)
269
+ stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
270
+ return await self._initialize_session_with_transport(stdio_transport, f"stdio server (command: {self.command})")
271
+
272
+
273
+ class SSEClient(MCPClient):
274
+ """
275
+ MCP client that connects to servers using SSE transport.
276
+ """
277
+
278
+ def __init__(self, base_url: str, token: str | None = None, timeout: int = 5) -> None:
279
+ """
280
+ Initialize an SSE MCP client.
281
+
282
+ :param base_url: Base URL of the server
283
+ :param token: Authentication token for the server (optional)
284
+ :param timeout: Connection timeout in seconds
285
+ """
286
+ super().__init__()
287
+ self.base_url: str = base_url.rstrip("/") # Remove any trailing slashes
288
+ self.token: str | None = token
289
+ self.timeout: int = timeout
290
+
291
+ async def connect(self) -> list[Tool]:
292
+ """
293
+ Connect to an MCP server using SSE transport.
294
+
295
+ :returns: List of available tools on the server
296
+ :raises MCPConnectionError: If connection to the server fails
297
+ """
298
+ sse_url = f"{self.base_url}/sse"
299
+ headers = {"Authorization": f"Bearer {self.token}"} if self.token else None
300
+ sse_transport = await self.exit_stack.enter_async_context(
301
+ sse_client(sse_url, headers=headers, timeout=self.timeout)
302
+ )
303
+ return await self._initialize_session_with_transport(sse_transport, f"HTTP server at {self.base_url}")
304
+
305
+
306
+ @dataclass
307
+ class MCPServerInfo(ABC):
308
+ """
309
+ Abstract base class for MCP server connection parameters.
310
+
311
+ This class defines the common interface for all MCP server connection types.
312
+ """
313
+
314
+ @abstractmethod
315
+ def create_client(self) -> MCPClient:
316
+ """
317
+ Create an appropriate MCP client for this server info.
318
+
319
+ :returns: An instance of MCPClient configured with this server info
320
+ """
321
+ pass
322
+
323
+ def to_dict(self) -> dict[str, Any]:
324
+ """
325
+ Serialize this server info to a dictionary.
326
+
327
+ :returns: Dictionary representation of this server info
328
+ """
329
+ # Store the fully qualified class name for deserialization
330
+ result = {"type": generate_qualified_class_name(type(self))}
331
+
332
+ # Add all fields from the dataclass
333
+ for field in fields(self):
334
+ result[field.name] = getattr(self, field.name)
335
+
336
+ return result
337
+
338
+ @classmethod
339
+ def from_dict(cls, data: dict[str, Any]) -> "MCPServerInfo":
340
+ """
341
+ Deserialize server info from a dictionary.
342
+
343
+ :param data: Dictionary containing serialized server info
344
+ :returns: Instance of the appropriate server info class
345
+ """
346
+ # Remove the type field as it's not a constructor parameter
347
+ data_copy = data.copy()
348
+ data_copy.pop("type", None)
349
+
350
+ # Create an instance of the class with the remaining fields
351
+ return cls(**data_copy)
352
+
353
+
354
+ @dataclass
355
+ class SSEServerInfo(MCPServerInfo):
356
+ """
357
+ Data class that encapsulates SSE MCP server connection parameters.
358
+
359
+ :param base_url: Base URL of the MCP server
360
+ :param token: Authentication token for the server (optional)
361
+ :param timeout: Connection timeout in seconds
362
+ """
363
+
364
+ base_url: str
365
+ token: str | None = None
366
+ timeout: int = 30
367
+
368
+ def create_client(self) -> MCPClient:
369
+ """
370
+ Create an SSE MCP client.
371
+
372
+ :returns: Configured HttpMCPClient instance
373
+ """
374
+ return SSEClient(self.base_url, self.token, self.timeout)
375
+
376
+
377
+ @dataclass
378
+ class StdioServerInfo(MCPServerInfo):
379
+ """
380
+ Data class that encapsulates stdio MCP server connection parameters.
381
+
382
+ :param command: Command to run (e.g., "python", "node")
383
+ :param args: Arguments to pass to the command
384
+ :param env: Environment variables for the command
385
+ """
386
+
387
+ command: str
388
+ args: list[str] | None = None
389
+ env: dict[str, str] | None = None
390
+
391
+ def create_client(self) -> MCPClient:
392
+ """
393
+ Create a stdio MCP client.
394
+
395
+ :returns: Configured StdioMCPClient instance
396
+ """
397
+ return StdioClient(self.command, self.args, self.env)
398
+
399
+
400
+ class MCPTool(Tool):
401
+ """
402
+ A Tool that represents a single tool from an MCP server.
403
+
404
+ This implementation uses the official MCP SDK for protocol handling while maintaining
405
+ compatibility with the Haystack tool ecosystem.
406
+
407
+ Response handling:
408
+ - Text content is supported and returned as strings
409
+ - Unsupported content types (like binary/images) will raise MCPResponseTypeError
410
+
411
+ Example using HTTP:
412
+ ```python
413
+ from haystack.tools import MCPTool, SSEServerInfo
414
+
415
+ # Create tool instance
416
+ tool = MCPTool(
417
+ name="add",
418
+ server_info=SSEServerInfo(base_url="http://localhost:8000")
419
+ )
420
+
421
+ # Use the tool
422
+ result = tool.invoke(a=5, b=3)
423
+ ```
424
+
425
+ Example using stdio:
426
+ ```python
427
+ from haystack.tools import MCPTool, StdioServerInfo
428
+
429
+ # Create tool instance
430
+ tool = MCPTool(
431
+ name="get_current_time",
432
+ server_info=StdioServerInfo(command="python", args=["path/to/server.py"])
433
+ )
434
+
435
+ # Use the tool
436
+ result = tool.invoke(timezone="America/New_York")
437
+ ```
438
+ """
439
+
440
+ def __init__(
441
+ self,
442
+ name: str,
443
+ server_info: MCPServerInfo,
444
+ description: str | None = None,
445
+ connection_timeout: int = 30,
446
+ invocation_timeout: int = 30,
447
+ ):
448
+ """
449
+ Initialize the MCP tool.
450
+
451
+ :param name: Name of the tool to use
452
+ :param server_info: Server connection information
453
+ :param description: Custom description (if None, server description will be used)
454
+ :param connection_timeout: Timeout in seconds for server connection
455
+ :param invocation_timeout: Default timeout in seconds for tool invocations
456
+ :raises MCPConnectionError: If connection to the server fails
457
+ :raises MCPToolNotFoundError: If no tools are available or the requested tool is not found
458
+ :raises TimeoutError: If connection times out
459
+ """
460
+
461
+ # Store connection parameters for serialization
462
+ self._server_info = server_info
463
+ self._connection_timeout = connection_timeout
464
+ self._invocation_timeout = invocation_timeout
465
+ client = None
466
+
467
+ # Initialize the connection
468
+ try:
469
+ # Create the appropriate client using the factory method
470
+ client = server_info.create_client()
471
+
472
+ # Connect and get available tools with timeout
473
+ tools = self._run_sync(client.connect(), timeout=connection_timeout)
474
+
475
+ # Handle no tools case
476
+ if not tools:
477
+ message = "No tools available on server"
478
+ raise MCPToolNotFoundError(message, tool_name=name)
479
+
480
+ # Find the specified tool
481
+ tool_info = next((t for t in tools if t.name == name), None)
482
+ if not tool_info:
483
+ available_tool_names = [t.name for t in tools]
484
+ available_tools_str = ", ".join(available_tool_names)
485
+ message = f"Tool '{name}' not found on server. Available tools: {available_tools_str}"
486
+ raise MCPToolNotFoundError(message, tool_name=name, available_tools=available_tool_names)
487
+
488
+ # Store the client for later use
489
+ self._client = client
490
+
491
+ # Initialize the parent class with the final values
492
+ logger.debug(f"Initializing MCPTool with name: {name}")
493
+
494
+ # Hook into the Tool base class
495
+ super().__init__(
496
+ name=name,
497
+ description=description or tool_info.description,
498
+ parameters=tool_info.inputSchema,
499
+ function=self._invoke_tool,
500
+ )
501
+
502
+ except Exception as e:
503
+ # Ensure proper cleanup of resources on initialization failure
504
+ if client is not None:
505
+ try:
506
+ self._run_sync(client.close(), timeout=10) # Short timeout for cleanup
507
+ except Exception as cleanup_error:
508
+ logger.warning(f"Error during cleanup after initialization failure: {cleanup_error}")
509
+
510
+ message = f"Failed to initialize MCPTool '{name}': {e}"
511
+ raise MCPConnectionError(message=message, server_info=server_info, operation="initialize") from e
512
+
513
+ def _invoke_tool(self, **kwargs: Any) -> Any:
514
+ """
515
+ Synchronous tool invocation.
516
+
517
+ This method is called by the Tool base class's invoke() method.
518
+
519
+ :param kwargs: Arguments to pass to the tool
520
+ :returns: Result of the tool invocation, processed based on content type
521
+ :raises MCPInvocationError: If the tool invocation fails
522
+ :raises MCPResponseTypeError: If response type is not supported
523
+ :raises TimeoutError: If the operation times out
524
+ """
525
+ try:
526
+ # Use the configured invocation timeout
527
+ return self._run_sync(self._client.call_tool(self.name, kwargs), timeout=self._invocation_timeout)
528
+ except (MCPError, TimeoutError):
529
+ raise
530
+ except Exception as e:
531
+ message = f"Failed to invoke tool '{self.name}'"
532
+ raise MCPInvocationError(message, self.name, kwargs) from e
533
+
534
+ async def ainvoke(self, **kwargs: Any) -> Any:
535
+ """
536
+ Asynchronous tool invocation.
537
+
538
+ :param kwargs: Arguments to pass to the tool
539
+ :returns: Result of the tool invocation, processed based on content type
540
+ :raises MCPInvocationError: If the tool invocation fails
541
+ :raises MCPResponseTypeError: If response type is not supported
542
+ :raises TimeoutError: If the operation times out
543
+ """
544
+ try:
545
+ # Use asyncio.wait_for with the configured timeout
546
+ return await asyncio.wait_for(self._client.call_tool(self.name, kwargs), timeout=self._invocation_timeout)
547
+ except asyncio.TimeoutError as e:
548
+ message = f"Tool invocation timed out after {self._invocation_timeout} seconds"
549
+ raise TimeoutError(message) from e
550
+ except Exception as e:
551
+ if isinstance(e, MCPError):
552
+ raise
553
+ message = f"Failed to invoke tool '{self.name}'"
554
+ raise MCPInvocationError(message, self.name, kwargs) from e
555
+
556
+ def to_dict(self) -> dict[str, Any]:
557
+ """
558
+ Serializes the MCPTool to a dictionary.
559
+
560
+ The serialization preserves all information needed to recreate the tool,
561
+ including server connection parameters and timeout settings. Note that the
562
+ active connection is not maintained.
563
+
564
+ :returns: Dictionary with serialized data in the format:
565
+ {"type": fully_qualified_class_name, "data": {parameters}}
566
+ """
567
+ serialized = {
568
+ "name": self.name,
569
+ "description": self.description,
570
+ "server_info": self._server_info.to_dict(),
571
+ "connection_timeout": self._connection_timeout,
572
+ "invocation_timeout": self._invocation_timeout,
573
+ }
574
+ return {
575
+ "type": generate_qualified_class_name(type(self)),
576
+ "data": serialized,
577
+ }
578
+
579
+ @classmethod
580
+ def from_dict(cls, data: dict[str, Any]) -> "Tool":
581
+ """
582
+ Deserializes the MCPTool from a dictionary.
583
+
584
+ This method reconstructs an MCPTool instance from a serialized dictionary,
585
+ including recreating the server_info object. A new connection will be established
586
+ to the MCP server during initialization.
587
+
588
+ :param data: Dictionary containing serialized tool data
589
+ :returns: A fully initialized MCPTool instance
590
+ :raises: Various exceptions if connection fails
591
+ """
592
+ # Extract the tool parameters from the data dictionary
593
+ inner_data = data["data"]
594
+ server_info_dict = inner_data.get("server_info", {})
595
+
596
+ # Reconstruct the server_info object
597
+ # First get the appropriate class by name
598
+ server_info_class = import_class_by_name(server_info_dict["type"])
599
+ # Then deserialize using that class's from_dict method
600
+ server_info = server_info_class.from_dict(server_info_dict)
601
+
602
+ # Handle backward compatibility for timeout parameters
603
+ connection_timeout = inner_data.get("connection_timeout", 30)
604
+ invocation_timeout = inner_data.get("invocation_timeout", 30)
605
+
606
+ # Create a new MCPTool instance with the deserialized parameters
607
+ # This will establish a new connection to the MCP server
608
+ return cls(
609
+ name=inner_data["name"],
610
+ description=inner_data.get("description"),
611
+ server_info=server_info,
612
+ connection_timeout=connection_timeout,
613
+ invocation_timeout=invocation_timeout,
614
+ )
615
+
616
+ def _run_sync(self, coro: Coroutine, timeout: float | None = 30) -> Any:
617
+ """
618
+ Run a coroutine in a synchronous context with improved handling.
619
+
620
+ This implementation is optimized for use with AsyncExitStack by ensuring
621
+ that coroutines run in the same event loop where AsyncExitStack resources
622
+ were initialized.
623
+
624
+ :param coro: Coroutine to run
625
+ :param timeout: Optional timeout in seconds
626
+ :returns: Result of the coroutine
627
+ :raises TimeoutError: If the operation times out
628
+ :raises Exception: Any exception that might occur during execution
629
+ """
630
+ try:
631
+ # Apply timeout if specified
632
+ if timeout is not None:
633
+ coro = asyncio.wait_for(coro, timeout)
634
+
635
+ # Try to get a running loop first (modern approach)
636
+ try:
637
+ loop = asyncio.get_running_loop()
638
+ except RuntimeError:
639
+ # No running loop, so we need to get or create one.
640
+ # The important part for AsyncExitStack compatibility is that
641
+ # we must use the SAME loop that was used to create the stack.
642
+
643
+ # IMPORTANT: Using get_event_loop() is necessary for AsyncExitStack compatibility
644
+ # but it generates a "There is no current event loop" deprecation warning in
645
+ # Python 3.10, 3.11, and 3.12.
646
+ #
647
+ # This is unavoidable because:
648
+ # 1. AsyncExitStack binds its resources to the loop where it was created
649
+ # 2. That loop was created using get_event_loop() internally
650
+ # 3. To access those resources, we must use the same loop
651
+ # 4. The only way to get that same loop is with get_event_loop()
652
+ loop = asyncio.get_event_loop_policy().get_event_loop()
653
+
654
+ # Run the coroutine in the loop but don't close it
655
+ # AsyncExitStack depends on this loop staying open
656
+ return loop.run_until_complete(coro)
657
+
658
+ except asyncio.TimeoutError:
659
+ message = f"Operation timed out after {timeout} seconds"
660
+ raise TimeoutError(message) from None
661
+ except Exception:
662
+ # Preserve the original exception
663
+ raise
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-haystack
3
+ Version: 0.0.1
4
+ Summary: Haystack integration for Model Context Protocol (MCP)
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mcp#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mcp
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: Haystack,MCP,Model Context Protocol
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: haystack-ai>=2.9.0
22
+ Requires-Dist: mcp
23
+ Description-Content-Type: text/markdown
24
+
25
+ # MCP Haystack Integration
26
+
27
+ This integration adds support for the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) to Haystack. MCP is an open protocol that standardizes how applications provide context to LLMs, similar to how USB-C provides a standardized way to connect devices.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install mcp-haystack
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from haystack_integrations.components.tools.mcp import MCPTool, SSEServerInfo
39
+
40
+ # Create an MCP tool that connects to an HTTP server
41
+ server_info = SSEServerInfo(base_url="http://localhost:8000")
42
+ tool = MCPTool(name="my_tool", server_info=server_info)
43
+
44
+ # Use the tool
45
+ result = tool.invoke(param1="value1", param2="value2")
46
+ ```
47
+
48
+ # Examples
49
+
50
+ Check out the examples directory to see practical demonstrations of how to integrate the MCPTool into Haystack's tooling architecture. These examples will help you get started quickly with your own agentic applications.
51
+
52
+ ## What is uvx?
53
+
54
+ In some examples below, we use the `StdioServerInfo` class which relies on `uvx` behind the scenes. `uvx` is a convenient command from the uv package that runs Python tools in temporary, isolated environments. You only need to install `uvx` once, and it will automatically fetch any required packages on first use without needing manual installation.
55
+
56
+ ## Example 1: MCP Server with SSE Transport
57
+
58
+ This example demonstrates how to create a simple calculator server using MCP and connect to it using the MCPTool with SSE transport.
59
+
60
+ ### Step 1: Run the MCP Server
61
+
62
+ First, run the server that exposes calculator functionality (addition and subtraction) via MCP:
63
+
64
+ ```bash
65
+ python examples/mcp_sse_server.py
66
+ ```
67
+
68
+ This creates a FastMCP server with two tools:
69
+ - `add(a, b)`: Adds two numbers
70
+ - `subtract(a, b)`: Subtracts two numbers
71
+
72
+ The server runs on http://localhost:8000 by default.
73
+
74
+ ### Step 2: Connect with the MCP Client
75
+
76
+ In a separate terminal, run the client that connects to the calculator server:
77
+
78
+ ```bash
79
+ python examples/mcp_sse_client.py
80
+ ```
81
+
82
+ The client creates MCPTool instances that connect to the server, inspect the tool specifications, and invoke the calculator functions remotely.
83
+
84
+ ## Example 2: MCP with StdIO Transport
85
+
86
+ This example shows how to use MCPTool with stdio transport to execute a local program directly:
87
+
88
+ ```bash
89
+ python examples/mcp_stdio_client.py
90
+ ```
91
+
92
+ The example creates an MCPTool that uses stdio transport with `StdioServerInfo`, which automatically uses `uvx` behind the scenes to run the `mcp-server-time` tool without requiring manual installation. It queries the current time in different timezones (New York and Los Angeles) by invoking the tool with different parameters.
93
+
94
+ This demonstrates how MCPTool can work with local programs without running a separate server process, using standard input/output for communication.
95
+
96
+ ## Example 3: MCPTool in a Haystack Pipeline
97
+
98
+ This example showcases how to integrate MCPTool into a Haystack pipeline along with an LLM:
99
+
100
+ ```bash
101
+ python examples/time_pipeline.py
102
+ ```
103
+
104
+ This example creates a pipeline that:
105
+ 1. Takes a user query about the current time in a city
106
+ 2. Uses an LLM (GPT-4o-mini) to interpret the query and decide which tool to use
107
+ 3. Invokes the time tool with the appropriate parameters (using `uvx` behind the scenes)
108
+ 4. Sends the tool's response back to the LLM to generate a final answer
109
+
110
+ This demonstrates how MCPTool can be seamlessly integrated into Haystack's agentic architecture, allowing LLMs to use external tools via the Model Context Protocol.
111
+
112
+ ## License
113
+
114
+ Apache 2.0
@@ -0,0 +1,6 @@
1
+ haystack_integrations/tools/mcp/__init__.py,sha256=pEchrb0JsHzpfg4WScvCKnt737TUG_yZwM9ck8p6MiI,477
2
+ haystack_integrations/tools/mcp/mcp_tool.py,sha256=cwP2Rb2HQVm0Bv9oXM2EvrOX2jHP_nzQGc7IreXgda0,25005
3
+ mcp_haystack-0.0.1.dist-info/METADATA,sha256=2UhzsnOEloR94t1Z0UzJltJE3CEp--y44WjEfZ9PJ-U,4651
4
+ mcp_haystack-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ mcp_haystack-0.0.1.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
6
+ mcp_haystack-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.