fast-agent-mcp 0.1.12__py3-none-any.whl → 0.2.0__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.
- {fast_agent_mcp-0.1.12.dist-info → fast_agent_mcp-0.2.0.dist-info}/METADATA +3 -4
- fast_agent_mcp-0.2.0.dist-info/RECORD +123 -0
- mcp_agent/__init__.py +75 -0
- mcp_agent/agents/agent.py +61 -415
- mcp_agent/agents/base_agent.py +522 -0
- mcp_agent/agents/workflow/__init__.py +1 -0
- mcp_agent/agents/workflow/chain_agent.py +173 -0
- mcp_agent/agents/workflow/evaluator_optimizer.py +362 -0
- mcp_agent/agents/workflow/orchestrator_agent.py +591 -0
- mcp_agent/{workflows/orchestrator → agents/workflow}/orchestrator_models.py +11 -21
- mcp_agent/agents/workflow/parallel_agent.py +182 -0
- mcp_agent/agents/workflow/router_agent.py +307 -0
- mcp_agent/app.py +15 -19
- mcp_agent/cli/commands/bootstrap.py +19 -38
- mcp_agent/cli/commands/config.py +4 -4
- mcp_agent/cli/commands/setup.py +7 -14
- mcp_agent/cli/main.py +7 -10
- mcp_agent/cli/terminal.py +3 -3
- mcp_agent/config.py +25 -40
- mcp_agent/context.py +12 -21
- mcp_agent/context_dependent.py +3 -5
- mcp_agent/core/agent_types.py +10 -7
- mcp_agent/core/direct_agent_app.py +179 -0
- mcp_agent/core/direct_decorators.py +443 -0
- mcp_agent/core/direct_factory.py +476 -0
- mcp_agent/core/enhanced_prompt.py +23 -55
- mcp_agent/core/exceptions.py +8 -8
- mcp_agent/core/fastagent.py +145 -371
- mcp_agent/core/interactive_prompt.py +424 -0
- mcp_agent/core/mcp_content.py +17 -17
- mcp_agent/core/prompt.py +6 -9
- mcp_agent/core/request_params.py +6 -3
- mcp_agent/core/validation.py +92 -18
- mcp_agent/executor/decorator_registry.py +9 -17
- mcp_agent/executor/executor.py +8 -17
- mcp_agent/executor/task_registry.py +2 -4
- mcp_agent/executor/temporal.py +19 -41
- mcp_agent/executor/workflow.py +3 -5
- mcp_agent/executor/workflow_signal.py +15 -21
- mcp_agent/human_input/handler.py +4 -7
- mcp_agent/human_input/types.py +2 -3
- mcp_agent/llm/__init__.py +2 -0
- mcp_agent/llm/augmented_llm.py +450 -0
- mcp_agent/llm/augmented_llm_passthrough.py +162 -0
- mcp_agent/llm/augmented_llm_playback.py +83 -0
- mcp_agent/llm/memory.py +103 -0
- mcp_agent/{workflows/llm → llm}/model_factory.py +22 -16
- mcp_agent/{workflows/llm → llm}/prompt_utils.py +1 -3
- mcp_agent/llm/providers/__init__.py +8 -0
- mcp_agent/{workflows/llm → llm/providers}/anthropic_utils.py +8 -25
- mcp_agent/{workflows/llm → llm/providers}/augmented_llm_anthropic.py +56 -194
- mcp_agent/llm/providers/augmented_llm_deepseek.py +53 -0
- mcp_agent/{workflows/llm → llm/providers}/augmented_llm_openai.py +99 -190
- mcp_agent/{workflows/llm → llm}/providers/multipart_converter_anthropic.py +72 -71
- mcp_agent/{workflows/llm → llm}/providers/multipart_converter_openai.py +65 -71
- mcp_agent/{workflows/llm → llm}/providers/openai_multipart.py +16 -44
- mcp_agent/{workflows/llm → llm/providers}/openai_utils.py +4 -4
- mcp_agent/{workflows/llm → llm}/providers/sampling_converter_anthropic.py +9 -11
- mcp_agent/{workflows/llm → llm}/providers/sampling_converter_openai.py +8 -12
- mcp_agent/{workflows/llm → llm}/sampling_converter.py +3 -31
- mcp_agent/llm/sampling_format_converter.py +37 -0
- mcp_agent/logging/events.py +1 -5
- mcp_agent/logging/json_serializer.py +7 -6
- mcp_agent/logging/listeners.py +20 -23
- mcp_agent/logging/logger.py +17 -19
- mcp_agent/logging/rich_progress.py +10 -8
- mcp_agent/logging/tracing.py +4 -6
- mcp_agent/logging/transport.py +22 -22
- mcp_agent/mcp/gen_client.py +1 -3
- mcp_agent/mcp/interfaces.py +117 -110
- mcp_agent/mcp/logger_textio.py +97 -0
- mcp_agent/mcp/mcp_agent_client_session.py +7 -7
- mcp_agent/mcp/mcp_agent_server.py +8 -8
- mcp_agent/mcp/mcp_aggregator.py +102 -143
- mcp_agent/mcp/mcp_connection_manager.py +20 -27
- mcp_agent/mcp/prompt_message_multipart.py +68 -16
- mcp_agent/mcp/prompt_render.py +77 -0
- mcp_agent/mcp/prompt_serialization.py +30 -48
- mcp_agent/mcp/prompts/prompt_constants.py +18 -0
- mcp_agent/mcp/prompts/prompt_helpers.py +327 -0
- mcp_agent/mcp/prompts/prompt_load.py +109 -0
- mcp_agent/mcp/prompts/prompt_server.py +155 -195
- mcp_agent/mcp/prompts/prompt_template.py +35 -66
- mcp_agent/mcp/resource_utils.py +7 -14
- mcp_agent/mcp/sampling.py +17 -17
- mcp_agent/mcp_server/agent_server.py +13 -17
- mcp_agent/mcp_server_registry.py +13 -22
- mcp_agent/resources/examples/{workflows → in_dev}/agent_build.py +3 -2
- mcp_agent/resources/examples/in_dev/slides.py +110 -0
- mcp_agent/resources/examples/internal/agent.py +6 -3
- mcp_agent/resources/examples/internal/fastagent.config.yaml +8 -2
- mcp_agent/resources/examples/internal/job.py +2 -1
- mcp_agent/resources/examples/internal/prompt_category.py +1 -1
- mcp_agent/resources/examples/internal/prompt_sizing.py +3 -5
- mcp_agent/resources/examples/internal/sizer.py +2 -1
- mcp_agent/resources/examples/internal/social.py +2 -1
- mcp_agent/resources/examples/prompting/agent.py +2 -1
- mcp_agent/resources/examples/prompting/image_server.py +4 -8
- mcp_agent/resources/examples/prompting/work_with_image.py +19 -0
- mcp_agent/ui/console_display.py +16 -20
- fast_agent_mcp-0.1.12.dist-info/RECORD +0 -161
- mcp_agent/core/agent_app.py +0 -646
- mcp_agent/core/agent_utils.py +0 -71
- mcp_agent/core/decorators.py +0 -455
- mcp_agent/core/factory.py +0 -463
- mcp_agent/core/proxies.py +0 -269
- mcp_agent/core/types.py +0 -24
- mcp_agent/eval/__init__.py +0 -0
- mcp_agent/mcp/stdio.py +0 -111
- mcp_agent/resources/examples/data-analysis/analysis-campaign.py +0 -188
- mcp_agent/resources/examples/data-analysis/analysis.py +0 -65
- mcp_agent/resources/examples/data-analysis/fastagent.config.yaml +0 -41
- mcp_agent/resources/examples/data-analysis/mount-point/WA_Fn-UseC_-HR-Employee-Attrition.csv +0 -1471
- mcp_agent/resources/examples/mcp_researcher/researcher-eval.py +0 -53
- mcp_agent/resources/examples/researcher/fastagent.config.yaml +0 -66
- mcp_agent/resources/examples/researcher/researcher-eval.py +0 -53
- mcp_agent/resources/examples/researcher/researcher-imp.py +0 -190
- mcp_agent/resources/examples/researcher/researcher.py +0 -38
- mcp_agent/resources/examples/workflows/chaining.py +0 -44
- mcp_agent/resources/examples/workflows/evaluator.py +0 -78
- mcp_agent/resources/examples/workflows/fastagent.config.yaml +0 -24
- mcp_agent/resources/examples/workflows/human_input.py +0 -25
- mcp_agent/resources/examples/workflows/orchestrator.py +0 -73
- mcp_agent/resources/examples/workflows/parallel.py +0 -78
- mcp_agent/resources/examples/workflows/router.py +0 -53
- mcp_agent/resources/examples/workflows/sse.py +0 -23
- mcp_agent/telemetry/__init__.py +0 -0
- mcp_agent/telemetry/usage_tracking.py +0 -18
- mcp_agent/workflows/__init__.py +0 -0
- mcp_agent/workflows/embedding/__init__.py +0 -0
- mcp_agent/workflows/embedding/embedding_base.py +0 -61
- mcp_agent/workflows/embedding/embedding_cohere.py +0 -49
- mcp_agent/workflows/embedding/embedding_openai.py +0 -46
- mcp_agent/workflows/evaluator_optimizer/__init__.py +0 -0
- mcp_agent/workflows/evaluator_optimizer/evaluator_optimizer.py +0 -481
- mcp_agent/workflows/intent_classifier/__init__.py +0 -0
- mcp_agent/workflows/intent_classifier/intent_classifier_base.py +0 -120
- mcp_agent/workflows/intent_classifier/intent_classifier_embedding.py +0 -134
- mcp_agent/workflows/intent_classifier/intent_classifier_embedding_cohere.py +0 -45
- mcp_agent/workflows/intent_classifier/intent_classifier_embedding_openai.py +0 -45
- mcp_agent/workflows/intent_classifier/intent_classifier_llm.py +0 -161
- mcp_agent/workflows/intent_classifier/intent_classifier_llm_anthropic.py +0 -60
- mcp_agent/workflows/intent_classifier/intent_classifier_llm_openai.py +0 -60
- mcp_agent/workflows/llm/__init__.py +0 -0
- mcp_agent/workflows/llm/augmented_llm.py +0 -753
- mcp_agent/workflows/llm/augmented_llm_passthrough.py +0 -241
- mcp_agent/workflows/llm/augmented_llm_playback.py +0 -109
- mcp_agent/workflows/llm/providers/__init__.py +0 -8
- mcp_agent/workflows/llm/sampling_format_converter.py +0 -22
- mcp_agent/workflows/orchestrator/__init__.py +0 -0
- mcp_agent/workflows/orchestrator/orchestrator.py +0 -578
- mcp_agent/workflows/parallel/__init__.py +0 -0
- mcp_agent/workflows/parallel/fan_in.py +0 -350
- mcp_agent/workflows/parallel/fan_out.py +0 -187
- mcp_agent/workflows/parallel/parallel_llm.py +0 -166
- mcp_agent/workflows/router/__init__.py +0 -0
- mcp_agent/workflows/router/router_base.py +0 -368
- mcp_agent/workflows/router/router_embedding.py +0 -240
- mcp_agent/workflows/router/router_embedding_cohere.py +0 -59
- mcp_agent/workflows/router/router_embedding_openai.py +0 -59
- mcp_agent/workflows/router/router_llm.py +0 -320
- mcp_agent/workflows/swarm/__init__.py +0 -0
- mcp_agent/workflows/swarm/swarm.py +0 -320
- mcp_agent/workflows/swarm/swarm_anthropic.py +0 -42
- mcp_agent/workflows/swarm/swarm_openai.py +0 -41
- {fast_agent_mcp-0.1.12.dist-info → fast_agent_mcp-0.2.0.dist-info}/WHEEL +0 -0
- {fast_agent_mcp-0.1.12.dist-info → fast_agent_mcp-0.2.0.dist-info}/entry_points.txt +0 -0
- {fast_agent_mcp-0.1.12.dist-info → fast_agent_mcp-0.2.0.dist-info}/licenses/LICENSE +0 -0
- /mcp_agent/{workflows/orchestrator → agents/workflow}/orchestrator_prompts.py +0 -0
@@ -1,59 +0,0 @@
|
|
1
|
-
from typing import Callable, List, Optional, TYPE_CHECKING
|
2
|
-
|
3
|
-
from mcp_agent.agents.agent import Agent
|
4
|
-
from mcp_agent.workflows.embedding.embedding_openai import OpenAIEmbeddingModel
|
5
|
-
from mcp_agent.workflows.router.router_embedding import EmbeddingRouter
|
6
|
-
|
7
|
-
if TYPE_CHECKING:
|
8
|
-
from mcp_agent.context import Context
|
9
|
-
|
10
|
-
|
11
|
-
class OpenAIEmbeddingRouter(EmbeddingRouter):
|
12
|
-
"""
|
13
|
-
A router that uses OpenAI embedding similarity to route requests to appropriate categories.
|
14
|
-
This class helps to route an input to a specific MCP server, an Agent (an aggregation of MCP servers),
|
15
|
-
or a function (any Callable).
|
16
|
-
"""
|
17
|
-
|
18
|
-
def __init__(
|
19
|
-
self,
|
20
|
-
server_names: List[str] | None = None,
|
21
|
-
agents: List[Agent] | None = None,
|
22
|
-
functions: List[Callable] | None = None,
|
23
|
-
embedding_model: OpenAIEmbeddingModel | None = None,
|
24
|
-
context: Optional["Context"] = None,
|
25
|
-
**kwargs,
|
26
|
-
):
|
27
|
-
embedding_model = embedding_model or OpenAIEmbeddingModel()
|
28
|
-
|
29
|
-
super().__init__(
|
30
|
-
embedding_model=embedding_model,
|
31
|
-
server_names=server_names,
|
32
|
-
agents=agents,
|
33
|
-
functions=functions,
|
34
|
-
context=context,
|
35
|
-
**kwargs,
|
36
|
-
)
|
37
|
-
|
38
|
-
@classmethod
|
39
|
-
async def create(
|
40
|
-
cls,
|
41
|
-
embedding_model: OpenAIEmbeddingModel | None = None,
|
42
|
-
server_names: List[str] | None = None,
|
43
|
-
agents: List[Agent] | None = None,
|
44
|
-
functions: List[Callable] | None = None,
|
45
|
-
context: Optional["Context"] = None,
|
46
|
-
) -> "OpenAIEmbeddingRouter":
|
47
|
-
"""
|
48
|
-
Factory method to create and initialize a router.
|
49
|
-
Use this instead of constructor since we need async initialization.
|
50
|
-
"""
|
51
|
-
instance = cls(
|
52
|
-
server_names=server_names,
|
53
|
-
agents=agents,
|
54
|
-
functions=functions,
|
55
|
-
embedding_model=embedding_model,
|
56
|
-
context=context,
|
57
|
-
)
|
58
|
-
await instance.initialize()
|
59
|
-
return instance
|
@@ -1,320 +0,0 @@
|
|
1
|
-
from typing import Callable, List, Literal, Optional, TYPE_CHECKING
|
2
|
-
|
3
|
-
from pydantic import BaseModel
|
4
|
-
|
5
|
-
from mcp_agent.agents.agent import Agent
|
6
|
-
from mcp_agent.workflows.llm.augmented_llm import AugmentedLLM, RequestParams
|
7
|
-
from mcp_agent.workflows.router.router_base import ResultT, Router, RouterResult
|
8
|
-
from mcp_agent.logging.logger import get_logger
|
9
|
-
from mcp_agent.event_progress import ProgressAction
|
10
|
-
|
11
|
-
if TYPE_CHECKING:
|
12
|
-
from mcp_agent.context import Context
|
13
|
-
|
14
|
-
logger = get_logger(__name__)
|
15
|
-
|
16
|
-
# TODO -- reinstate function/server routing
|
17
|
-
# TODO -- Generate the Example Schema from the Pydantic Model
|
18
|
-
DEFAULT_ROUTING_INSTRUCTION = """
|
19
|
-
You are a highly accurate request router that directs incoming requests to the most appropriate category.
|
20
|
-
A category is a specialized destination, such as a Function, an MCP Server (a collection of tools/functions), or an Agent (a collection of servers).
|
21
|
-
|
22
|
-
<fastagent:data>
|
23
|
-
<fastagent:categories>
|
24
|
-
{context}
|
25
|
-
</fastagent:categories>
|
26
|
-
|
27
|
-
<fastagent:request>
|
28
|
-
{request}
|
29
|
-
</fastagent:request>
|
30
|
-
</fastagent:data>
|
31
|
-
|
32
|
-
Your task is to analyze the request and determine the most appropriate categories from the options above. Consider:
|
33
|
-
- The specific capabilities and tools each destination offers
|
34
|
-
- How well the request matches the category's description
|
35
|
-
- Whether the request might benefit from multiple categories (up to {top_k})
|
36
|
-
|
37
|
-
<fastagent:instruction>
|
38
|
-
Respond in JSON format. NEVER include Code Fences:
|
39
|
-
{{
|
40
|
-
"categories": [
|
41
|
-
{{
|
42
|
-
"category": <category name>,
|
43
|
-
"confidence": <high, medium or low>,
|
44
|
-
"reasoning": <brief explanation>
|
45
|
-
}}
|
46
|
-
]
|
47
|
-
}}
|
48
|
-
|
49
|
-
Only include categories that are truly relevant. You may return fewer than {top_k} if appropriate.
|
50
|
-
If none of the categories are relevant, return an empty list.
|
51
|
-
</fastagent:instruction>
|
52
|
-
"""
|
53
|
-
|
54
|
-
ROUTING_SYSTEM_INSTRUCTION = """
|
55
|
-
You are a highly accurate request router that directs incoming requests to the most appropriate category.
|
56
|
-
A category is a specialized destination, such as a Function, an MCP Server (a collection of tools/functions), or an Agent (a collection of servers).
|
57
|
-
|
58
|
-
You will analyze requests and choose the most appropriate categories based on their capabilities and descriptions.
|
59
|
-
You can choose one or more categories, or choose none if no category is appropriate.
|
60
|
-
|
61
|
-
Follow these guidelines:
|
62
|
-
- Carefully match the request's needs with category capabilities
|
63
|
-
- Consider which tools or servers would best address the request
|
64
|
-
- If multiple categories could help, select all relevant ones
|
65
|
-
- Only include truly relevant categories, not tangentially related ones
|
66
|
-
"""
|
67
|
-
|
68
|
-
|
69
|
-
class ConfidenceRating(BaseModel):
|
70
|
-
"""Base class for models with confidence ratings and reasoning"""
|
71
|
-
|
72
|
-
"""The confidence level of the routing decision."""
|
73
|
-
confidence: Literal["high", "medium", "low"]
|
74
|
-
"""A brief explanation of the routing decision."""
|
75
|
-
reasoning: str | None = None # Make nullable to support both use cases
|
76
|
-
|
77
|
-
|
78
|
-
# Used for LLM output parsing
|
79
|
-
class StructuredResponseCategory(ConfidenceRating):
|
80
|
-
"""The name of the category (i.e. MCP server, Agent or function) to route the input to."""
|
81
|
-
|
82
|
-
category: str # Category name for lookup
|
83
|
-
|
84
|
-
|
85
|
-
class StructuredResponse(BaseModel):
|
86
|
-
categories: List[StructuredResponseCategory]
|
87
|
-
|
88
|
-
|
89
|
-
# Used for final router output
|
90
|
-
class LLMRouterResult(RouterResult[ResultT], ConfidenceRating):
|
91
|
-
# Inherits 'result' from RouterResult
|
92
|
-
# Inherits 'confidence' and 'reasoning' from ConfidenceRating
|
93
|
-
pass
|
94
|
-
|
95
|
-
|
96
|
-
class LLMRouter(Router):
|
97
|
-
"""
|
98
|
-
A router that uses an LLM to route an input to a specific category.
|
99
|
-
"""
|
100
|
-
|
101
|
-
def __init__(
|
102
|
-
self,
|
103
|
-
llm_factory: Callable[..., AugmentedLLM],
|
104
|
-
name: str = "LLM Router",
|
105
|
-
server_names: List[str] | None = None,
|
106
|
-
agents: List[Agent] | None = None,
|
107
|
-
functions: List[Callable] | None = None,
|
108
|
-
routing_instruction: str | None = None,
|
109
|
-
context: Optional["Context"] = None,
|
110
|
-
default_request_params: Optional[RequestParams] = None,
|
111
|
-
**kwargs,
|
112
|
-
):
|
113
|
-
# Extract verb from kwargs to avoid passing it up the inheritance chain
|
114
|
-
self._llm_verb = kwargs.pop("verb", None)
|
115
|
-
|
116
|
-
super().__init__(
|
117
|
-
server_names=server_names,
|
118
|
-
agents=agents,
|
119
|
-
functions=functions,
|
120
|
-
routing_instruction=routing_instruction,
|
121
|
-
context=context,
|
122
|
-
**kwargs,
|
123
|
-
)
|
124
|
-
|
125
|
-
self.name = name
|
126
|
-
self.llm_factory = llm_factory
|
127
|
-
self.default_request_params = default_request_params or RequestParams()
|
128
|
-
self.llm = None # Will be initialized in create()
|
129
|
-
|
130
|
-
@classmethod
|
131
|
-
async def create(
|
132
|
-
cls,
|
133
|
-
llm_factory: Callable[..., AugmentedLLM],
|
134
|
-
name: str = "LLM Router",
|
135
|
-
server_names: List[str] | None = None,
|
136
|
-
agents: List[Agent] | None = None,
|
137
|
-
functions: List[Callable] | None = None,
|
138
|
-
routing_instruction: str | None = None,
|
139
|
-
context: Optional["Context"] = None,
|
140
|
-
default_request_params: Optional[RequestParams] = None,
|
141
|
-
) -> "LLMRouter":
|
142
|
-
"""
|
143
|
-
Factory method to create and initialize a router.
|
144
|
-
Use this instead of constructor since we need async initialization.
|
145
|
-
"""
|
146
|
-
instance = cls(
|
147
|
-
llm_factory=llm_factory,
|
148
|
-
name=name,
|
149
|
-
server_names=server_names,
|
150
|
-
agents=agents,
|
151
|
-
functions=functions,
|
152
|
-
routing_instruction=DEFAULT_ROUTING_INSTRUCTION,
|
153
|
-
context=context,
|
154
|
-
default_request_params=default_request_params,
|
155
|
-
)
|
156
|
-
await instance.initialize()
|
157
|
-
return instance
|
158
|
-
|
159
|
-
async def initialize(self):
|
160
|
-
"""Initialize the router and create the LLM instance."""
|
161
|
-
if not self.initialized:
|
162
|
-
await super().initialize()
|
163
|
-
router_params = RequestParams(
|
164
|
-
systemPrompt=ROUTING_SYSTEM_INSTRUCTION,
|
165
|
-
use_history=False, # Router should be stateless :)
|
166
|
-
)
|
167
|
-
|
168
|
-
# Merge with any provided default params
|
169
|
-
if self.default_request_params:
|
170
|
-
params_dict = router_params.model_dump()
|
171
|
-
params_dict.update(
|
172
|
-
self.default_request_params.model_dump(exclude_unset=True)
|
173
|
-
)
|
174
|
-
router_params = RequestParams(**params_dict)
|
175
|
-
# Set up router-specific request params with routing instruction
|
176
|
-
router_params.use_history = False
|
177
|
-
# Use the stored verb if available, otherwise default to ROUTING
|
178
|
-
verb_param = (
|
179
|
-
self._llm_verb
|
180
|
-
if hasattr(self, "_llm_verb") and self._llm_verb
|
181
|
-
else ProgressAction.ROUTING
|
182
|
-
)
|
183
|
-
|
184
|
-
self.llm = self.llm_factory(
|
185
|
-
agent=None, # Router doesn't need an agent context
|
186
|
-
name=self.name, # Use the name provided during initialization
|
187
|
-
default_request_params=router_params,
|
188
|
-
verb=verb_param, # Use stored verb parameter or default to ROUTING
|
189
|
-
)
|
190
|
-
self.initialized = True
|
191
|
-
|
192
|
-
async def route(
|
193
|
-
self, request: str, top_k: int = 1
|
194
|
-
) -> List[LLMRouterResult[str | Agent | Callable]]:
|
195
|
-
if not self.initialized:
|
196
|
-
await self.initialize()
|
197
|
-
|
198
|
-
return await self._route_with_llm(request, top_k)
|
199
|
-
|
200
|
-
async def route_to_server(
|
201
|
-
self, request: str, top_k: int = 1
|
202
|
-
) -> List[LLMRouterResult[str]]:
|
203
|
-
if not self.initialized:
|
204
|
-
await self.initialize()
|
205
|
-
|
206
|
-
return await self._route_with_llm(
|
207
|
-
request,
|
208
|
-
top_k,
|
209
|
-
include_servers=True,
|
210
|
-
include_agents=False,
|
211
|
-
include_functions=False,
|
212
|
-
)
|
213
|
-
|
214
|
-
async def route_to_agent(
|
215
|
-
self, request: str, top_k: int = 1
|
216
|
-
) -> List[LLMRouterResult[Agent]]:
|
217
|
-
if not self.initialized:
|
218
|
-
await self.initialize()
|
219
|
-
|
220
|
-
return await self._route_with_llm(
|
221
|
-
request,
|
222
|
-
top_k,
|
223
|
-
include_servers=False,
|
224
|
-
include_agents=True,
|
225
|
-
include_functions=False,
|
226
|
-
)
|
227
|
-
|
228
|
-
async def route_to_function(
|
229
|
-
self, request: str, top_k: int = 1
|
230
|
-
) -> List[LLMRouterResult[Callable]]:
|
231
|
-
if not self.initialized:
|
232
|
-
await self.initialize()
|
233
|
-
|
234
|
-
return await self._route_with_llm(
|
235
|
-
request,
|
236
|
-
top_k,
|
237
|
-
include_servers=False,
|
238
|
-
include_agents=False,
|
239
|
-
include_functions=True,
|
240
|
-
)
|
241
|
-
|
242
|
-
async def _route_with_llm(
|
243
|
-
self,
|
244
|
-
request: str,
|
245
|
-
top_k: int = 1,
|
246
|
-
include_servers: bool = True,
|
247
|
-
include_agents: bool = True,
|
248
|
-
include_functions: bool = True,
|
249
|
-
) -> List[LLMRouterResult]:
|
250
|
-
if not self.initialized:
|
251
|
-
await self.initialize()
|
252
|
-
|
253
|
-
routing_instruction = self.routing_instruction or DEFAULT_ROUTING_INSTRUCTION
|
254
|
-
|
255
|
-
# Generate the categories context
|
256
|
-
context = self._generate_context(
|
257
|
-
include_servers=include_servers,
|
258
|
-
include_agents=include_agents,
|
259
|
-
include_functions=include_functions,
|
260
|
-
)
|
261
|
-
|
262
|
-
# Format the prompt with all the necessary information
|
263
|
-
prompt = routing_instruction.format(
|
264
|
-
context=context, request=request, top_k=top_k
|
265
|
-
)
|
266
|
-
|
267
|
-
response = await self.llm.generate_structured(
|
268
|
-
message=prompt,
|
269
|
-
response_model=StructuredResponse,
|
270
|
-
)
|
271
|
-
|
272
|
-
# Construct the result
|
273
|
-
if not response or not response.categories:
|
274
|
-
return []
|
275
|
-
|
276
|
-
result: List[LLMRouterResult] = []
|
277
|
-
for r in response.categories:
|
278
|
-
router_category = self.categories.get(r.category)
|
279
|
-
if not router_category:
|
280
|
-
# TODO: log or raise an error
|
281
|
-
continue
|
282
|
-
|
283
|
-
result.append(
|
284
|
-
LLMRouterResult(
|
285
|
-
result=router_category.category,
|
286
|
-
confidence=r.confidence,
|
287
|
-
reasoning=r.reasoning,
|
288
|
-
)
|
289
|
-
)
|
290
|
-
|
291
|
-
return result[:top_k]
|
292
|
-
|
293
|
-
def _generate_context(
|
294
|
-
self,
|
295
|
-
include_servers: bool = True,
|
296
|
-
include_agents: bool = True,
|
297
|
-
include_functions: bool = True,
|
298
|
-
) -> str:
|
299
|
-
"""Generate a formatted context list of categories."""
|
300
|
-
|
301
|
-
context_list = []
|
302
|
-
idx = 1
|
303
|
-
|
304
|
-
# Format all categories
|
305
|
-
if include_servers:
|
306
|
-
for category in self.server_categories.values():
|
307
|
-
context_list.append(self.format_category(category, idx))
|
308
|
-
idx += 1
|
309
|
-
|
310
|
-
if include_agents:
|
311
|
-
for category in self.agent_categories.values():
|
312
|
-
context_list.append(self.format_category(category, idx))
|
313
|
-
idx += 1
|
314
|
-
|
315
|
-
if include_functions:
|
316
|
-
for category in self.function_categories.values():
|
317
|
-
context_list.append(self.format_category(category, idx))
|
318
|
-
idx += 1
|
319
|
-
|
320
|
-
return "\n\n".join(context_list)
|
File without changes
|
@@ -1,320 +0,0 @@
|
|
1
|
-
from typing import Callable, Dict, Generic, List, Optional, TYPE_CHECKING
|
2
|
-
from collections import defaultdict
|
3
|
-
|
4
|
-
from pydantic import AnyUrl, BaseModel, ConfigDict
|
5
|
-
from mcp.types import (
|
6
|
-
CallToolRequest,
|
7
|
-
EmbeddedResource,
|
8
|
-
CallToolResult,
|
9
|
-
TextContent,
|
10
|
-
TextResourceContents,
|
11
|
-
Tool,
|
12
|
-
)
|
13
|
-
|
14
|
-
from mcp_agent.agents.agent import Agent
|
15
|
-
from mcp_agent.human_input.types import HumanInputCallback
|
16
|
-
from mcp_agent.workflows.llm.augmented_llm import (
|
17
|
-
AugmentedLLM,
|
18
|
-
MessageParamT,
|
19
|
-
MessageT,
|
20
|
-
)
|
21
|
-
from mcp_agent.logging.logger import get_logger
|
22
|
-
|
23
|
-
if TYPE_CHECKING:
|
24
|
-
from mcp_agent.context import Context
|
25
|
-
|
26
|
-
logger = get_logger(__name__)
|
27
|
-
|
28
|
-
|
29
|
-
class AgentResource(EmbeddedResource):
|
30
|
-
"""
|
31
|
-
A resource that returns an agent. Meant for use with tool calls that want to return an Agent for further processing.
|
32
|
-
"""
|
33
|
-
|
34
|
-
agent: Optional["Agent"] = None
|
35
|
-
|
36
|
-
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
|
37
|
-
|
38
|
-
|
39
|
-
class AgentFunctionResultResource(EmbeddedResource):
|
40
|
-
"""
|
41
|
-
A resource that returns an AgentFunctionResult.
|
42
|
-
Meant for use with tool calls that return an AgentFunctionResult for further processing.
|
43
|
-
"""
|
44
|
-
|
45
|
-
result: "AgentFunctionResult"
|
46
|
-
|
47
|
-
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
|
48
|
-
|
49
|
-
|
50
|
-
def create_agent_resource(agent: "Agent") -> AgentResource:
|
51
|
-
return AgentResource(
|
52
|
-
type="resource",
|
53
|
-
agent=agent,
|
54
|
-
resource=TextResourceContents(
|
55
|
-
text=f"You are now Agent '{agent.name}'. Please review the messages and continue execution",
|
56
|
-
uri=AnyUrl("http://fake.url"), # Required property but not needed
|
57
|
-
),
|
58
|
-
)
|
59
|
-
|
60
|
-
|
61
|
-
def create_agent_function_result_resource(
|
62
|
-
result: "AgentFunctionResult",
|
63
|
-
) -> AgentFunctionResultResource:
|
64
|
-
return AgentFunctionResultResource(
|
65
|
-
type="resource",
|
66
|
-
result=result,
|
67
|
-
resource=TextResourceContents(
|
68
|
-
text=result.value or result.agent.name or "AgentFunctionResult",
|
69
|
-
uri=AnyUrl("http://fake.url"), # Required property but not needed
|
70
|
-
),
|
71
|
-
)
|
72
|
-
|
73
|
-
|
74
|
-
class SwarmAgent(Agent):
|
75
|
-
"""
|
76
|
-
A SwarmAgent is an Agent that can spawn other agents and interactively resolve a task.
|
77
|
-
Based on OpenAI Swarm: https://github.com/openai/swarm.
|
78
|
-
|
79
|
-
SwarmAgents have access to tools available on the servers they are connected to, but additionally
|
80
|
-
have a list of (possibly local) functions that can be called as tools.
|
81
|
-
"""
|
82
|
-
|
83
|
-
def __init__(
|
84
|
-
self,
|
85
|
-
name: str,
|
86
|
-
instruction: str | Callable[[Dict], str] = "You are a helpful agent.",
|
87
|
-
server_names: list[str] = None,
|
88
|
-
functions: List["AgentFunctionCallable"] = None,
|
89
|
-
parallel_tool_calls: bool = True,
|
90
|
-
human_input_callback: HumanInputCallback = None,
|
91
|
-
context: Optional["Context"] = None,
|
92
|
-
**kwargs,
|
93
|
-
):
|
94
|
-
super().__init__(
|
95
|
-
name=name,
|
96
|
-
instruction=instruction,
|
97
|
-
server_names=server_names,
|
98
|
-
functions=functions,
|
99
|
-
# TODO: saqadri - figure out if Swarm can maintain connection persistence
|
100
|
-
# It's difficult because we don't know when the agent will be done with its task
|
101
|
-
connection_persistence=False,
|
102
|
-
human_input_callback=human_input_callback,
|
103
|
-
context=context,
|
104
|
-
**kwargs,
|
105
|
-
)
|
106
|
-
self.parallel_tool_calls = parallel_tool_calls
|
107
|
-
|
108
|
-
async def call_tool(
|
109
|
-
self, name: str, arguments: dict | None = None
|
110
|
-
) -> CallToolResult:
|
111
|
-
if not self.initialized:
|
112
|
-
await self.initialize()
|
113
|
-
|
114
|
-
if name in self._function_tool_map:
|
115
|
-
tool = self._function_tool_map[name]
|
116
|
-
result = await tool.run(arguments)
|
117
|
-
|
118
|
-
logger.debug(f"Function tool {name} result:", data=result)
|
119
|
-
|
120
|
-
if isinstance(result, Agent) or isinstance(result, SwarmAgent):
|
121
|
-
resource = create_agent_resource(result)
|
122
|
-
return CallToolResult(content=[resource])
|
123
|
-
elif isinstance(result, AgentFunctionResult):
|
124
|
-
resource = create_agent_function_result_resource(result)
|
125
|
-
return CallToolResult(content=[resource])
|
126
|
-
elif isinstance(result, str):
|
127
|
-
# TODO: saqadri - this is likely meant for returning context variables
|
128
|
-
return CallToolResult(content=[TextContent(type="text", text=result)])
|
129
|
-
elif isinstance(result, dict):
|
130
|
-
return CallToolResult(
|
131
|
-
content=[TextContent(type="text", text=str(result))]
|
132
|
-
)
|
133
|
-
else:
|
134
|
-
logger.warning(f"Unknown result type: {result}, returning as text.")
|
135
|
-
return CallToolResult(
|
136
|
-
content=[TextContent(type="text", text=str(result))]
|
137
|
-
)
|
138
|
-
|
139
|
-
return await super().call_tool(name, arguments)
|
140
|
-
|
141
|
-
|
142
|
-
class AgentFunctionResult(BaseModel):
|
143
|
-
"""
|
144
|
-
Encapsulates the possible return values for a Swarm agent function.
|
145
|
-
|
146
|
-
Attributes:
|
147
|
-
value (str): The result value as a string.
|
148
|
-
agent (Agent): The agent instance, if applicable.
|
149
|
-
context_variables (dict): A dictionary of context variables.
|
150
|
-
"""
|
151
|
-
|
152
|
-
value: str = ""
|
153
|
-
agent: Agent | None = None
|
154
|
-
context_variables: dict = {}
|
155
|
-
|
156
|
-
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
|
157
|
-
|
158
|
-
|
159
|
-
AgentFunctionReturnType = str | Agent | dict | AgentFunctionResult
|
160
|
-
"""A type alias for the return type of a Swarm agent function."""
|
161
|
-
|
162
|
-
AgentFunctionCallable = Callable[[], AgentFunctionReturnType]
|
163
|
-
|
164
|
-
|
165
|
-
async def create_transfer_to_agent_tool(
|
166
|
-
agent: "Agent", agent_function: Callable[[], None]
|
167
|
-
) -> Tool:
|
168
|
-
return Tool(
|
169
|
-
name="transfer_to_agent",
|
170
|
-
description="Transfer control to the agent",
|
171
|
-
agent_resource=create_agent_resource(agent),
|
172
|
-
agent_function=agent_function,
|
173
|
-
)
|
174
|
-
|
175
|
-
|
176
|
-
async def create_agent_function_tool(agent_function: "AgentFunctionCallable") -> Tool:
|
177
|
-
return Tool(
|
178
|
-
name="agent_function",
|
179
|
-
description="Agent function",
|
180
|
-
agent_resource=None,
|
181
|
-
agent_function=agent_function,
|
182
|
-
)
|
183
|
-
|
184
|
-
|
185
|
-
class Swarm(AugmentedLLM[MessageParamT, MessageT], Generic[MessageParamT, MessageT]):
|
186
|
-
"""
|
187
|
-
Handles orchestrating agents that can use tools via MCP servers.
|
188
|
-
|
189
|
-
MCP version of the OpenAI Swarm class (https://github.com/openai/swarm.)
|
190
|
-
"""
|
191
|
-
|
192
|
-
# TODO: saqadri - streaming isn't supported yet because the underlying AugmentedLLM classes don't support it
|
193
|
-
def __init__(self, agent: SwarmAgent, context_variables: Dict[str, str] = None):
|
194
|
-
"""
|
195
|
-
Initialize the LLM planner with an agent, which will be used as the
|
196
|
-
starting point for the workflow.
|
197
|
-
"""
|
198
|
-
super().__init__(agent=agent)
|
199
|
-
self.context_variables = defaultdict(str, context_variables or {})
|
200
|
-
self.instruction = (
|
201
|
-
agent.instruction(self.context_variables)
|
202
|
-
if isinstance(agent.instruction, Callable)
|
203
|
-
else agent.instruction
|
204
|
-
)
|
205
|
-
logger.debug(
|
206
|
-
f"Swarm initialized with agent {agent.name}",
|
207
|
-
data={
|
208
|
-
"context_variables": self.context_variables,
|
209
|
-
"instruction": self.instruction,
|
210
|
-
},
|
211
|
-
)
|
212
|
-
|
213
|
-
async def get_tool(self, tool_name: str) -> Tool | None:
|
214
|
-
"""Get the schema for a tool by name."""
|
215
|
-
result = await self.aggregator.list_tools()
|
216
|
-
for tool in result.tools:
|
217
|
-
if tool.name == tool_name:
|
218
|
-
return tool
|
219
|
-
|
220
|
-
return None
|
221
|
-
|
222
|
-
async def pre_tool_call(
|
223
|
-
self, tool_call_id: str | None, request: CallToolRequest
|
224
|
-
) -> CallToolRequest | bool:
|
225
|
-
if not self.aggregator:
|
226
|
-
# If there are no agents, we can't do anything, so we should bail
|
227
|
-
return False
|
228
|
-
|
229
|
-
tool = await self.get_tool(request.params.name)
|
230
|
-
if not tool:
|
231
|
-
logger.warning(
|
232
|
-
f"Warning: Tool '{request.params.name}' not found in agent '{self.aggregator.name}' tools. Proceeding with original request params."
|
233
|
-
)
|
234
|
-
return request
|
235
|
-
|
236
|
-
# If the tool has a "context_variables" parameter, we set it to our context variables state
|
237
|
-
if "context_variables" in tool.inputSchema:
|
238
|
-
logger.debug(
|
239
|
-
f"Setting context variables on tool_call '{request.params.name}'",
|
240
|
-
data=self.context_variables,
|
241
|
-
)
|
242
|
-
request.params.arguments["context_variables"] = self.context_variables
|
243
|
-
|
244
|
-
return request
|
245
|
-
|
246
|
-
async def post_tool_call(
|
247
|
-
self, tool_call_id: str | None, request: CallToolRequest, result: CallToolResult
|
248
|
-
) -> CallToolResult:
|
249
|
-
contents = []
|
250
|
-
for content in result.content:
|
251
|
-
if isinstance(content, AgentResource):
|
252
|
-
# Set the new agent as the current agent
|
253
|
-
await self.set_agent(content.agent)
|
254
|
-
contents.append(TextContent(type="text", text=content.resource.text))
|
255
|
-
elif isinstance(content, AgentFunctionResult):
|
256
|
-
logger.info(
|
257
|
-
"Updating context variables with new context variables from agent function result",
|
258
|
-
data=content.context_variables,
|
259
|
-
)
|
260
|
-
self.context_variables.update(content.context_variables)
|
261
|
-
if content.agent:
|
262
|
-
# Set the new agent as the current agent
|
263
|
-
self.set_agent(content.agent)
|
264
|
-
|
265
|
-
contents.append(TextContent(type="text", text=content.resource.text))
|
266
|
-
else:
|
267
|
-
contents.append(content)
|
268
|
-
|
269
|
-
result.content = contents
|
270
|
-
return result
|
271
|
-
|
272
|
-
async def set_agent(
|
273
|
-
self,
|
274
|
-
agent: SwarmAgent,
|
275
|
-
):
|
276
|
-
logger.info(
|
277
|
-
f"Switching from agent '{self.aggregator.name}' -> agent '{agent.name if agent else 'NULL'}'"
|
278
|
-
)
|
279
|
-
if self.aggregator:
|
280
|
-
# Close the current agent
|
281
|
-
await self.aggregator.shutdown()
|
282
|
-
|
283
|
-
# Initialize the new agent (if it's not None)
|
284
|
-
self.aggregator = agent
|
285
|
-
|
286
|
-
if not self.aggregator or isinstance(self.aggregator, DoneAgent):
|
287
|
-
self.instruction = None
|
288
|
-
return
|
289
|
-
|
290
|
-
await self.aggregator.initialize()
|
291
|
-
self.instruction = (
|
292
|
-
agent.instruction(self.context_variables)
|
293
|
-
if callable(agent.instruction)
|
294
|
-
else agent.instruction
|
295
|
-
)
|
296
|
-
|
297
|
-
def should_continue(self) -> bool:
|
298
|
-
"""
|
299
|
-
Returns True if the workflow should continue, False otherwise.
|
300
|
-
"""
|
301
|
-
if not self.aggregator or isinstance(self.aggregator, DoneAgent):
|
302
|
-
return False
|
303
|
-
|
304
|
-
return True
|
305
|
-
|
306
|
-
|
307
|
-
class DoneAgent(SwarmAgent):
|
308
|
-
"""
|
309
|
-
A special agent that represents the end of a Swarm workflow.
|
310
|
-
"""
|
311
|
-
|
312
|
-
def __init__(self):
|
313
|
-
super().__init__(name="__done__", instruction="Swarm Workflow is complete.")
|
314
|
-
|
315
|
-
async def call_tool(
|
316
|
-
self, _name: str, _arguments: dict | None = None
|
317
|
-
) -> CallToolResult:
|
318
|
-
return CallToolResult(
|
319
|
-
content=[TextContent(type="text", text="Workflow is complete.")]
|
320
|
-
)
|