rasa-pro 3.14.0.dev20250922__py3-none-any.whl → 3.14.0rc2__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.
- rasa/__main__.py +15 -3
- rasa/agents/__init__.py +0 -0
- rasa/agents/agent_factory.py +122 -0
- rasa/agents/agent_manager.py +211 -0
- rasa/agents/constants.py +43 -0
- rasa/agents/core/__init__.py +0 -0
- rasa/agents/core/agent_protocol.py +107 -0
- rasa/agents/core/types.py +81 -0
- rasa/agents/exceptions.py +38 -0
- rasa/agents/protocol/__init__.py +5 -0
- rasa/agents/protocol/a2a/__init__.py +0 -0
- rasa/agents/protocol/a2a/a2a_agent.py +879 -0
- rasa/agents/protocol/mcp/__init__.py +0 -0
- rasa/agents/protocol/mcp/mcp_base_agent.py +726 -0
- rasa/agents/protocol/mcp/mcp_open_agent.py +327 -0
- rasa/agents/protocol/mcp/mcp_task_agent.py +522 -0
- rasa/agents/schemas/__init__.py +13 -0
- rasa/agents/schemas/agent_input.py +38 -0
- rasa/agents/schemas/agent_output.py +26 -0
- rasa/agents/schemas/agent_tool_result.py +65 -0
- rasa/agents/schemas/agent_tool_schema.py +186 -0
- rasa/agents/templates/__init__.py +0 -0
- rasa/agents/templates/mcp_open_agent_prompt_template.jinja2 +20 -0
- rasa/agents/templates/mcp_task_agent_prompt_template.jinja2 +22 -0
- rasa/agents/utils.py +206 -0
- rasa/agents/validation.py +485 -0
- rasa/api.py +24 -9
- rasa/builder/config.py +6 -2
- rasa/builder/copilot/constants.py +4 -1
- rasa/builder/copilot/copilot.py +155 -79
- rasa/builder/copilot/models.py +304 -108
- rasa/builder/copilot/prompts/copilot_training_error_handler_prompt.jinja2 +53 -0
- rasa/builder/guardrails/{lakera.py → clients.py} +55 -5
- rasa/builder/guardrails/constants.py +3 -0
- rasa/builder/guardrails/models.py +45 -10
- rasa/builder/guardrails/policy_checker.py +324 -0
- rasa/builder/guardrails/utils.py +42 -276
- rasa/builder/jobs.py +182 -12
- rasa/builder/llm_service.py +32 -5
- rasa/builder/models.py +13 -3
- rasa/builder/project_generator.py +6 -1
- rasa/builder/service.py +31 -15
- rasa/builder/training_service.py +18 -24
- rasa/builder/validation_service.py +1 -1
- rasa/cli/arguments/default_arguments.py +12 -0
- rasa/cli/arguments/run.py +2 -0
- rasa/cli/arguments/train.py +2 -0
- rasa/cli/data.py +10 -8
- rasa/cli/dialogue_understanding_test.py +10 -7
- rasa/cli/e2e_test.py +9 -6
- rasa/cli/evaluate.py +4 -2
- rasa/cli/export.py +5 -2
- rasa/cli/inspect.py +8 -4
- rasa/cli/interactive.py +5 -4
- rasa/cli/llm_fine_tuning.py +11 -6
- rasa/cli/project_templates/finance/domain/general/help.yml +0 -0
- rasa/cli/project_templates/tutorial/credentials.yml +10 -0
- rasa/cli/run.py +12 -10
- rasa/cli/scaffold.py +4 -4
- rasa/cli/shell.py +9 -5
- rasa/cli/studio/studio.py +1 -1
- rasa/cli/test.py +34 -14
- rasa/cli/train.py +41 -28
- rasa/cli/utils.py +1 -393
- rasa/cli/validation/__init__.py +0 -0
- rasa/cli/validation/bot_config.py +223 -0
- rasa/cli/validation/config_path_validation.py +257 -0
- rasa/cli/x.py +8 -4
- rasa/constants.py +7 -1
- rasa/core/actions/action.py +51 -10
- rasa/core/actions/grpc_custom_action_executor.py +1 -1
- rasa/core/agent.py +19 -2
- rasa/core/available_agents.py +229 -0
- rasa/core/brokers/kafka.py +5 -1
- rasa/core/channels/__init__.py +82 -35
- rasa/core/channels/development_inspector.py +3 -3
- rasa/core/channels/inspector/README.md +25 -13
- rasa/core/channels/inspector/dist/assets/{arc-35222594.js → arc-6177260a.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{blockDiagram-38ab4fdb-a0efbfd3.js → blockDiagram-38ab4fdb-b054f038.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{c4Diagram-3d4e48cf-0584c0f2.js → c4Diagram-3d4e48cf-f25427d5.js} +1 -1
- rasa/core/channels/inspector/dist/assets/channel-bf9cbb34.js +1 -0
- rasa/core/channels/inspector/dist/assets/{classDiagram-70f12bd4-39f40dbe.js → classDiagram-70f12bd4-c7a2af53.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{classDiagram-v2-f2320105-1ad755f3.js → classDiagram-v2-f2320105-58db65c0.js} +1 -1
- rasa/core/channels/inspector/dist/assets/clone-8f9083bb.js +1 -0
- rasa/core/channels/inspector/dist/assets/{createText-2e5e7dd3-b0f4f0fe.js → createText-2e5e7dd3-088372e2.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{edges-e0da2a9e-9039bff9.js → edges-e0da2a9e-58676240.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{erDiagram-9861fffd-65c9b127.js → erDiagram-9861fffd-0c14d7c6.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{flowDb-956e92f1-4f08b38e.js → flowDb-956e92f1-ea63f85c.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{flowDiagram-66a62f08-e95c362a.js → flowDiagram-66a62f08-a2af48cd.js} +1 -1
- rasa/core/channels/inspector/dist/assets/flowDiagram-v2-96b9c2cf-9ecd5b59.js +1 -0
- rasa/core/channels/inspector/dist/assets/{flowchart-elk-definition-4a651766-703c3015.js → flowchart-elk-definition-4a651766-6937abe7.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{ganttDiagram-c361ad54-699328ea.js → ganttDiagram-c361ad54-7473f357.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{gitGraphDiagram-72cf32ee-04cf4b05.js → gitGraphDiagram-72cf32ee-d0c9405e.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{graph-ee94449e.js → graph-0a6f8466.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{index-3862675e-940162b4.js → index-3862675e-7610671a.js} +1 -1
- rasa/core/channels/inspector/dist/assets/index-74e01d94.js +1354 -0
- rasa/core/channels/inspector/dist/assets/{infoDiagram-f8f76790-c79c2866.js → infoDiagram-f8f76790-be397dc7.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{journeyDiagram-49397b02-84489d30.js → journeyDiagram-49397b02-4cefbf62.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{layout-a9aa9858.js → layout-e7fbc2bf.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{line-eb73cf26.js → line-a8aa457c.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{linear-b3399f9a.js → linear-3351e0d2.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{mindmap-definition-fc14e90a-b095bf1a.js → mindmap-definition-fc14e90a-b8cbf605.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{pieDiagram-8a3498a8-07644b66.js → pieDiagram-8a3498a8-f327f774.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{quadrantDiagram-120e2f19-573a3f9c.js → quadrantDiagram-120e2f19-2854c591.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{requirementDiagram-deff3bca-d457e1e1.js → requirementDiagram-deff3bca-964985d5.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{sankeyDiagram-04a897e0-9d26e1a2.js → sankeyDiagram-04a897e0-edeb4f33.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{sequenceDiagram-704730f1-3a9cde10.js → sequenceDiagram-704730f1-fcf70125.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{stateDiagram-587899a1-4f3e8cec.js → stateDiagram-587899a1-0e770395.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{stateDiagram-v2-d93cdb3a-e617e5bf.js → stateDiagram-v2-d93cdb3a-af8dcd22.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{styles-6aaf32cf-eab30d2f.js → styles-6aaf32cf-36a9e70d.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{styles-9a916d00-09994be2.js → styles-9a916d00-884a8b5b.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{styles-c10674c1-b7110364.js → styles-c10674c1-dc097813.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{svgDrawCommon-08f97a94-3ebc92ad.js → svgDrawCommon-08f97a94-5a2c7eed.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{timeline-definition-85554ec2-7d13d2f2.js → timeline-definition-85554ec2-e89c4f6e.js} +1 -1
- rasa/core/channels/inspector/dist/assets/{xychartDiagram-e933f94c-488385e1.js → xychartDiagram-e933f94c-afb6fe56.js} +1 -1
- rasa/core/channels/inspector/dist/index.html +1 -1
- rasa/core/channels/inspector/package.json +18 -18
- rasa/core/channels/inspector/src/App.tsx +29 -4
- rasa/core/channels/inspector/src/components/DialogueAgentStack.tsx +108 -0
- rasa/core/channels/inspector/src/components/{DialogueStack.tsx → DialogueHistoryStack.tsx} +4 -2
- rasa/core/channels/inspector/src/helpers/audio/audiostream.ts +7 -4
- rasa/core/channels/inspector/src/helpers/formatters.test.ts +4 -0
- rasa/core/channels/inspector/src/helpers/formatters.ts +24 -3
- rasa/core/channels/inspector/src/helpers/utils.test.ts +127 -0
- rasa/core/channels/inspector/src/helpers/utils.ts +66 -1
- rasa/core/channels/inspector/src/theme/base/styles.ts +19 -1
- rasa/core/channels/inspector/src/types.ts +21 -0
- rasa/core/channels/inspector/yarn.lock +336 -189
- rasa/core/channels/studio_chat.py +6 -6
- rasa/core/channels/telegram.py +4 -9
- rasa/core/channels/voice_stream/genesys.py +1 -1
- rasa/core/channels/voice_stream/tts/deepgram.py +140 -0
- rasa/core/channels/voice_stream/twilio_media_streams.py +5 -1
- rasa/core/channels/voice_stream/voice_channel.py +3 -0
- rasa/core/concurrent_lock_store.py +38 -21
- rasa/core/config/__init__.py +0 -0
- rasa/core/{available_endpoints.py → config/available_endpoints.py} +51 -16
- rasa/core/config/configuration.py +260 -0
- rasa/core/config/credentials.py +19 -0
- rasa/core/config/message_procesing_config.py +34 -0
- rasa/core/constants.py +10 -0
- rasa/core/iam_credentials_providers/aws_iam_credentials_providers.py +69 -4
- rasa/core/iam_credentials_providers/credentials_provider_protocol.py +2 -1
- rasa/core/lock_store.py +4 -0
- rasa/core/policies/enterprise_search_policy.py +5 -3
- rasa/core/policies/flow_policy.py +4 -4
- rasa/core/policies/flows/agent_executor.py +632 -0
- rasa/core/policies/flows/flow_executor.py +136 -75
- rasa/core/policies/flows/mcp_tool_executor.py +298 -0
- rasa/core/policies/intentless_policy.py +1 -1
- rasa/core/policies/ted_policy.py +20 -12
- rasa/core/policies/unexpected_intent_policy.py +6 -0
- rasa/core/processor.py +68 -44
- rasa/core/redis_connection_factory.py +7 -2
- rasa/core/run.py +37 -8
- rasa/core/test.py +4 -0
- rasa/core/tracker_stores/redis_tracker_store.py +4 -0
- rasa/core/tracker_stores/sql_tracker_store.py +3 -1
- rasa/core/tracker_stores/tracker_store.py +3 -7
- rasa/core/train.py +1 -1
- rasa/core/training/interactive.py +20 -18
- rasa/core/training/story_conflict.py +5 -5
- rasa/core/utils.py +22 -23
- rasa/dialogue_understanding/commands/__init__.py +8 -0
- rasa/dialogue_understanding/commands/cancel_flow_command.py +19 -5
- rasa/dialogue_understanding/commands/chit_chat_answer_command.py +21 -2
- rasa/dialogue_understanding/commands/clarify_command.py +20 -2
- rasa/dialogue_understanding/commands/continue_agent_command.py +91 -0
- rasa/dialogue_understanding/commands/knowledge_answer_command.py +21 -2
- rasa/dialogue_understanding/commands/restart_agent_command.py +162 -0
- rasa/dialogue_understanding/commands/start_flow_command.py +68 -7
- rasa/dialogue_understanding/commands/utils.py +124 -2
- rasa/dialogue_understanding/generator/command_parser.py +4 -0
- rasa/dialogue_understanding/generator/llm_based_command_generator.py +50 -12
- rasa/dialogue_understanding/generator/llm_command_generator.py +1 -1
- rasa/dialogue_understanding/generator/multi_step/multi_step_llm_command_generator.py +1 -1
- rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v2_claude_3_5_sonnet_20240620_template.jinja2 +66 -0
- rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v2_gpt_4o_2024_11_20_template.jinja2 +66 -0
- rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v3_claude_3_5_sonnet_20240620_template.jinja2 +89 -0
- rasa/dialogue_understanding/generator/prompt_templates/agent_command_prompt_v3_gpt_4o_2024_11_20_template.jinja2 +88 -0
- rasa/dialogue_understanding/generator/single_step/compact_llm_command_generator.py +42 -7
- rasa/dialogue_understanding/generator/single_step/search_ready_llm_command_generator.py +40 -3
- rasa/dialogue_understanding/generator/single_step/single_step_based_llm_command_generator.py +20 -3
- rasa/dialogue_understanding/patterns/cancel.py +27 -6
- rasa/dialogue_understanding/patterns/clarify.py +3 -14
- rasa/dialogue_understanding/patterns/continue_interrupted.py +239 -6
- rasa/dialogue_understanding/patterns/default_flows_for_patterns.yml +46 -8
- rasa/dialogue_understanding/processor/command_processor.py +136 -15
- rasa/dialogue_understanding/stack/dialogue_stack.py +98 -2
- rasa/dialogue_understanding/stack/frames/flow_stack_frame.py +57 -0
- rasa/dialogue_understanding/stack/utils.py +57 -3
- rasa/dialogue_understanding/utils.py +24 -4
- rasa/dialogue_understanding_test/du_test_runner.py +8 -3
- rasa/e2e_test/e2e_test_runner.py +13 -3
- rasa/engine/caching.py +2 -2
- rasa/engine/constants.py +1 -1
- rasa/engine/recipes/default_components.py +138 -49
- rasa/engine/recipes/default_recipe.py +108 -11
- rasa/engine/runner/dask.py +8 -5
- rasa/engine/validation.py +19 -6
- rasa/graph_components/validators/default_recipe_validator.py +86 -28
- rasa/hooks.py +5 -5
- rasa/llm_fine_tuning/utils.py +2 -2
- rasa/model_training.py +60 -47
- rasa/nlu/classifiers/diet_classifier.py +198 -98
- rasa/nlu/classifiers/logistic_regression_classifier.py +1 -4
- rasa/nlu/classifiers/mitie_intent_classifier.py +3 -0
- rasa/nlu/classifiers/sklearn_intent_classifier.py +1 -3
- rasa/nlu/extractors/crf_entity_extractor.py +9 -10
- rasa/nlu/extractors/mitie_entity_extractor.py +3 -0
- rasa/nlu/extractors/spacy_entity_extractor.py +3 -0
- rasa/nlu/featurizers/dense_featurizer/convert_featurizer.py +4 -0
- rasa/nlu/featurizers/dense_featurizer/lm_featurizer.py +5 -0
- rasa/nlu/featurizers/dense_featurizer/mitie_featurizer.py +2 -0
- rasa/nlu/featurizers/dense_featurizer/spacy_featurizer.py +3 -0
- rasa/nlu/featurizers/sparse_featurizer/count_vectors_featurizer.py +4 -2
- rasa/nlu/featurizers/sparse_featurizer/lexical_syntactic_featurizer.py +4 -0
- rasa/nlu/selectors/response_selector.py +10 -2
- rasa/nlu/tokenizers/jieba_tokenizer.py +3 -4
- rasa/nlu/tokenizers/mitie_tokenizer.py +3 -2
- rasa/nlu/tokenizers/spacy_tokenizer.py +3 -2
- rasa/nlu/utils/mitie_utils.py +3 -0
- rasa/nlu/utils/spacy_utils.py +3 -2
- rasa/plugin.py +8 -8
- rasa/privacy/privacy_manager.py +12 -3
- rasa/server.py +15 -3
- rasa/shared/agents/__init__.py +0 -0
- rasa/shared/agents/auth/__init__.py +0 -0
- rasa/shared/agents/auth/agent_auth_factory.py +105 -0
- rasa/shared/agents/auth/agent_auth_manager.py +92 -0
- rasa/shared/agents/auth/auth_strategy/__init__.py +19 -0
- rasa/shared/agents/auth/auth_strategy/agent_auth_strategy.py +52 -0
- rasa/shared/agents/auth/auth_strategy/api_key_auth_strategy.py +42 -0
- rasa/shared/agents/auth/auth_strategy/bearer_token_auth_strategy.py +28 -0
- rasa/shared/agents/auth/auth_strategy/oauth2_auth_strategy.py +167 -0
- rasa/shared/agents/auth/constants.py +12 -0
- rasa/shared/agents/auth/types.py +12 -0
- rasa/shared/agents/utils.py +35 -0
- rasa/shared/constants.py +8 -0
- rasa/shared/core/constants.py +16 -1
- rasa/shared/core/domain.py +0 -7
- rasa/shared/core/events.py +327 -0
- rasa/shared/core/flows/constants.py +5 -0
- rasa/shared/core/flows/flows_list.py +21 -5
- rasa/shared/core/flows/flows_yaml_schema.json +119 -184
- rasa/shared/core/flows/steps/call.py +49 -5
- rasa/shared/core/flows/steps/collect.py +98 -13
- rasa/shared/core/flows/validation.py +372 -8
- rasa/shared/core/flows/yaml_flows_io.py +3 -2
- rasa/shared/core/slots.py +2 -2
- rasa/shared/core/trackers.py +5 -2
- rasa/shared/exceptions.py +16 -0
- rasa/shared/importers/rasa.py +1 -1
- rasa/shared/importers/utils.py +9 -3
- rasa/shared/providers/llm/_base_litellm_client.py +41 -9
- rasa/shared/providers/llm/litellm_router_llm_client.py +8 -4
- rasa/shared/providers/llm/llm_client.py +7 -3
- rasa/shared/providers/llm/llm_response.py +66 -0
- rasa/shared/providers/llm/self_hosted_llm_client.py +8 -4
- rasa/shared/utils/common.py +24 -0
- rasa/shared/utils/health_check/health_check.py +7 -3
- rasa/shared/utils/llm.py +39 -16
- rasa/shared/utils/mcp/__init__.py +0 -0
- rasa/shared/utils/mcp/server_connection.py +247 -0
- rasa/shared/utils/mcp/utils.py +20 -0
- rasa/shared/utils/schemas/events.py +42 -0
- rasa/shared/utils/yaml.py +3 -1
- rasa/studio/pull/pull.py +3 -2
- rasa/studio/train.py +8 -7
- rasa/studio/upload.py +3 -6
- rasa/telemetry.py +69 -5
- rasa/tracing/config.py +45 -12
- rasa/tracing/constants.py +14 -0
- rasa/tracing/instrumentation/attribute_extractors.py +142 -9
- rasa/tracing/instrumentation/instrumentation.py +626 -21
- rasa/tracing/instrumentation/intentless_policy_instrumentation.py +4 -4
- rasa/tracing/instrumentation/metrics.py +32 -0
- rasa/tracing/metric_instrument_provider.py +68 -0
- rasa/utils/common.py +92 -1
- rasa/utils/endpoints.py +11 -2
- rasa/utils/log_utils.py +96 -5
- rasa/utils/ml_utils.py +1 -1
- rasa/utils/tensorflow/__init__.py +7 -0
- rasa/utils/tensorflow/callback.py +136 -101
- rasa/utils/tensorflow/crf.py +1 -1
- rasa/utils/tensorflow/data_generator.py +21 -8
- rasa/utils/tensorflow/layers.py +21 -11
- rasa/utils/tensorflow/metrics.py +7 -3
- rasa/utils/tensorflow/models.py +56 -8
- rasa/utils/tensorflow/rasa_layers.py +8 -6
- rasa/utils/tensorflow/transformer.py +2 -3
- rasa/utils/train_utils.py +54 -24
- rasa/validator.py +5 -5
- rasa/version.py +1 -1
- {rasa_pro-3.14.0.dev20250922.dist-info → rasa_pro-3.14.0rc2.dist-info}/METADATA +47 -41
- {rasa_pro-3.14.0.dev20250922.dist-info → rasa_pro-3.14.0rc2.dist-info}/RECORD +299 -238
- rasa/builder/scrape_rasa_docs.py +0 -97
- rasa/core/channels/inspector/dist/assets/channel-8e08bed9.js +0 -1
- rasa/core/channels/inspector/dist/assets/clone-78c82dea.js +0 -1
- rasa/core/channels/inspector/dist/assets/flowDiagram-v2-96b9c2cf-2b08f601.js +0 -1
- rasa/core/channels/inspector/dist/assets/index-c941dcb3.js +0 -1336
- {rasa_pro-3.14.0.dev20250922.dist-info → rasa_pro-3.14.0rc2.dist-info}/NOTICE +0 -0
- {rasa_pro-3.14.0.dev20250922.dist-info → rasa_pro-3.14.0rc2.dist-info}/WHEEL +0 -0
- {rasa_pro-3.14.0.dev20250922.dist-info → rasa_pro-3.14.0rc2.dist-info}/entry_points.txt +0 -0
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from inspect import isawaitable
|
|
5
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
import structlog
|
|
8
|
+
from jinja2 import Template
|
|
9
|
+
from mcp import ListToolsResult
|
|
10
|
+
|
|
11
|
+
from rasa.agents.constants import (
|
|
12
|
+
AGENT_DEFAULT_MAX_RETRIES,
|
|
13
|
+
AGENT_DEFAULT_TIMEOUT_SECONDS,
|
|
14
|
+
AGENT_METADATA_STRUCTURED_RESULTS_KEY,
|
|
15
|
+
KEY_ARGUMENTS,
|
|
16
|
+
KEY_CONTENT,
|
|
17
|
+
KEY_FUNCTION,
|
|
18
|
+
KEY_ID,
|
|
19
|
+
KEY_NAME,
|
|
20
|
+
KEY_ROLE,
|
|
21
|
+
KEY_TOOL_CALL_ID,
|
|
22
|
+
KEY_TOOL_CALLS,
|
|
23
|
+
KEY_TYPE,
|
|
24
|
+
)
|
|
25
|
+
from rasa.agents.core.agent_protocol import AgentProtocol
|
|
26
|
+
from rasa.agents.core.types import AgentStatus, ProtocolType
|
|
27
|
+
from rasa.agents.schemas import (
|
|
28
|
+
AgentInput,
|
|
29
|
+
AgentOutput,
|
|
30
|
+
AgentToolResult,
|
|
31
|
+
AgentToolSchema,
|
|
32
|
+
CustomToolSchema,
|
|
33
|
+
)
|
|
34
|
+
from rasa.core.available_agents import AgentConfig, AgentMCPServerConfig, ProtocolConfig
|
|
35
|
+
from rasa.shared.agents.utils import make_agent_identifier
|
|
36
|
+
from rasa.shared.constants import (
|
|
37
|
+
MAX_COMPLETION_TOKENS_CONFIG_KEY,
|
|
38
|
+
MODEL_CONFIG_KEY,
|
|
39
|
+
OPENAI_PROVIDER,
|
|
40
|
+
PROVIDER_CONFIG_KEY,
|
|
41
|
+
ROLE_ASSISTANT,
|
|
42
|
+
ROLE_SYSTEM,
|
|
43
|
+
ROLE_TOOL,
|
|
44
|
+
ROLE_USER,
|
|
45
|
+
TEMPERATURE_CONFIG_KEY,
|
|
46
|
+
TIMEOUT_CONFIG_KEY,
|
|
47
|
+
)
|
|
48
|
+
from rasa.shared.core.events import BotUttered, UserUttered
|
|
49
|
+
from rasa.shared.exceptions import AgentInitializationException, AuthenticationError
|
|
50
|
+
from rasa.shared.providers.llm.llm_response import LLMResponse, LLMToolCall
|
|
51
|
+
from rasa.shared.utils.constants import LOG_COMPONENT_SOURCE_METHOD_INIT
|
|
52
|
+
from rasa.shared.utils.llm import (
|
|
53
|
+
get_prompt_template,
|
|
54
|
+
llm_factory,
|
|
55
|
+
resolve_model_client_config,
|
|
56
|
+
)
|
|
57
|
+
from rasa.shared.utils.mcp.server_connection import MCPServerConnection
|
|
58
|
+
|
|
59
|
+
DEFAULT_OPENAI_MAX_GENERATED_TOKENS = 256
|
|
60
|
+
MODEL_NAME_GPT_4O_2024_11_20 = "gpt-4o-2024-11-20"
|
|
61
|
+
DEFAULT_LLM_CONFIG = {
|
|
62
|
+
PROVIDER_CONFIG_KEY: OPENAI_PROVIDER,
|
|
63
|
+
MODEL_CONFIG_KEY: MODEL_NAME_GPT_4O_2024_11_20,
|
|
64
|
+
TEMPERATURE_CONFIG_KEY: 0.0,
|
|
65
|
+
MAX_COMPLETION_TOKENS_CONFIG_KEY: DEFAULT_OPENAI_MAX_GENERATED_TOKENS,
|
|
66
|
+
TIMEOUT_CONFIG_KEY: 7,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
structlogger = structlog.get_logger()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class MCPBaseAgent(AgentProtocol):
|
|
74
|
+
"""MCP protocol implementation"""
|
|
75
|
+
|
|
76
|
+
MAX_ITERATIONS = 10
|
|
77
|
+
|
|
78
|
+
# ============================================================================
|
|
79
|
+
# Initialization & Setup
|
|
80
|
+
# ============================================================================
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
name: str,
|
|
85
|
+
description: str,
|
|
86
|
+
protocol_type: ProtocolConfig,
|
|
87
|
+
server_configs: List[AgentMCPServerConfig],
|
|
88
|
+
llm_config: Optional[Dict[str, Any]] = None,
|
|
89
|
+
prompt_template: Optional[str] = None,
|
|
90
|
+
timeout: Optional[int] = None,
|
|
91
|
+
max_retries: Optional[int] = None,
|
|
92
|
+
):
|
|
93
|
+
self._name = name
|
|
94
|
+
|
|
95
|
+
self._description = description
|
|
96
|
+
|
|
97
|
+
self._protocol_type = protocol_type
|
|
98
|
+
|
|
99
|
+
self._llm_config = resolve_model_client_config(
|
|
100
|
+
llm_config, self.__class__.__name__
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
self.llm_client = llm_factory(self._llm_config, self.get_default_llm_config())
|
|
104
|
+
|
|
105
|
+
self.prompt_template = get_prompt_template(
|
|
106
|
+
prompt_template,
|
|
107
|
+
self.get_default_prompt_template(),
|
|
108
|
+
log_source_component=self.__class__.__name__,
|
|
109
|
+
log_source_method=LOG_COMPONENT_SOURCE_METHOD_INIT,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
self._timeout = timeout or AGENT_DEFAULT_TIMEOUT_SECONDS
|
|
113
|
+
|
|
114
|
+
self._max_retries = max_retries or AGENT_DEFAULT_MAX_RETRIES
|
|
115
|
+
|
|
116
|
+
self._server_configs = server_configs or []
|
|
117
|
+
|
|
118
|
+
# Stores the MCP tools for the agent.
|
|
119
|
+
self._mcp_tools: List[AgentToolSchema] = []
|
|
120
|
+
|
|
121
|
+
# Stores the custom tools for the agent.
|
|
122
|
+
self._custom_tools: List[CustomToolSchema] = [
|
|
123
|
+
CustomToolSchema.from_dict(tool)
|
|
124
|
+
for tool in self.get_custom_tool_definitions()
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# Maps the tool names to the MCP servers that provide them.
|
|
128
|
+
# key: tool name, value: server name.
|
|
129
|
+
self._tool_to_server_mapper: Dict[str, str] = {}
|
|
130
|
+
|
|
131
|
+
# Stores the connections to the MCP servers.
|
|
132
|
+
# key: server name, value: connection object.
|
|
133
|
+
self._server_connections: Dict[str, MCPServerConnection] = {}
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def from_config(cls, config: AgentConfig) -> "MCPBaseAgent":
|
|
137
|
+
"""Initialize the MCP Open Agent with the given configuration."""
|
|
138
|
+
return cls(
|
|
139
|
+
name=config.agent.name,
|
|
140
|
+
description=config.agent.description,
|
|
141
|
+
protocol_type=config.agent.protocol,
|
|
142
|
+
llm_config=config.configuration.llm if config.configuration else None,
|
|
143
|
+
prompt_template=config.configuration.prompt_template
|
|
144
|
+
if config.configuration
|
|
145
|
+
else None,
|
|
146
|
+
timeout=config.configuration.timeout if config.configuration else None,
|
|
147
|
+
max_retries=config.configuration.max_retries
|
|
148
|
+
if config.configuration
|
|
149
|
+
else None,
|
|
150
|
+
server_configs=config.connections.mcp_servers
|
|
151
|
+
if config.connections
|
|
152
|
+
else None,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# ============================================================================
|
|
156
|
+
# Class Configuration & Properties
|
|
157
|
+
# ============================================================================
|
|
158
|
+
|
|
159
|
+
@classmethod
|
|
160
|
+
@abstractmethod
|
|
161
|
+
def get_default_prompt_template(cls) -> str: ...
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def agent_conforms_to(self) -> ProtocolConfig:
|
|
165
|
+
return self._protocol_type
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
@abstractmethod
|
|
169
|
+
def protocol_type(self) -> ProtocolType: ...
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def get_default_llm_config() -> Dict[str, Any]:
|
|
173
|
+
"""Get the default LLM config for the command generator."""
|
|
174
|
+
return DEFAULT_LLM_CONFIG
|
|
175
|
+
|
|
176
|
+
@classmethod
|
|
177
|
+
def get_agent_specific_built_in_tools(
|
|
178
|
+
cls, agent_input: AgentInput
|
|
179
|
+
) -> List[AgentToolSchema]:
|
|
180
|
+
"""Get agentic specific built-in tools."""
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
def get_custom_tool_definitions(self) -> List[Dict[str, Any]]:
|
|
184
|
+
"""Add custom tool definitions and their executors for MCP agents.
|
|
185
|
+
|
|
186
|
+
This method can be overridden to provide custom tools that the agent
|
|
187
|
+
can use during its operation. Each tool definition follows the LiteLLM JSON
|
|
188
|
+
format and must include:
|
|
189
|
+
- "type": should always be "function" for tools.
|
|
190
|
+
- "function" → the tool metadata (name, description, and parameters).
|
|
191
|
+
- "tool_executor" → a coroutine method that actually performs the tool's action.
|
|
192
|
+
|
|
193
|
+
Refer:
|
|
194
|
+
- LiteLLM JSON Format - https://docs.litellm.ai/docs/completion/function_call#full-code---parallel-function-calling-with-gpt-35-turbo-1106
|
|
195
|
+
- OpenAI Tool JSON Format - https://platform.openai.com/docs/guides/tools?tool-type=function-calling
|
|
196
|
+
|
|
197
|
+
Note:
|
|
198
|
+
- In LiteLLM, the tool metadata is wrapped inside the "function" key.
|
|
199
|
+
- This differs from OpenAI's format, where the metadata (name, description,
|
|
200
|
+
parameters) sits at the top level. Be careful when copying examples from
|
|
201
|
+
OpenAI docs.
|
|
202
|
+
- The tool executor method should be a coroutine function that returns an
|
|
203
|
+
AgentToolResult object.
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
A list of tool definitions paired with their executors.
|
|
207
|
+
|
|
208
|
+
Example:
|
|
209
|
+
```python
|
|
210
|
+
def get_custom_tool_definitions(self) -> List[Dict[str, Any]]:
|
|
211
|
+
return [
|
|
212
|
+
{
|
|
213
|
+
"type": "function",
|
|
214
|
+
"function": {
|
|
215
|
+
"name": "get_current_weather",
|
|
216
|
+
"description": "Get the current weather in given location",
|
|
217
|
+
"parameters": {
|
|
218
|
+
"type": "object",
|
|
219
|
+
"properties": {
|
|
220
|
+
"location": {
|
|
221
|
+
"type": "string",
|
|
222
|
+
"description": "The city, e.g. San Francisco",
|
|
223
|
+
},
|
|
224
|
+
"unit": {
|
|
225
|
+
"type": "string",
|
|
226
|
+
"enum": ["celsius", "fahrenheit"],
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
"required": ["location"],
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
"tool_executor": self.get_current_weather,
|
|
233
|
+
}
|
|
234
|
+
]
|
|
235
|
+
```
|
|
236
|
+
"""
|
|
237
|
+
return []
|
|
238
|
+
|
|
239
|
+
# ============================================================================
|
|
240
|
+
# Connection Management
|
|
241
|
+
# ============================================================================
|
|
242
|
+
|
|
243
|
+
async def connect(self) -> None:
|
|
244
|
+
"""Connect to the MCP servers and initialize the agent.
|
|
245
|
+
|
|
246
|
+
This method establishes connections to the configured MCP servers,
|
|
247
|
+
fetches the available tools, and prepares the agent for operation.
|
|
248
|
+
It should be called before sending any messages to the agent.
|
|
249
|
+
|
|
250
|
+
Retries:
|
|
251
|
+
Retries connection N times if a ConnectionError is raised.
|
|
252
|
+
|
|
253
|
+
Logs:
|
|
254
|
+
Warning: If the connection to any server fails.
|
|
255
|
+
Warning: If there is a duplicate tool name across servers.
|
|
256
|
+
Warning: If there is an error fetching tools from any server.
|
|
257
|
+
"""
|
|
258
|
+
for attempt in range(1, self._max_retries + 1):
|
|
259
|
+
try:
|
|
260
|
+
await self.connect_to_servers()
|
|
261
|
+
await self.fetch_and_store_available_tools()
|
|
262
|
+
break
|
|
263
|
+
except ConnectionError as ce:
|
|
264
|
+
structlogger.warning(
|
|
265
|
+
"mcp_agent.connect.connection_error",
|
|
266
|
+
event_info=f"Connection attempt {attempt} failed.",
|
|
267
|
+
error=str(ce),
|
|
268
|
+
attempt=attempt,
|
|
269
|
+
max_retries=self._max_retries,
|
|
270
|
+
)
|
|
271
|
+
if attempt == self._max_retries:
|
|
272
|
+
structlogger.error(
|
|
273
|
+
"mcp_agent.connect.failed_after_retries",
|
|
274
|
+
event_info="All connection attempts failed.",
|
|
275
|
+
)
|
|
276
|
+
raise AgentInitializationException(
|
|
277
|
+
f"Failed to connect to MCP servers after {self._max_retries} "
|
|
278
|
+
f"attempts. Agent `{self._name}` failed to initialize."
|
|
279
|
+
) from ce
|
|
280
|
+
except (Exception, AuthenticationError) as e:
|
|
281
|
+
if isinstance(e, AuthenticationError):
|
|
282
|
+
event_info = "Authentication error during agent initialization."
|
|
283
|
+
else:
|
|
284
|
+
event_info = "Unexpected error during agent initialization."
|
|
285
|
+
structlogger.error(
|
|
286
|
+
"mcp_agent.connect.unexpected_exception",
|
|
287
|
+
event_info=event_info,
|
|
288
|
+
error=str(e),
|
|
289
|
+
agent_name=self._name,
|
|
290
|
+
agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
|
|
291
|
+
)
|
|
292
|
+
raise AgentInitializationException(e) from e
|
|
293
|
+
|
|
294
|
+
async def connect_to_server(self, server_config: AgentMCPServerConfig) -> None:
|
|
295
|
+
server_name = server_config.name
|
|
296
|
+
connection = MCPServerConnection.from_config(server_config.model_dump())
|
|
297
|
+
try:
|
|
298
|
+
await connection.connect()
|
|
299
|
+
self._server_connections[server_name] = connection
|
|
300
|
+
structlogger.info(
|
|
301
|
+
"mcp_agent.connect_to_server.connected",
|
|
302
|
+
event_info=(
|
|
303
|
+
f"Agent `{self._name}` connected to MCP server - "
|
|
304
|
+
f"`{server_name}` @ `{connection.server_url}`"
|
|
305
|
+
),
|
|
306
|
+
server_id=server_name,
|
|
307
|
+
server_url=connection.server_url,
|
|
308
|
+
agent_name=self._name,
|
|
309
|
+
agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
|
|
310
|
+
)
|
|
311
|
+
except Exception as e:
|
|
312
|
+
event_info = (
|
|
313
|
+
f"Agent `{self._name}` failed to connect to MCP server - "
|
|
314
|
+
f"`{server_name}` @ `{server_config.url}`: {e!s}"
|
|
315
|
+
)
|
|
316
|
+
structlogger.error(
|
|
317
|
+
"mcp_agent.connect.failed_to_connect",
|
|
318
|
+
event_info=event_info,
|
|
319
|
+
server_id=server_name,
|
|
320
|
+
server_url=server_config.url,
|
|
321
|
+
agent_name=self._name,
|
|
322
|
+
agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
|
|
323
|
+
)
|
|
324
|
+
raise e
|
|
325
|
+
|
|
326
|
+
async def connect_to_servers(self) -> None:
|
|
327
|
+
"""Connect to MCP servers."""
|
|
328
|
+
for server_config in self._server_configs:
|
|
329
|
+
await self.connect_to_server(server_config)
|
|
330
|
+
|
|
331
|
+
async def disconnect_server(self, server_name: str) -> None:
|
|
332
|
+
"""Disconnect from an MCP server.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
server_name: The name of the server to disconnect from.
|
|
336
|
+
|
|
337
|
+
Side effects:
|
|
338
|
+
- Removes the server from the server connections.
|
|
339
|
+
|
|
340
|
+
Logs:
|
|
341
|
+
- An error if the server disconnect fails.
|
|
342
|
+
"""
|
|
343
|
+
if server_name not in self._server_connections:
|
|
344
|
+
return
|
|
345
|
+
try:
|
|
346
|
+
await self._server_connections[server_name].close()
|
|
347
|
+
del self._server_connections[server_name]
|
|
348
|
+
except Exception as e:
|
|
349
|
+
structlogger.error(
|
|
350
|
+
"mcp_agent.disconnect_server.error",
|
|
351
|
+
event_info=f"Failed to disconnect from server `{server_name}`: {e!s}",
|
|
352
|
+
server_name=server_name,
|
|
353
|
+
agent_name=self._name,
|
|
354
|
+
agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
async def disconnect(self) -> None:
|
|
358
|
+
"""Close all MCP server connections."""
|
|
359
|
+
server_names = list(self._server_connections.keys())
|
|
360
|
+
for server_name in server_names:
|
|
361
|
+
await self.disconnect_server(server_name)
|
|
362
|
+
|
|
363
|
+
# ============================================================================
|
|
364
|
+
# Tool Management
|
|
365
|
+
# ============================================================================
|
|
366
|
+
|
|
367
|
+
async def list_tools(self, connection: MCPServerConnection) -> ListToolsResult:
|
|
368
|
+
"""List the tools from the MCP server."""
|
|
369
|
+
session = await connection.ensure_active_session()
|
|
370
|
+
return await session.list_tools()
|
|
371
|
+
|
|
372
|
+
def get_custom_tools(self) -> List[AgentToolSchema]:
|
|
373
|
+
"""Get the custom tools for the agent."""
|
|
374
|
+
return [tool.tool_definition for tool in self._custom_tools]
|
|
375
|
+
|
|
376
|
+
def get_available_tools(self, agent_input: AgentInput) -> List[AgentToolSchema]:
|
|
377
|
+
"""Get the available tools for the agent."""
|
|
378
|
+
return (
|
|
379
|
+
self._mcp_tools
|
|
380
|
+
+ self.get_agent_specific_built_in_tools(agent_input)
|
|
381
|
+
+ self.get_custom_tools()
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
async def _get_filtered_tools_from_server(
|
|
385
|
+
self,
|
|
386
|
+
server_name: str,
|
|
387
|
+
connection: MCPServerConnection,
|
|
388
|
+
include_tools: Optional[List[str]] = None,
|
|
389
|
+
exclude_tools: Optional[List[str]] = None,
|
|
390
|
+
) -> List[AgentToolSchema]:
|
|
391
|
+
"""Get filtered tools from the MCP server.
|
|
392
|
+
|
|
393
|
+
This method fetches the available tools from the MCP server and filters them
|
|
394
|
+
based on the include_tools and exclude_tools parameters.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
server_name: The name of the MCP server.
|
|
398
|
+
connection: The MCP server connection.
|
|
399
|
+
include_tools: List of tool names to include. If provided, only tools in
|
|
400
|
+
this list will be fetched.
|
|
401
|
+
exclude_tools: List of tool names to exclude. If provided, tools in this
|
|
402
|
+
list will not be fetched.
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
A list of AgentToolSchema objects representing the filtered tools.
|
|
406
|
+
|
|
407
|
+
Logs:
|
|
408
|
+
Warning: If there is a duplicate tool name across servers.
|
|
409
|
+
Warning: If there is an error fetching tools from the server.
|
|
410
|
+
"""
|
|
411
|
+
try:
|
|
412
|
+
tools_response = await self.list_tools(connection)
|
|
413
|
+
if not tools_response:
|
|
414
|
+
return []
|
|
415
|
+
|
|
416
|
+
filtered_tools = []
|
|
417
|
+
for tool in tools_response.tools:
|
|
418
|
+
if include_tools and tool.name not in include_tools:
|
|
419
|
+
continue
|
|
420
|
+
if exclude_tools and tool.name in exclude_tools:
|
|
421
|
+
continue
|
|
422
|
+
filtered_tools.append(AgentToolSchema.from_mcp_tool(tool))
|
|
423
|
+
|
|
424
|
+
return filtered_tools
|
|
425
|
+
|
|
426
|
+
except Exception as e:
|
|
427
|
+
event_info = f"Failed to load tools from {server_name}"
|
|
428
|
+
structlogger.warning(
|
|
429
|
+
"mcp_agent.get_filtered_tools_from_server.failed_to_get_tools",
|
|
430
|
+
event_info=event_info,
|
|
431
|
+
server_name=server_name,
|
|
432
|
+
server_url=connection.server_url,
|
|
433
|
+
error=str(e),
|
|
434
|
+
)
|
|
435
|
+
return []
|
|
436
|
+
|
|
437
|
+
def _get_include_exclude_tools_from_server_configs(
|
|
438
|
+
self, server_name: str
|
|
439
|
+
) -> Tuple[Optional[List[str]], Optional[List[str]]]:
|
|
440
|
+
"""Get the include and exclude tools from the server configs."""
|
|
441
|
+
for server_config in self._server_configs:
|
|
442
|
+
if server_config.name == server_name:
|
|
443
|
+
return server_config.include_tools, server_config.exclude_tools
|
|
444
|
+
return None, None
|
|
445
|
+
|
|
446
|
+
async def fetch_and_store_available_tools(self) -> None:
|
|
447
|
+
"""Fetch and store the available tools from the MCP servers.
|
|
448
|
+
|
|
449
|
+
This method fetches the available tools from the MCP servers and stores them
|
|
450
|
+
in the agent's internal state. It also maps the tool names to the MCP servers
|
|
451
|
+
that provide them.
|
|
452
|
+
|
|
453
|
+
Side effects:
|
|
454
|
+
- Updates the `_mcp_tools` attribute.
|
|
455
|
+
- Updates the `_tool_to_server_mapper` attribute.
|
|
456
|
+
|
|
457
|
+
Logs:
|
|
458
|
+
Warning: If there is a duplicate tool name across servers.
|
|
459
|
+
Warning: If there is an error fetching tools from any server.
|
|
460
|
+
"""
|
|
461
|
+
for server_name, connection in self._server_connections.items():
|
|
462
|
+
# Get the include and exclude tools from the server configs.
|
|
463
|
+
include_tools, exclude_tools = (
|
|
464
|
+
self._get_include_exclude_tools_from_server_configs(server_name)
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
# Get the filtered tools from the server.
|
|
468
|
+
tools = await self._get_filtered_tools_from_server(
|
|
469
|
+
server_name, connection, include_tools, exclude_tools
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
# Add the tools to the tool_to_server_mapper and the available_tools.
|
|
473
|
+
for tool in tools:
|
|
474
|
+
if tool.name in self._tool_to_server_mapper:
|
|
475
|
+
structlogger.warning(
|
|
476
|
+
"mcp_agent.duplicate_tool_name",
|
|
477
|
+
event_info=(
|
|
478
|
+
f"Tool - {tool.name} from server {server_name} already "
|
|
479
|
+
f"exists in {self._tool_to_server_mapper[tool.name]}. "
|
|
480
|
+
f"Omitting the tool from server {server_name}."
|
|
481
|
+
),
|
|
482
|
+
tool_name=tool.name,
|
|
483
|
+
server_name=server_name,
|
|
484
|
+
server_url=connection.server_url,
|
|
485
|
+
)
|
|
486
|
+
continue
|
|
487
|
+
|
|
488
|
+
self._tool_to_server_mapper[tool.name] = server_name
|
|
489
|
+
self._mcp_tools.append(tool)
|
|
490
|
+
|
|
491
|
+
structlogger.debug(
|
|
492
|
+
"mcp_agent.fetch_and_store_available_tools.success",
|
|
493
|
+
event_info=(
|
|
494
|
+
"Successfully fetched and stored available tools from MCP servers."
|
|
495
|
+
),
|
|
496
|
+
agent_name=self._name,
|
|
497
|
+
agent_id=str(make_agent_identifier(self._name, self.protocol_type)),
|
|
498
|
+
mcp_tools_fetched=len(self._mcp_tools),
|
|
499
|
+
mcp_tools=[tool.name for tool in self._mcp_tools],
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
# ============================================================================
|
|
503
|
+
# LLM & Prompt Management
|
|
504
|
+
# ============================================================================
|
|
505
|
+
|
|
506
|
+
def _get_current_date_time_day(self) -> Tuple[str, str, str]:
|
|
507
|
+
"""Get the current date, time, and day in standard formats."""
|
|
508
|
+
now = datetime.now()
|
|
509
|
+
current_date = now.strftime("%Y-%m-%d") # e.g. 2025-09-14
|
|
510
|
+
current_time = now.strftime("%H:%M:%S") # e.g. 16:45:12
|
|
511
|
+
current_day = now.strftime("%A") # e.g. Sunday
|
|
512
|
+
return current_date, current_time, current_day
|
|
513
|
+
|
|
514
|
+
def render_prompt_template(self, context: AgentInput) -> str:
|
|
515
|
+
"""Render the prompt template with the provided inputs."""
|
|
516
|
+
# Current date, time, and weekday in standard formats
|
|
517
|
+
current_date, current_time, current_day = self._get_current_date_time_day()
|
|
518
|
+
|
|
519
|
+
return Template(self.prompt_template).render(
|
|
520
|
+
**context.model_dump(exclude={"id", "timestamp", "events"}),
|
|
521
|
+
description=self._description,
|
|
522
|
+
current_date=current_date,
|
|
523
|
+
current_time=current_time,
|
|
524
|
+
current_day=current_day,
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
def build_messages_for_llm_request(
|
|
528
|
+
self, context: AgentInput, turns: int = 20
|
|
529
|
+
) -> List[Dict[str, str]]:
|
|
530
|
+
"""Build messages for the LLM request."""
|
|
531
|
+
messages = [
|
|
532
|
+
{KEY_ROLE: ROLE_SYSTEM, KEY_CONTENT: self.render_prompt_template(context)}
|
|
533
|
+
]
|
|
534
|
+
|
|
535
|
+
# Limit to last N events - set by `turns`.
|
|
536
|
+
for event in context.events[-turns:]:
|
|
537
|
+
if isinstance(event, UserUttered):
|
|
538
|
+
if not event.text:
|
|
539
|
+
continue
|
|
540
|
+
messages.append({KEY_ROLE: ROLE_USER, KEY_CONTENT: event.text})
|
|
541
|
+
elif isinstance(event, BotUttered):
|
|
542
|
+
if not event.text:
|
|
543
|
+
continue
|
|
544
|
+
messages.append({KEY_ROLE: ROLE_ASSISTANT, KEY_CONTENT: event.text})
|
|
545
|
+
|
|
546
|
+
if context.user_message != messages[-1][KEY_CONTENT]:
|
|
547
|
+
messages.append({KEY_ROLE: ROLE_USER, KEY_CONTENT: context.user_message})
|
|
548
|
+
return messages
|
|
549
|
+
|
|
550
|
+
def _get_assistant_message_with_tool_calls(
|
|
551
|
+
self, llm_response: LLMResponse
|
|
552
|
+
) -> Dict[str, Any]:
|
|
553
|
+
"""Get assistant message with tool calls."""
|
|
554
|
+
if not llm_response.tool_calls:
|
|
555
|
+
return {}
|
|
556
|
+
return {
|
|
557
|
+
KEY_ROLE: ROLE_ASSISTANT,
|
|
558
|
+
KEY_CONTENT: llm_response.choices[0],
|
|
559
|
+
KEY_TOOL_CALLS: [
|
|
560
|
+
{
|
|
561
|
+
KEY_ID: tool_call.id,
|
|
562
|
+
KEY_TYPE: tool_call.type,
|
|
563
|
+
KEY_FUNCTION: {
|
|
564
|
+
KEY_NAME: tool_call.tool_name,
|
|
565
|
+
KEY_ARGUMENTS: json.dumps(tool_call.tool_args),
|
|
566
|
+
},
|
|
567
|
+
}
|
|
568
|
+
for tool_call in llm_response.tool_calls
|
|
569
|
+
],
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
def _get_tool_call_message(self, tool_response: AgentOutput) -> Dict[str, Any]:
|
|
573
|
+
"""Get the tool call message."""
|
|
574
|
+
return {
|
|
575
|
+
KEY_ROLE: ROLE_TOOL,
|
|
576
|
+
KEY_TOOL_CALL_ID: tool_response.id,
|
|
577
|
+
KEY_CONTENT: tool_response.response_message,
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
def _get_system_message_for_malformed_tool_response(self) -> Dict[str, Any]:
|
|
581
|
+
"""Get the system message for a malformed tool response."""
|
|
582
|
+
system_message = (
|
|
583
|
+
"The previous tool response contained invalid or incomplete JSON and could"
|
|
584
|
+
" not be parsed. Retry by generating a tool response in STRICT JSON string "
|
|
585
|
+
"format only. Ensure the JSON is fully well-formed and corresponds exactly "
|
|
586
|
+
"to the user's last request."
|
|
587
|
+
)
|
|
588
|
+
return {
|
|
589
|
+
KEY_ROLE: ROLE_SYSTEM,
|
|
590
|
+
KEY_CONTENT: system_message,
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
# ============================================================================
|
|
594
|
+
# Tool Execution
|
|
595
|
+
# ============================================================================
|
|
596
|
+
|
|
597
|
+
async def _execute_mcp_tool(
|
|
598
|
+
self, tool_name: str, arguments: Dict[str, Any]
|
|
599
|
+
) -> AgentToolResult:
|
|
600
|
+
"""Execute a tool call via MCP servers."""
|
|
601
|
+
if tool_name not in self._tool_to_server_mapper:
|
|
602
|
+
return AgentToolResult(
|
|
603
|
+
tool_name=tool_name,
|
|
604
|
+
result=None,
|
|
605
|
+
is_error=True,
|
|
606
|
+
error_message=f"Tool `{tool_name}` not found in the server.",
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
server_id = self._tool_to_server_mapper[tool_name]
|
|
610
|
+
connection = self._server_connections[server_id]
|
|
611
|
+
try:
|
|
612
|
+
session = await connection.ensure_active_session()
|
|
613
|
+
result = await session.call_tool(tool_name, arguments)
|
|
614
|
+
return AgentToolResult.from_mcp_tool_result(tool_name, result)
|
|
615
|
+
except Exception as e:
|
|
616
|
+
return AgentToolResult(
|
|
617
|
+
tool_name=tool_name,
|
|
618
|
+
result=None,
|
|
619
|
+
is_error=True,
|
|
620
|
+
error_message=(
|
|
621
|
+
f"Failed to execute tool `{tool_name}` via MCP server `{server_id}`"
|
|
622
|
+
f" @ `{connection.server_url}`: {e!s}"
|
|
623
|
+
),
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
async def _execute_tool_call(
|
|
627
|
+
self, tool_name: str, arguments: Dict[str, Any]
|
|
628
|
+
) -> AgentToolResult:
|
|
629
|
+
"""Execute a tool call.
|
|
630
|
+
|
|
631
|
+
This method first checks if the tool is a built-in tool. If it is, it executes
|
|
632
|
+
the built-in tool. If it is not, it executes the tool via MCP servers.
|
|
633
|
+
|
|
634
|
+
Args:
|
|
635
|
+
tool_name: The name of the tool to execute.
|
|
636
|
+
arguments: The arguments to pass to the tool.
|
|
637
|
+
|
|
638
|
+
Returns:
|
|
639
|
+
The result of the tool execution as an AgentToolResult object.
|
|
640
|
+
"""
|
|
641
|
+
try:
|
|
642
|
+
for custom_tool in self._custom_tools:
|
|
643
|
+
if custom_tool.tool_name == tool_name:
|
|
644
|
+
result = custom_tool.tool_executor(arguments)
|
|
645
|
+
return await result if isawaitable(result) else result
|
|
646
|
+
except Exception as e:
|
|
647
|
+
return AgentToolResult(
|
|
648
|
+
tool_name=tool_name,
|
|
649
|
+
result=None,
|
|
650
|
+
is_error=True,
|
|
651
|
+
error_message=f"Failed to execute built-in tool `{tool_name}`: {e!s}",
|
|
652
|
+
)
|
|
653
|
+
return await self._execute_mcp_tool(tool_name, arguments)
|
|
654
|
+
|
|
655
|
+
def _generate_agent_error_output(
|
|
656
|
+
self,
|
|
657
|
+
tool_output: AgentToolResult,
|
|
658
|
+
agent_input: AgentInput,
|
|
659
|
+
tool_call: LLMToolCall,
|
|
660
|
+
) -> AgentOutput:
|
|
661
|
+
"""Generate an agent error output."""
|
|
662
|
+
structlogger.error(
|
|
663
|
+
"mcp_agent.send_message.tool_execution_error",
|
|
664
|
+
event_info=(
|
|
665
|
+
f"Tool `{tool_output.tool_name}` returned an error: "
|
|
666
|
+
f"{tool_output.error_message}"
|
|
667
|
+
),
|
|
668
|
+
tool_name=tool_output.tool_name,
|
|
669
|
+
tool_args=json.dumps(tool_call.tool_args),
|
|
670
|
+
)
|
|
671
|
+
if tool_output.is_error:
|
|
672
|
+
return AgentOutput(
|
|
673
|
+
id=agent_input.id,
|
|
674
|
+
status=AgentStatus.FATAL_ERROR,
|
|
675
|
+
error_message=tool_output.error_message,
|
|
676
|
+
)
|
|
677
|
+
else:
|
|
678
|
+
return AgentOutput(
|
|
679
|
+
id=agent_input.id,
|
|
680
|
+
status=AgentStatus.RECOVERABLE_ERROR,
|
|
681
|
+
error_message=tool_output.error_message,
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
def _get_structured_results_for_agent_output(
|
|
685
|
+
self,
|
|
686
|
+
agent_input: AgentInput,
|
|
687
|
+
current_tool_results: Dict[str, AgentToolResult],
|
|
688
|
+
) -> List[List[Dict[str, Any]]]:
|
|
689
|
+
"""Get the tool results for the agent output."""
|
|
690
|
+
structured_results_of_current_iteration: List[Dict[str, Any]] = []
|
|
691
|
+
for tool_result in current_tool_results.values():
|
|
692
|
+
structured_results_of_current_iteration.append(
|
|
693
|
+
{"name": tool_result.tool_name, "result": tool_result.result}
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
previous_structured_results: List[List[Dict[str, Any]]] = (
|
|
697
|
+
agent_input.metadata.get(AGENT_METADATA_STRUCTURED_RESULTS_KEY, []) or []
|
|
698
|
+
)
|
|
699
|
+
previous_structured_results.append(structured_results_of_current_iteration)
|
|
700
|
+
|
|
701
|
+
return previous_structured_results
|
|
702
|
+
|
|
703
|
+
# ============================================================================
|
|
704
|
+
# Core Protocol Methods
|
|
705
|
+
# ============================================================================
|
|
706
|
+
|
|
707
|
+
@abstractmethod
|
|
708
|
+
async def send_message(self, agent_input: AgentInput) -> AgentOutput:
|
|
709
|
+
"""Send a message to the agent."""
|
|
710
|
+
...
|
|
711
|
+
|
|
712
|
+
async def run(self, input: AgentInput) -> AgentOutput:
|
|
713
|
+
"""Send a message to Agent/server and return response."""
|
|
714
|
+
return await self.send_message(input)
|
|
715
|
+
|
|
716
|
+
# ============================================================================
|
|
717
|
+
# Message Processing
|
|
718
|
+
# ============================================================================
|
|
719
|
+
|
|
720
|
+
async def process_input(self, input: AgentInput) -> AgentInput:
|
|
721
|
+
"""Pre-process the input before sending it to the agent."""
|
|
722
|
+
return input
|
|
723
|
+
|
|
724
|
+
async def process_output(self, output: AgentOutput) -> AgentOutput:
|
|
725
|
+
"""Post-process the output before returning it to Rasa."""
|
|
726
|
+
return output
|