rasa-pro 3.13.6__py3-none-any.whl → 3.14.0.dev1__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.

Potentially problematic release.


This version of rasa-pro might be problematic. Click here for more details.

Files changed (178) hide show
  1. rasa/agents/__init__.py +0 -0
  2. rasa/agents/agent_factory.py +122 -0
  3. rasa/agents/agent_manager.py +162 -0
  4. rasa/agents/constants.py +31 -0
  5. rasa/agents/core/__init__.py +0 -0
  6. rasa/agents/core/agent_protocol.py +108 -0
  7. rasa/agents/core/types.py +70 -0
  8. rasa/agents/exceptions.py +8 -0
  9. rasa/agents/protocol/__init__.py +5 -0
  10. rasa/agents/protocol/a2a/__init__.py +0 -0
  11. rasa/agents/protocol/a2a/a2a_agent.py +51 -0
  12. rasa/agents/protocol/mcp/__init__.py +0 -0
  13. rasa/agents/protocol/mcp/mcp_base_agent.py +697 -0
  14. rasa/agents/protocol/mcp/mcp_open_agent.py +275 -0
  15. rasa/agents/protocol/mcp/mcp_task_agent.py +447 -0
  16. rasa/agents/schemas/__init__.py +6 -0
  17. rasa/agents/schemas/agent_input.py +24 -0
  18. rasa/agents/schemas/agent_output.py +26 -0
  19. rasa/agents/schemas/agent_tool_result.py +51 -0
  20. rasa/agents/schemas/agent_tool_schema.py +112 -0
  21. rasa/agents/templates/__init__.py +0 -0
  22. rasa/agents/templates/mcp_open_agent_prompt_template.jinja2 +15 -0
  23. rasa/agents/templates/mcp_task_agent_prompt_template.jinja2 +13 -0
  24. rasa/agents/utils.py +72 -0
  25. rasa/api.py +5 -0
  26. rasa/cli/arguments/default_arguments.py +12 -0
  27. rasa/cli/arguments/run.py +2 -0
  28. rasa/cli/dialogue_understanding_test.py +4 -0
  29. rasa/cli/e2e_test.py +4 -0
  30. rasa/cli/inspect.py +3 -0
  31. rasa/cli/llm_fine_tuning.py +5 -0
  32. rasa/cli/run.py +4 -0
  33. rasa/cli/shell.py +3 -0
  34. rasa/cli/train.py +2 -2
  35. rasa/constants.py +6 -0
  36. rasa/core/actions/action.py +69 -39
  37. rasa/core/actions/action_run_slot_rejections.py +1 -1
  38. rasa/core/agent.py +16 -0
  39. rasa/core/available_agents.py +196 -0
  40. rasa/core/available_endpoints.py +30 -0
  41. rasa/core/channels/development_inspector.py +47 -14
  42. rasa/core/channels/inspector/dist/assets/{arc-0b11fe30.js → arc-2e78c586.js} +1 -1
  43. rasa/core/channels/inspector/dist/assets/{blockDiagram-38ab4fdb-9eef30a7.js → blockDiagram-38ab4fdb-806b712e.js} +1 -1
  44. rasa/core/channels/inspector/dist/assets/{c4Diagram-3d4e48cf-03e94f28.js → c4Diagram-3d4e48cf-0745efa9.js} +1 -1
  45. rasa/core/channels/inspector/dist/assets/channel-c436ca7c.js +1 -0
  46. rasa/core/channels/inspector/dist/assets/{classDiagram-70f12bd4-95c09eba.js → classDiagram-70f12bd4-7bd1082b.js} +1 -1
  47. rasa/core/channels/inspector/dist/assets/{classDiagram-v2-f2320105-38e8446c.js → classDiagram-v2-f2320105-d937ba49.js} +1 -1
  48. rasa/core/channels/inspector/dist/assets/clone-50dd656b.js +1 -0
  49. rasa/core/channels/inspector/dist/assets/{createText-2e5e7dd3-57dc3038.js → createText-2e5e7dd3-a2a564ca.js} +1 -1
  50. rasa/core/channels/inspector/dist/assets/{edges-e0da2a9e-4bac0545.js → edges-e0da2a9e-b5256940.js} +1 -1
  51. rasa/core/channels/inspector/dist/assets/{erDiagram-9861fffd-81795c90.js → erDiagram-9861fffd-e6883ad2.js} +1 -1
  52. rasa/core/channels/inspector/dist/assets/{flowDb-956e92f1-89489ae6.js → flowDb-956e92f1-e576fc02.js} +1 -1
  53. rasa/core/channels/inspector/dist/assets/{flowDiagram-66a62f08-cd152627.js → flowDiagram-66a62f08-2e298d01.js} +1 -1
  54. rasa/core/channels/inspector/dist/assets/flowDiagram-v2-96b9c2cf-2b2aeaf8.js +1 -0
  55. rasa/core/channels/inspector/dist/assets/{flowchart-elk-definition-4a651766-3da369bc.js → flowchart-elk-definition-4a651766-dd7b150a.js} +1 -1
  56. rasa/core/channels/inspector/dist/assets/{ganttDiagram-c361ad54-85ec16f8.js → ganttDiagram-c361ad54-5b79575c.js} +1 -1
  57. rasa/core/channels/inspector/dist/assets/{gitGraphDiagram-72cf32ee-495bc140.js → gitGraphDiagram-72cf32ee-3016f40a.js} +1 -1
  58. rasa/core/channels/inspector/dist/assets/{graph-1ec4d266.js → graph-3e19170f.js} +1 -1
  59. rasa/core/channels/inspector/dist/assets/index-1bd9135e.js +1353 -0
  60. rasa/core/channels/inspector/dist/assets/{index-3862675e-0a0e97c9.js → index-3862675e-eb9c86de.js} +1 -1
  61. rasa/core/channels/inspector/dist/assets/{infoDiagram-f8f76790-4d54bcde.js → infoDiagram-f8f76790-b4280e4d.js} +1 -1
  62. rasa/core/channels/inspector/dist/assets/{journeyDiagram-49397b02-dc097114.js → journeyDiagram-49397b02-556091f8.js} +1 -1
  63. rasa/core/channels/inspector/dist/assets/{layout-1a08981e.js → layout-08436411.js} +1 -1
  64. rasa/core/channels/inspector/dist/assets/{line-95f7f1d3.js → line-683c4f3b.js} +1 -1
  65. rasa/core/channels/inspector/dist/assets/{linear-97e69543.js → linear-cee6d791.js} +1 -1
  66. rasa/core/channels/inspector/dist/assets/{mindmap-definition-fc14e90a-8c71ff03.js → mindmap-definition-fc14e90a-a0bf0b1a.js} +1 -1
  67. rasa/core/channels/inspector/dist/assets/{pieDiagram-8a3498a8-f14c71c7.js → pieDiagram-8a3498a8-3730d5c4.js} +1 -1
  68. rasa/core/channels/inspector/dist/assets/{quadrantDiagram-120e2f19-f1d3c9ff.js → quadrantDiagram-120e2f19-12a20fed.js} +1 -1
  69. rasa/core/channels/inspector/dist/assets/{requirementDiagram-deff3bca-bfa2412f.js → requirementDiagram-deff3bca-b9732102.js} +1 -1
  70. rasa/core/channels/inspector/dist/assets/{sankeyDiagram-04a897e0-53f2c97b.js → sankeyDiagram-04a897e0-a2e72776.js} +1 -1
  71. rasa/core/channels/inspector/dist/assets/{sequenceDiagram-704730f1-319d7c0e.js → sequenceDiagram-704730f1-8b7a76bb.js} +1 -1
  72. rasa/core/channels/inspector/dist/assets/{stateDiagram-587899a1-76a09418.js → stateDiagram-587899a1-e65853ac.js} +1 -1
  73. rasa/core/channels/inspector/dist/assets/{stateDiagram-v2-d93cdb3a-a67f15d4.js → stateDiagram-v2-d93cdb3a-6f58a44b.js} +1 -1
  74. rasa/core/channels/inspector/dist/assets/{styles-6aaf32cf-0654e7c3.js → styles-6aaf32cf-df25b934.js} +1 -1
  75. rasa/core/channels/inspector/dist/assets/{styles-9a916d00-1394bb9d.js → styles-9a916d00-88357141.js} +1 -1
  76. rasa/core/channels/inspector/dist/assets/{styles-c10674c1-e4c5bdae.js → styles-c10674c1-d600174d.js} +1 -1
  77. rasa/core/channels/inspector/dist/assets/{svgDrawCommon-08f97a94-50957104.js → svgDrawCommon-08f97a94-4adc3e0b.js} +1 -1
  78. rasa/core/channels/inspector/dist/assets/{timeline-definition-85554ec2-b0885a6a.js → timeline-definition-85554ec2-42816fa1.js} +1 -1
  79. rasa/core/channels/inspector/dist/assets/{xychartDiagram-e933f94c-79e6541a.js → xychartDiagram-e933f94c-621eb66a.js} +1 -1
  80. rasa/core/channels/inspector/dist/index.html +2 -2
  81. rasa/core/channels/inspector/index.html +1 -1
  82. rasa/core/channels/inspector/src/App.tsx +53 -7
  83. rasa/core/channels/inspector/src/components/Chat.tsx +3 -2
  84. rasa/core/channels/inspector/src/components/DiagramFlow.tsx +1 -1
  85. rasa/core/channels/inspector/src/components/DialogueStack.tsx +7 -5
  86. rasa/core/channels/inspector/src/components/LatencyDisplay.tsx +268 -0
  87. rasa/core/channels/inspector/src/components/LoadingSpinner.tsx +6 -2
  88. rasa/core/channels/inspector/src/helpers/audio/audiostream.ts +8 -3
  89. rasa/core/channels/inspector/src/helpers/formatters.ts +24 -3
  90. rasa/core/channels/inspector/src/theme/base/styles.ts +19 -1
  91. rasa/core/channels/inspector/src/types.ts +12 -0
  92. rasa/core/channels/studio_chat.py +125 -34
  93. rasa/core/channels/voice_ready/twilio_voice.py +1 -1
  94. rasa/core/channels/voice_stream/audiocodes.py +9 -6
  95. rasa/core/channels/voice_stream/browser_audio.py +39 -4
  96. rasa/core/channels/voice_stream/call_state.py +13 -2
  97. rasa/core/channels/voice_stream/genesys.py +16 -13
  98. rasa/core/channels/voice_stream/jambonz.py +13 -11
  99. rasa/core/channels/voice_stream/twilio_media_streams.py +14 -13
  100. rasa/core/channels/voice_stream/util.py +11 -1
  101. rasa/core/channels/voice_stream/voice_channel.py +101 -29
  102. rasa/core/constants.py +4 -0
  103. rasa/core/nlg/contextual_response_rephraser.py +11 -7
  104. rasa/core/nlg/generator.py +21 -5
  105. rasa/core/nlg/response.py +43 -6
  106. rasa/core/nlg/translate.py +8 -0
  107. rasa/core/policies/enterprise_search_policy.py +4 -2
  108. rasa/core/policies/flow_policy.py +2 -2
  109. rasa/core/policies/flows/flow_executor.py +374 -35
  110. rasa/core/policies/flows/mcp_tool_executor.py +240 -0
  111. rasa/core/processor.py +6 -1
  112. rasa/core/run.py +8 -1
  113. rasa/core/utils.py +21 -1
  114. rasa/dialogue_understanding/commands/__init__.py +8 -0
  115. rasa/dialogue_understanding/commands/cancel_flow_command.py +97 -4
  116. rasa/dialogue_understanding/commands/chit_chat_answer_command.py +11 -0
  117. rasa/dialogue_understanding/commands/continue_agent_command.py +91 -0
  118. rasa/dialogue_understanding/commands/knowledge_answer_command.py +11 -0
  119. rasa/dialogue_understanding/commands/restart_agent_command.py +146 -0
  120. rasa/dialogue_understanding/commands/start_flow_command.py +129 -8
  121. rasa/dialogue_understanding/commands/utils.py +6 -2
  122. rasa/dialogue_understanding/generator/command_parser.py +4 -0
  123. rasa/dialogue_understanding/generator/llm_based_command_generator.py +50 -12
  124. rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v2_claude_3_5_sonnet_20240620_template.jinja2 +61 -0
  125. rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v2_gpt_4o_2024_11_20_template.jinja2 +61 -0
  126. rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v3_claude_3_5_sonnet_20240620_template.jinja2 +81 -0
  127. rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v3_gpt_4o_2024_11_20_template.jinja2 +81 -0
  128. rasa/dialogue_understanding/generator/single_step/compact_llm_command_generator.py +7 -6
  129. rasa/dialogue_understanding/generator/single_step/search_ready_llm_command_generator.py +7 -6
  130. rasa/dialogue_understanding/generator/single_step/single_step_based_llm_command_generator.py +41 -2
  131. rasa/dialogue_understanding/patterns/continue_interrupted.py +163 -1
  132. rasa/dialogue_understanding/patterns/default_flows_for_patterns.yml +51 -7
  133. rasa/dialogue_understanding/processor/command_processor.py +27 -11
  134. rasa/dialogue_understanding/stack/dialogue_stack.py +123 -2
  135. rasa/dialogue_understanding/stack/frames/flow_stack_frame.py +57 -0
  136. rasa/dialogue_understanding/stack/utils.py +3 -2
  137. rasa/dialogue_understanding_test/du_test_runner.py +7 -2
  138. rasa/dialogue_understanding_test/du_test_schema.yml +3 -3
  139. rasa/e2e_test/e2e_test_runner.py +5 -0
  140. rasa/e2e_test/e2e_test_schema.yml +3 -3
  141. rasa/model_manager/model_api.py +1 -1
  142. rasa/model_manager/socket_bridge.py +8 -2
  143. rasa/server.py +10 -0
  144. rasa/shared/agents/__init__.py +0 -0
  145. rasa/shared/agents/utils.py +35 -0
  146. rasa/shared/constants.py +5 -0
  147. rasa/shared/core/constants.py +12 -1
  148. rasa/shared/core/domain.py +5 -5
  149. rasa/shared/core/events.py +319 -0
  150. rasa/shared/core/flows/flows_list.py +2 -2
  151. rasa/shared/core/flows/flows_yaml_schema.json +101 -186
  152. rasa/shared/core/flows/steps/call.py +51 -5
  153. rasa/shared/core/flows/validation.py +45 -7
  154. rasa/shared/core/flows/yaml_flows_io.py +3 -3
  155. rasa/shared/providers/llm/_base_litellm_client.py +39 -7
  156. rasa/shared/providers/llm/litellm_router_llm_client.py +8 -4
  157. rasa/shared/providers/llm/llm_client.py +7 -3
  158. rasa/shared/providers/llm/llm_response.py +49 -0
  159. rasa/shared/providers/llm/self_hosted_llm_client.py +8 -4
  160. rasa/shared/utils/common.py +2 -1
  161. rasa/shared/utils/llm.py +28 -5
  162. rasa/shared/utils/mcp/__init__.py +0 -0
  163. rasa/shared/utils/mcp/server_connection.py +157 -0
  164. rasa/shared/utils/schemas/events.py +42 -0
  165. rasa/tracing/instrumentation/instrumentation.py +4 -2
  166. rasa/utils/common.py +53 -0
  167. rasa/utils/licensing.py +21 -10
  168. rasa/utils/plotting.py +1 -1
  169. rasa/version.py +1 -1
  170. {rasa_pro-3.13.6.dist-info → rasa_pro-3.14.0.dev1.dist-info}/METADATA +16 -15
  171. {rasa_pro-3.13.6.dist-info → rasa_pro-3.14.0.dev1.dist-info}/RECORD +174 -137
  172. rasa/core/channels/inspector/dist/assets/channel-51d02e9e.js +0 -1
  173. rasa/core/channels/inspector/dist/assets/clone-cc738fa6.js +0 -1
  174. rasa/core/channels/inspector/dist/assets/flowDiagram-v2-96b9c2cf-0c716443.js +0 -1
  175. rasa/core/channels/inspector/dist/assets/index-c804b295.js +0 -1335
  176. {rasa_pro-3.13.6.dist-info → rasa_pro-3.14.0.dev1.dist-info}/NOTICE +0 -0
  177. {rasa_pro-3.13.6.dist-info → rasa_pro-3.14.0.dev1.dist-info}/WHEEL +0 -0
  178. {rasa_pro-3.13.6.dist-info → rasa_pro-3.14.0.dev1.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,697 @@
1
+ import json
2
+ from abc import abstractmethod
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import structlog
6
+ from jinja2 import Template
7
+ from mcp import ListToolsResult
8
+
9
+ from rasa.agents.constants import (
10
+ AGENT_METADATA_TOOL_RESULTS_KEY,
11
+ KEY_ARGUMENTS,
12
+ KEY_CONTENT,
13
+ KEY_FUNCTION,
14
+ KEY_ID,
15
+ KEY_NAME,
16
+ KEY_ROLE,
17
+ KEY_TOOL_CALL_ID,
18
+ KEY_TOOL_CALLS,
19
+ KEY_TYPE,
20
+ )
21
+ from rasa.agents.core.agent_protocol import AgentProtocol
22
+ from rasa.agents.core.types import AgentStatus, ProtocolType
23
+ from rasa.agents.schemas import (
24
+ AgentInput,
25
+ AgentOutput,
26
+ AgentToolResult,
27
+ AgentToolSchema,
28
+ )
29
+ from rasa.core.available_agents import AgentConfig, AgentMCPServerConfig, ProtocolConfig
30
+ from rasa.shared.agents.utils import make_agent_identifier
31
+ from rasa.shared.constants import (
32
+ MAX_COMPLETION_TOKENS_CONFIG_KEY,
33
+ MODEL_CONFIG_KEY,
34
+ OPENAI_PROVIDER,
35
+ PROVIDER_CONFIG_KEY,
36
+ ROLE_ASSISTANT,
37
+ ROLE_SYSTEM,
38
+ ROLE_TOOL,
39
+ ROLE_USER,
40
+ TEMPERATURE_CONFIG_KEY,
41
+ TIMEOUT_CONFIG_KEY,
42
+ )
43
+ from rasa.shared.core.events import BotUttered, UserUttered
44
+ from rasa.shared.providers.llm.llm_response import LLMResponse, LLMToolCall
45
+ from rasa.shared.utils.constants import LOG_COMPONENT_SOURCE_METHOD_INIT
46
+ from rasa.shared.utils.llm import (
47
+ get_prompt_template,
48
+ llm_factory,
49
+ resolve_model_client_config,
50
+ )
51
+ from rasa.shared.utils.mcp.server_connection import MCPServerConnection
52
+
53
+ DEFAULT_OPENAI_MAX_GENERATED_TOKENS = 256
54
+ MODEL_NAME_GPT_4O_2024_11_20 = "gpt-4o-2024-11-20"
55
+ DEFAULT_LLM_CONFIG = {
56
+ PROVIDER_CONFIG_KEY: OPENAI_PROVIDER,
57
+ MODEL_CONFIG_KEY: MODEL_NAME_GPT_4O_2024_11_20,
58
+ TEMPERATURE_CONFIG_KEY: 0.0,
59
+ MAX_COMPLETION_TOKENS_CONFIG_KEY: DEFAULT_OPENAI_MAX_GENERATED_TOKENS,
60
+ TIMEOUT_CONFIG_KEY: 7,
61
+ }
62
+
63
+
64
+ structlogger = structlog.get_logger()
65
+
66
+
67
+ class MCPBaseAgent(AgentProtocol):
68
+ """MCP protocol implementation"""
69
+
70
+ MAX_ITERATIONS = 10
71
+
72
+ # ============================================================================
73
+ # Initialization & Setup
74
+ # ============================================================================
75
+
76
+ def __init__(
77
+ self,
78
+ name: str,
79
+ description: str,
80
+ protocol_type: ProtocolConfig,
81
+ server_configs: List[AgentMCPServerConfig],
82
+ llm_config: Optional[Dict[str, Any]] = None,
83
+ prompt_template: Optional[str] = None,
84
+ timeout: Optional[int] = None,
85
+ max_retries: Optional[int] = None,
86
+ ):
87
+ self._name = name
88
+
89
+ self._description = description
90
+
91
+ self._protocol_type = protocol_type
92
+
93
+ self._llm_config = resolve_model_client_config(
94
+ llm_config, self.__class__.__name__
95
+ )
96
+
97
+ self.llm_client = llm_factory(self._llm_config, self.get_default_llm_config())
98
+
99
+ self.prompt_template = get_prompt_template(
100
+ prompt_template,
101
+ self.get_default_prompt_template(),
102
+ log_source_component=self.__class__.__name__,
103
+ log_source_method=LOG_COMPONENT_SOURCE_METHOD_INIT,
104
+ )
105
+
106
+ self._timeout = timeout or 30
107
+
108
+ self._max_retries = max_retries or 3
109
+
110
+ self._server_configs = server_configs or []
111
+
112
+ # Stores the MCP tools for the agent.
113
+ self._mcp_tools: List[AgentToolSchema] = []
114
+
115
+ # Maps the tool names to the MCP servers that provide them.
116
+ # key: tool name, value: server name.
117
+ self._tool_to_server_mapper: Dict[str, str] = {}
118
+
119
+ # Stores the connections to the MCP servers.
120
+ # key: server name, value: connection object.
121
+ self._server_connections: Dict[str, MCPServerConnection] = {}
122
+
123
+ @classmethod
124
+ def from_config(cls, config: AgentConfig) -> "MCPBaseAgent":
125
+ """Initialize the MCP Open Agent with the given configuration."""
126
+ return cls(
127
+ name=config.agent.name,
128
+ description=config.agent.description,
129
+ protocol_type=config.agent.protocol,
130
+ llm_config=config.configuration.llm if config.configuration else None,
131
+ prompt_template=config.configuration.prompt_template
132
+ if config.configuration
133
+ else None,
134
+ timeout=config.configuration.timeout if config.configuration else None,
135
+ max_retries=config.configuration.max_retries
136
+ if config.configuration
137
+ else None,
138
+ server_configs=config.connections.mcp_servers
139
+ if config.connections
140
+ else None,
141
+ )
142
+
143
+ # ============================================================================
144
+ # Class Configuration & Properties
145
+ # ============================================================================
146
+
147
+ @classmethod
148
+ @abstractmethod
149
+ def get_default_prompt_template(cls) -> str: ...
150
+
151
+ @property
152
+ def agent_conforms_to(self) -> ProtocolConfig:
153
+ return self._protocol_type
154
+
155
+ @property
156
+ @abstractmethod
157
+ def protocol_type(self) -> ProtocolType: ...
158
+
159
+ @staticmethod
160
+ def get_default_llm_config() -> Dict[str, Any]:
161
+ """Get the default LLM config for the command generator."""
162
+ return DEFAULT_LLM_CONFIG
163
+
164
+ @classmethod
165
+ def get_agent_specific_built_in_tools(
166
+ cls, agent_input: AgentInput
167
+ ) -> List[Dict[str, Any]]:
168
+ """Get agentic specific built-in tools."""
169
+ return []
170
+
171
+ @staticmethod
172
+ def get_additional_tools(agent_input: AgentInput) -> List[Dict[str, Any]]:
173
+ """Get additional tools for MCP. Override to add specific tools.
174
+ This method can be overridden to provide additional tools that the agent
175
+ can use during its operation. The tools should be defined in the OpenAI
176
+ JSON format, which includes the tool name, description, and parameters.
177
+
178
+ Refer: https://platform.openai.com/docs/guides/function-calling?api-mode=responses
179
+
180
+ Args:
181
+ agent_input: The agent input.
182
+
183
+ Returns:
184
+ A list of additional tools.
185
+
186
+ Example:
187
+ ```python
188
+ def get_additional_tools(self) -> List[Dict[str, Any]]:
189
+ return [
190
+ {
191
+ "type": "function",
192
+ "function": {
193
+ "name": "get_current_weather",
194
+ "description": "Get the current weather in given location",
195
+ "parameters": {
196
+ "type": "object",
197
+ "properties": {
198
+ "location": {
199
+ "type": "string",
200
+ "description": "The city, e.g. San Francisco",
201
+ },
202
+ "unit": {
203
+ "type": "string",
204
+ "enum": ["celsius", "fahrenheit"],
205
+ },
206
+ },
207
+ "required": ["location"],
208
+ },
209
+ },
210
+ }
211
+ ]
212
+ ```
213
+ """
214
+ return []
215
+
216
+ # ============================================================================
217
+ # Connection Management
218
+ # ============================================================================
219
+
220
+ async def connect(self) -> None:
221
+ """Connect to the MCP servers and initialize the agent.
222
+
223
+ This method establishes connections to the configured MCP servers,
224
+ fetches the available tools, and prepares the agent for operation.
225
+ It should be called before sending any messages to the agent.
226
+
227
+ Retries:
228
+ Retries connection N times if a ConnectionError is raised.
229
+
230
+ Logs:
231
+ Warning: If the connection to any server fails.
232
+ Warning: If there is a duplicate tool name across servers.
233
+ Warning: If there is an error fetching tools from any server.
234
+ """
235
+ for attempt in range(1, self._max_retries + 1):
236
+ try:
237
+ await self.connect_to_servers()
238
+ await self.fetch_and_store_available_tools()
239
+ break
240
+ except ConnectionError as ce:
241
+ structlogger.warning(
242
+ "mcp_agent.connect.connection_error",
243
+ event_info=f"Connection attempt {attempt} failed: {ce}",
244
+ attempt=attempt,
245
+ max_retries=self._max_retries,
246
+ )
247
+ if attempt == self._max_retries:
248
+ structlogger.error(
249
+ "mcp_agent.connect.failed_after_retries",
250
+ event_info="All connection attempts failed.",
251
+ )
252
+ except Exception as e:
253
+ structlogger.error(
254
+ "mcp_agent.connect.unexpected_exception",
255
+ event_info="Unexpected error during agent initialization.",
256
+ error=str(e),
257
+ )
258
+
259
+ async def connect_to_server(self, server_config: AgentMCPServerConfig) -> None:
260
+ server_name = server_config.name
261
+ connection = MCPServerConnection.from_config(server_config.model_dump())
262
+ try:
263
+ await connection.connect()
264
+ self._server_connections[server_name] = connection
265
+ structlogger.info(
266
+ "mcp_agent.connect_to_server.connected",
267
+ event_info=(
268
+ f"Agent `{self._name}` connected to MCP server - "
269
+ f"`{server_name}` @ `{connection.server_url}`"
270
+ ),
271
+ server_id=server_name,
272
+ server_url=connection.server_url,
273
+ agent_name=self._name,
274
+ agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
275
+ )
276
+ except Exception as e:
277
+ event_info = (
278
+ f"Agent `{self._name}` failed to connect to MCP server - "
279
+ f"{server_name} @ {server_config.url}: {e}"
280
+ )
281
+ structlogger.error(
282
+ "mcp_agent.connect.failed_to_connect",
283
+ event_info=event_info,
284
+ server_id=server_name,
285
+ server_url=server_config.url,
286
+ agent_name=self._name,
287
+ agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
288
+ )
289
+ raise ConnectionError(e)
290
+
291
+ async def connect_to_servers(self) -> None:
292
+ """Connect to MCP servers."""
293
+ for server_config in self._server_configs:
294
+ await self.connect_to_server(server_config)
295
+
296
+ async def disconnect_server(self, server_name: str) -> None:
297
+ """Disconnect from an MCP server.
298
+
299
+ Args:
300
+ server_name: The name of the server to disconnect from.
301
+
302
+ Side effects:
303
+ - Removes the server from the server connections.
304
+
305
+ Logs:
306
+ - An error if the server disconnect fails.
307
+ """
308
+ if server_name not in self._server_connections:
309
+ return
310
+ try:
311
+ await self._server_connections[server_name].close()
312
+ del self._server_connections[server_name]
313
+ except Exception as e:
314
+ structlogger.error(
315
+ "mcp_agent.disconnect_server.error",
316
+ event_info=f"Failed to disconnect from server `{server_name}`: {e}",
317
+ server_name=server_name,
318
+ agent_name=self._name,
319
+ agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
320
+ )
321
+
322
+ async def disconnect(self) -> None:
323
+ """Close all MCP server connections."""
324
+ server_names = list(self._server_connections.keys())
325
+ for server_name in server_names:
326
+ await self.disconnect_server(server_name)
327
+
328
+ # ============================================================================
329
+ # Tool Management
330
+ # ============================================================================
331
+
332
+ async def list_tools(self, connection: MCPServerConnection) -> ListToolsResult:
333
+ """List the tools from the MCP server."""
334
+ session = await connection.ensure_active_session()
335
+ return await session.list_tools()
336
+
337
+ @classmethod
338
+ def get_built_in_tools(cls, agent_input: AgentInput) -> List[AgentToolSchema]:
339
+ """Get built-in tools that are always available for MCP agents."""
340
+ built_in_tools = []
341
+ if agent_specific_built_in_tools := cls.get_agent_specific_built_in_tools(
342
+ agent_input
343
+ ):
344
+ built_in_tools.extend(agent_specific_built_in_tools)
345
+ if additional_tools := cls.get_additional_tools(agent_input):
346
+ built_in_tools.extend(additional_tools)
347
+ return [
348
+ AgentToolSchema.from_openai_json_format(tool) for tool in built_in_tools
349
+ ]
350
+
351
+ def get_available_tools(self, agent_input: AgentInput) -> List[AgentToolSchema]:
352
+ """Get the available tools for the agent."""
353
+ return self._mcp_tools + self.get_built_in_tools(agent_input)
354
+
355
+ async def _get_filtered_tools_from_server(
356
+ self,
357
+ server_name: str,
358
+ connection: MCPServerConnection,
359
+ include_tools: Optional[List[str]] = None,
360
+ exclude_tools: Optional[List[str]] = None,
361
+ ) -> List[AgentToolSchema]:
362
+ """Get filtered tools from the MCP server.
363
+
364
+ This method fetches the available tools from the MCP server and filters them
365
+ based on the include_tools and exclude_tools parameters.
366
+
367
+ Args:
368
+ server_name: The name of the MCP server.
369
+ connection: The MCP server connection.
370
+ include_tools: List of tool names to include. If provided, only tools in
371
+ this list will be fetched.
372
+ exclude_tools: List of tool names to exclude. If provided, tools in this
373
+ list will not be fetched.
374
+
375
+ Returns:
376
+ A list of AgentToolSchema objects representing the filtered tools.
377
+
378
+ Logs:
379
+ Warning: If there is a duplicate tool name across servers.
380
+ Warning: If there is an error fetching tools from the server.
381
+ """
382
+ try:
383
+ tools_response = await self.list_tools(connection)
384
+ if not tools_response:
385
+ return []
386
+
387
+ filtered_tools = []
388
+ for tool in tools_response.tools:
389
+ if include_tools and tool.name not in include_tools:
390
+ continue
391
+ if exclude_tools and tool.name in exclude_tools:
392
+ continue
393
+ filtered_tools.append(AgentToolSchema.from_mcp_tool(tool))
394
+
395
+ return filtered_tools
396
+
397
+ except Exception as e:
398
+ event_info = f"Failed to load tools from {server_name}"
399
+ structlogger.warning(
400
+ "mcp_agent.get_filtered_tools_from_server.failed_to_get_tools",
401
+ event_info=event_info,
402
+ server_name=server_name,
403
+ server_url=connection.server_url,
404
+ error=str(e),
405
+ )
406
+ return []
407
+
408
+ def _get_include_exclude_tools_from_server_configs(
409
+ self, server_name: str
410
+ ) -> Tuple[Optional[List[str]], Optional[List[str]]]:
411
+ """Get the include and exclude tools from the server configs."""
412
+ for server_config in self._server_configs:
413
+ if server_config.name == server_name:
414
+ return server_config.include_tools, server_config.exclude_tools
415
+ return None, None
416
+
417
+ async def fetch_and_store_available_tools(self) -> None:
418
+ """Fetch and store the available tools from the MCP servers.
419
+
420
+ This method fetches the available tools from the MCP servers and stores them
421
+ in the agent's internal state. It also maps the tool names to the MCP servers
422
+ that provide them.
423
+
424
+ Side effects:
425
+ - Updates the `_mcp_tools` attribute.
426
+ - Updates the `_tool_to_server_mapper` attribute.
427
+
428
+ Logs:
429
+ Warning: If there is a duplicate tool name across servers.
430
+ Warning: If there is an error fetching tools from any server.
431
+ """
432
+ for server_name, connection in self._server_connections.items():
433
+ # Get the include and exclude tools from the server configs.
434
+ include_tools, exclude_tools = (
435
+ self._get_include_exclude_tools_from_server_configs(server_name)
436
+ )
437
+
438
+ # Get the filtered tools from the server.
439
+ tools = await self._get_filtered_tools_from_server(
440
+ server_name, connection, include_tools, exclude_tools
441
+ )
442
+
443
+ # Add the tools to the tool_to_server_mapper and the available_tools.
444
+ for tool in tools:
445
+ if tool.name in self._tool_to_server_mapper:
446
+ structlogger.warning(
447
+ "mcp_agent.duplicate_tool_name",
448
+ event_info=(
449
+ f"Tool - {tool.name} from server {server_name} already "
450
+ f"exists in {self._tool_to_server_mapper[tool.name]}. "
451
+ f"Omitting the tool from server {server_name}."
452
+ ),
453
+ tool_name=tool.name,
454
+ server_name=server_name,
455
+ server_url=connection.server_url,
456
+ )
457
+ continue
458
+
459
+ self._tool_to_server_mapper[tool.name] = server_name
460
+ self._mcp_tools.append(tool)
461
+
462
+ structlogger.debug(
463
+ "mcp_agent.fetch_and_store_available_tools.success",
464
+ event_info=(
465
+ "Successfully fetched and stored available tools from MCP servers."
466
+ ),
467
+ agent_name=self._name,
468
+ agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
469
+ mcp_tools_fetched=len(self._mcp_tools),
470
+ mcp_tools=[tool.name for tool in self._mcp_tools],
471
+ )
472
+
473
+ # ============================================================================
474
+ # LLM & Prompt Management
475
+ # ============================================================================
476
+
477
+ def render_prompt_template(self, context: AgentInput) -> str:
478
+ """Render the prompt template with the provided inputs."""
479
+ return Template(self.prompt_template).render(
480
+ **context.model_dump(exclude={"id", "timestamp", "events"}),
481
+ description=self._description,
482
+ )
483
+
484
+ def build_messages_for_llm_request(
485
+ self, context: AgentInput, turns: int = 20
486
+ ) -> List[Dict[str, str]]:
487
+ """Build messages for the LLM request."""
488
+ messages = [
489
+ {KEY_ROLE: ROLE_SYSTEM, KEY_CONTENT: self.render_prompt_template(context)}
490
+ ]
491
+
492
+ # Limit to last N events - set by `turns`.
493
+ for event in context.events[-turns:]:
494
+ if isinstance(event, UserUttered):
495
+ if not event.text:
496
+ continue
497
+ messages.append({KEY_ROLE: ROLE_USER, KEY_CONTENT: event.text})
498
+ elif isinstance(event, BotUttered):
499
+ if not event.text:
500
+ continue
501
+ messages.append({KEY_ROLE: ROLE_ASSISTANT, KEY_CONTENT: event.text})
502
+
503
+ if context.user_message != messages[-1][KEY_CONTENT]:
504
+ messages.append({KEY_ROLE: ROLE_USER, KEY_CONTENT: context.user_message})
505
+ return messages
506
+
507
+ def _get_assistant_message_with_tool_calls(
508
+ self, llm_response: LLMResponse
509
+ ) -> Dict[str, Any]:
510
+ """Get assistant message with tool calls."""
511
+ if not llm_response.tool_calls:
512
+ return {}
513
+ return {
514
+ KEY_ROLE: ROLE_ASSISTANT,
515
+ KEY_CONTENT: llm_response.choices[0],
516
+ KEY_TOOL_CALLS: [
517
+ {
518
+ KEY_ID: tool_call.id,
519
+ KEY_TYPE: tool_call.type,
520
+ KEY_FUNCTION: {
521
+ KEY_NAME: tool_call.tool_name,
522
+ KEY_ARGUMENTS: json.dumps(tool_call.tool_args),
523
+ },
524
+ }
525
+ for tool_call in llm_response.tool_calls
526
+ ],
527
+ }
528
+
529
+ def _get_tool_call_message(self, tool_response: AgentOutput) -> Dict[str, Any]:
530
+ """Get the tool call message."""
531
+ return {
532
+ KEY_ROLE: ROLE_TOOL,
533
+ KEY_TOOL_CALL_ID: tool_response.id,
534
+ KEY_CONTENT: tool_response.response_message,
535
+ }
536
+
537
+ # ============================================================================
538
+ # Tool Execution
539
+ # ============================================================================
540
+
541
+ async def _execute_mcp_tool(
542
+ self, tool_name: str, arguments: Dict[str, Any]
543
+ ) -> AgentToolResult:
544
+ """Execute a tool call via MCP servers."""
545
+ if tool_name not in self._tool_to_server_mapper:
546
+ return AgentToolResult(
547
+ tool_name=tool_name,
548
+ result=None,
549
+ is_error=True,
550
+ error_message=f"Tool `{tool_name}` not found in the server.",
551
+ )
552
+
553
+ server_id = self._tool_to_server_mapper[tool_name]
554
+ connection = self._server_connections[server_id]
555
+ session = await connection.ensure_active_session()
556
+ try:
557
+ result = await session.call_tool(tool_name, arguments)
558
+ return AgentToolResult.from_mcp_tool_result(tool_name, result)
559
+ except Exception as e:
560
+ return AgentToolResult(
561
+ tool_name=tool_name,
562
+ result=None,
563
+ is_error=True,
564
+ error_message=(
565
+ f"Failed to execute tool `{tool_name}` via MCP server `{server_id}`"
566
+ f"@ {connection.server_url}: {e}"
567
+ ),
568
+ )
569
+
570
+ async def execute_additional_tool(
571
+ self, tool_name: str, arguments: Dict[str, Any]
572
+ ) -> Optional[AgentToolResult]:
573
+ """Execute additional tool. Override to add logic for specific tool.
574
+
575
+ Args:
576
+ tool_name: The name of the tool to execute.
577
+ arguments: The arguments to pass to the tool.
578
+
579
+ Returns:
580
+ The result of the tool execution as an AgentOutput object.
581
+
582
+ Example:
583
+ ```python
584
+ async def execute_additional_tool(
585
+ self, tool_name: str, arguments: Dict[str, Any]
586
+ ) -> Optional[AgentToolResult]:
587
+ if tool_name == "get_location":
588
+ return get_location_tool(arguments)
589
+ elif tool_name == "get_current_weather":
590
+ return get_current_weather_tool(arguments)
591
+ return None
592
+
593
+ ```
594
+ """
595
+ return None
596
+
597
+ async def _execute_tool_call(
598
+ self, tool_name: str, arguments: Dict[str, Any]
599
+ ) -> AgentToolResult:
600
+ """Execute a tool call.
601
+
602
+ This method first checks if the tool is a built-in tool. If it is, it executes
603
+ the built-in tool. If it is not, it executes the tool via MCP servers.
604
+
605
+ Args:
606
+ tool_name: The name of the tool to execute.
607
+ arguments: The arguments to pass to the tool.
608
+
609
+ Returns:
610
+ The result of the tool execution as an AgentToolResult object.
611
+ """
612
+ try:
613
+ if additional_tool_result := await self.execute_additional_tool(
614
+ tool_name, arguments
615
+ ):
616
+ return additional_tool_result
617
+ except Exception as e:
618
+ return AgentToolResult(
619
+ tool_name=tool_name,
620
+ result=None,
621
+ is_error=True,
622
+ error_message=f"Failed to execute built-in tool `{tool_name}`: {e}",
623
+ )
624
+ return await self._execute_mcp_tool(tool_name, arguments)
625
+
626
+ def _generate_agent_error_output(
627
+ self,
628
+ tool_output: AgentToolResult,
629
+ agent_input: AgentInput,
630
+ tool_call: LLMToolCall,
631
+ ) -> AgentOutput:
632
+ """Generate an agent error output."""
633
+ structlogger.error(
634
+ "mcp_agent.send_message.tool_execution_error",
635
+ event_info=(
636
+ f"Tool `{tool_output.tool_name}` returned an error: "
637
+ f"{tool_output.error_message}"
638
+ ),
639
+ tool_name=tool_output.tool_name,
640
+ tool_args=json.dumps(tool_call.tool_args),
641
+ )
642
+ if tool_output.is_error:
643
+ return AgentOutput(
644
+ id=agent_input.id,
645
+ status=AgentStatus.FATAL_ERROR,
646
+ error_message=tool_output.error_message,
647
+ )
648
+ else:
649
+ return AgentOutput(
650
+ id=agent_input.id,
651
+ status=AgentStatus.RECOVERABLE_ERROR,
652
+ error_message=tool_output.error_message,
653
+ )
654
+
655
+ def _get_tool_results_for_agent_output(
656
+ self,
657
+ agent_input: AgentInput,
658
+ current_tool_results: Dict[str, AgentToolResult],
659
+ ) -> List[List[Dict[str, Any]]]:
660
+ """Get the tool results for the agent output."""
661
+ tool_results_of_current_iteration: List[Dict[str, Any]] = []
662
+ for tool_result in current_tool_results.values():
663
+ tool_results_of_current_iteration.append(
664
+ {"tool_name": tool_result.tool_name, "result": tool_result.result}
665
+ )
666
+
667
+ previous_tool_results: List[List[Dict[str, Any]]] = (
668
+ agent_input.metadata.get(AGENT_METADATA_TOOL_RESULTS_KEY, []) or []
669
+ )
670
+ previous_tool_results.append(tool_results_of_current_iteration)
671
+
672
+ return previous_tool_results
673
+
674
+ # ============================================================================
675
+ # Core Protocol Methods
676
+ # ============================================================================
677
+
678
+ @abstractmethod
679
+ async def send_message(self, agent_input: AgentInput) -> AgentOutput:
680
+ """Send a message to the agent."""
681
+ ...
682
+
683
+ async def run(self, input: AgentInput) -> AgentOutput:
684
+ """Send a message to Agent/server and return response."""
685
+ return await self.send_message(input)
686
+
687
+ # ============================================================================
688
+ # Message Processing
689
+ # ============================================================================
690
+
691
+ async def process_input(self, input: AgentInput) -> AgentInput:
692
+ """Pre-process the input before sending it to the agent."""
693
+ return input
694
+
695
+ async def process_output(self, output: AgentOutput) -> AgentOutput:
696
+ """Post-process the output before returning it to Rasa."""
697
+ return output