fast-agent-mcp 0.1.13__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.
Files changed (147) hide show
  1. {fast_agent_mcp-0.1.13.dist-info → fast_agent_mcp-0.2.0.dist-info}/METADATA +3 -4
  2. fast_agent_mcp-0.2.0.dist-info/RECORD +123 -0
  3. mcp_agent/__init__.py +75 -0
  4. mcp_agent/agents/agent.py +59 -371
  5. mcp_agent/agents/base_agent.py +522 -0
  6. mcp_agent/agents/workflow/__init__.py +1 -0
  7. mcp_agent/agents/workflow/chain_agent.py +173 -0
  8. mcp_agent/agents/workflow/evaluator_optimizer.py +362 -0
  9. mcp_agent/agents/workflow/orchestrator_agent.py +591 -0
  10. mcp_agent/{workflows/orchestrator → agents/workflow}/orchestrator_models.py +27 -11
  11. mcp_agent/agents/workflow/parallel_agent.py +182 -0
  12. mcp_agent/agents/workflow/router_agent.py +307 -0
  13. mcp_agent/app.py +3 -1
  14. mcp_agent/cli/commands/bootstrap.py +18 -7
  15. mcp_agent/cli/commands/setup.py +12 -4
  16. mcp_agent/cli/main.py +1 -1
  17. mcp_agent/cli/terminal.py +1 -1
  18. mcp_agent/config.py +24 -35
  19. mcp_agent/context.py +3 -1
  20. mcp_agent/context_dependent.py +3 -1
  21. mcp_agent/core/agent_types.py +10 -7
  22. mcp_agent/core/direct_agent_app.py +179 -0
  23. mcp_agent/core/direct_decorators.py +443 -0
  24. mcp_agent/core/direct_factory.py +476 -0
  25. mcp_agent/core/enhanced_prompt.py +15 -20
  26. mcp_agent/core/fastagent.py +151 -337
  27. mcp_agent/core/interactive_prompt.py +424 -0
  28. mcp_agent/core/mcp_content.py +19 -11
  29. mcp_agent/core/prompt.py +6 -2
  30. mcp_agent/core/validation.py +89 -16
  31. mcp_agent/executor/decorator_registry.py +6 -2
  32. mcp_agent/executor/temporal.py +35 -11
  33. mcp_agent/executor/workflow_signal.py +8 -2
  34. mcp_agent/human_input/handler.py +3 -1
  35. mcp_agent/llm/__init__.py +2 -0
  36. mcp_agent/{workflows/llm → llm}/augmented_llm.py +131 -256
  37. mcp_agent/{workflows/llm → llm}/augmented_llm_passthrough.py +35 -107
  38. mcp_agent/llm/augmented_llm_playback.py +83 -0
  39. mcp_agent/{workflows/llm → llm}/model_factory.py +26 -8
  40. mcp_agent/llm/providers/__init__.py +8 -0
  41. mcp_agent/{workflows/llm → llm/providers}/anthropic_utils.py +5 -1
  42. mcp_agent/{workflows/llm → llm/providers}/augmented_llm_anthropic.py +37 -141
  43. mcp_agent/llm/providers/augmented_llm_deepseek.py +53 -0
  44. mcp_agent/{workflows/llm → llm/providers}/augmented_llm_openai.py +112 -148
  45. mcp_agent/{workflows/llm → llm}/providers/multipart_converter_anthropic.py +78 -35
  46. mcp_agent/{workflows/llm → llm}/providers/multipart_converter_openai.py +73 -44
  47. mcp_agent/{workflows/llm → llm}/providers/openai_multipart.py +18 -4
  48. mcp_agent/{workflows/llm → llm/providers}/openai_utils.py +3 -3
  49. mcp_agent/{workflows/llm → llm}/providers/sampling_converter_anthropic.py +3 -3
  50. mcp_agent/{workflows/llm → llm}/providers/sampling_converter_openai.py +3 -3
  51. mcp_agent/{workflows/llm → llm}/sampling_converter.py +0 -21
  52. mcp_agent/{workflows/llm → llm}/sampling_format_converter.py +16 -1
  53. mcp_agent/logging/logger.py +2 -2
  54. mcp_agent/mcp/gen_client.py +9 -3
  55. mcp_agent/mcp/interfaces.py +67 -45
  56. mcp_agent/mcp/logger_textio.py +97 -0
  57. mcp_agent/mcp/mcp_agent_client_session.py +12 -4
  58. mcp_agent/mcp/mcp_agent_server.py +3 -1
  59. mcp_agent/mcp/mcp_aggregator.py +124 -93
  60. mcp_agent/mcp/mcp_connection_manager.py +21 -7
  61. mcp_agent/mcp/prompt_message_multipart.py +59 -1
  62. mcp_agent/mcp/prompt_render.py +77 -0
  63. mcp_agent/mcp/prompt_serialization.py +20 -13
  64. mcp_agent/mcp/prompts/prompt_constants.py +18 -0
  65. mcp_agent/mcp/prompts/prompt_helpers.py +327 -0
  66. mcp_agent/mcp/prompts/prompt_load.py +15 -5
  67. mcp_agent/mcp/prompts/prompt_server.py +154 -87
  68. mcp_agent/mcp/prompts/prompt_template.py +26 -35
  69. mcp_agent/mcp/resource_utils.py +3 -1
  70. mcp_agent/mcp/sampling.py +24 -15
  71. mcp_agent/mcp_server/agent_server.py +8 -5
  72. mcp_agent/mcp_server_registry.py +22 -9
  73. mcp_agent/resources/examples/{workflows → in_dev}/agent_build.py +1 -1
  74. mcp_agent/resources/examples/{data-analysis → in_dev}/slides.py +1 -1
  75. mcp_agent/resources/examples/internal/agent.py +4 -2
  76. mcp_agent/resources/examples/internal/fastagent.config.yaml +8 -2
  77. mcp_agent/resources/examples/prompting/image_server.py +3 -1
  78. mcp_agent/resources/examples/prompting/work_with_image.py +19 -0
  79. mcp_agent/ui/console_display.py +27 -7
  80. fast_agent_mcp-0.1.13.dist-info/RECORD +0 -164
  81. mcp_agent/core/agent_app.py +0 -570
  82. mcp_agent/core/agent_utils.py +0 -69
  83. mcp_agent/core/decorators.py +0 -448
  84. mcp_agent/core/factory.py +0 -422
  85. mcp_agent/core/proxies.py +0 -278
  86. mcp_agent/core/types.py +0 -22
  87. mcp_agent/eval/__init__.py +0 -0
  88. mcp_agent/mcp/stdio.py +0 -114
  89. mcp_agent/resources/examples/data-analysis/analysis-campaign.py +0 -188
  90. mcp_agent/resources/examples/data-analysis/analysis.py +0 -65
  91. mcp_agent/resources/examples/data-analysis/fastagent.config.yaml +0 -41
  92. mcp_agent/resources/examples/data-analysis/mount-point/WA_Fn-UseC_-HR-Employee-Attrition.csv +0 -1471
  93. mcp_agent/resources/examples/mcp_researcher/researcher-eval.py +0 -53
  94. mcp_agent/resources/examples/researcher/fastagent.config.yaml +0 -66
  95. mcp_agent/resources/examples/researcher/researcher-eval.py +0 -53
  96. mcp_agent/resources/examples/researcher/researcher-imp.py +0 -189
  97. mcp_agent/resources/examples/researcher/researcher.py +0 -39
  98. mcp_agent/resources/examples/workflows/chaining.py +0 -45
  99. mcp_agent/resources/examples/workflows/evaluator.py +0 -79
  100. mcp_agent/resources/examples/workflows/fastagent.config.yaml +0 -24
  101. mcp_agent/resources/examples/workflows/human_input.py +0 -26
  102. mcp_agent/resources/examples/workflows/orchestrator.py +0 -74
  103. mcp_agent/resources/examples/workflows/parallel.py +0 -79
  104. mcp_agent/resources/examples/workflows/router.py +0 -54
  105. mcp_agent/resources/examples/workflows/sse.py +0 -23
  106. mcp_agent/telemetry/__init__.py +0 -0
  107. mcp_agent/telemetry/usage_tracking.py +0 -19
  108. mcp_agent/workflows/__init__.py +0 -0
  109. mcp_agent/workflows/embedding/__init__.py +0 -0
  110. mcp_agent/workflows/embedding/embedding_base.py +0 -58
  111. mcp_agent/workflows/embedding/embedding_cohere.py +0 -49
  112. mcp_agent/workflows/embedding/embedding_openai.py +0 -37
  113. mcp_agent/workflows/evaluator_optimizer/__init__.py +0 -0
  114. mcp_agent/workflows/evaluator_optimizer/evaluator_optimizer.py +0 -447
  115. mcp_agent/workflows/intent_classifier/__init__.py +0 -0
  116. mcp_agent/workflows/intent_classifier/intent_classifier_base.py +0 -117
  117. mcp_agent/workflows/intent_classifier/intent_classifier_embedding.py +0 -130
  118. mcp_agent/workflows/intent_classifier/intent_classifier_embedding_cohere.py +0 -41
  119. mcp_agent/workflows/intent_classifier/intent_classifier_embedding_openai.py +0 -41
  120. mcp_agent/workflows/intent_classifier/intent_classifier_llm.py +0 -150
  121. mcp_agent/workflows/intent_classifier/intent_classifier_llm_anthropic.py +0 -60
  122. mcp_agent/workflows/intent_classifier/intent_classifier_llm_openai.py +0 -58
  123. mcp_agent/workflows/llm/__init__.py +0 -0
  124. mcp_agent/workflows/llm/augmented_llm_playback.py +0 -111
  125. mcp_agent/workflows/llm/providers/__init__.py +0 -8
  126. mcp_agent/workflows/orchestrator/__init__.py +0 -0
  127. mcp_agent/workflows/orchestrator/orchestrator.py +0 -535
  128. mcp_agent/workflows/parallel/__init__.py +0 -0
  129. mcp_agent/workflows/parallel/fan_in.py +0 -320
  130. mcp_agent/workflows/parallel/fan_out.py +0 -181
  131. mcp_agent/workflows/parallel/parallel_llm.py +0 -149
  132. mcp_agent/workflows/router/__init__.py +0 -0
  133. mcp_agent/workflows/router/router_base.py +0 -338
  134. mcp_agent/workflows/router/router_embedding.py +0 -226
  135. mcp_agent/workflows/router/router_embedding_cohere.py +0 -59
  136. mcp_agent/workflows/router/router_embedding_openai.py +0 -59
  137. mcp_agent/workflows/router/router_llm.py +0 -304
  138. mcp_agent/workflows/swarm/__init__.py +0 -0
  139. mcp_agent/workflows/swarm/swarm.py +0 -292
  140. mcp_agent/workflows/swarm/swarm_anthropic.py +0 -42
  141. mcp_agent/workflows/swarm/swarm_openai.py +0 -41
  142. {fast_agent_mcp-0.1.13.dist-info → fast_agent_mcp-0.2.0.dist-info}/WHEEL +0 -0
  143. {fast_agent_mcp-0.1.13.dist-info → fast_agent_mcp-0.2.0.dist-info}/entry_points.txt +0 -0
  144. {fast_agent_mcp-0.1.13.dist-info → fast_agent_mcp-0.2.0.dist-info}/licenses/LICENSE +0 -0
  145. /mcp_agent/{workflows/orchestrator → agents/workflow}/orchestrator_prompts.py +0 -0
  146. /mcp_agent/{workflows/llm → llm}/memory.py +0 -0
  147. /mcp_agent/{workflows/llm → llm}/prompt_utils.py +0 -0
@@ -1,304 +0,0 @@
1
- from typing import TYPE_CHECKING, Callable, List, Literal, Optional
2
-
3
- from pydantic import BaseModel
4
-
5
- from mcp_agent.agents.agent import Agent
6
- from mcp_agent.event_progress import ProgressAction
7
- from mcp_agent.logging.logger import get_logger
8
- from mcp_agent.workflows.llm.augmented_llm import AugmentedLLM, RequestParams
9
- from mcp_agent.workflows.router.router_base import ResultT, Router, RouterResult
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
- ) -> None:
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) -> None:
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(self.default_request_params.model_dump(exclude_unset=True))
172
- router_params = RequestParams(**params_dict)
173
- # Set up router-specific request params with routing instruction
174
- router_params.use_history = False
175
- # Use the stored verb if available, otherwise default to ROUTING
176
- verb_param = self._llm_verb if hasattr(self, "_llm_verb") and self._llm_verb else ProgressAction.ROUTING
177
-
178
- self.llm = self.llm_factory(
179
- agent=None, # Router doesn't need an agent context
180
- name=self.name, # Use the name provided during initialization
181
- default_request_params=router_params,
182
- verb=verb_param, # Use stored verb parameter or default to ROUTING
183
- )
184
- self.initialized = True
185
-
186
- async def route(self, request: str, top_k: int = 1) -> List[LLMRouterResult[str | Agent | Callable]]:
187
- if not self.initialized:
188
- await self.initialize()
189
-
190
- return await self._route_with_llm(request, top_k)
191
-
192
- async def route_to_server(self, request: str, top_k: int = 1) -> List[LLMRouterResult[str]]:
193
- if not self.initialized:
194
- await self.initialize()
195
-
196
- return await self._route_with_llm(
197
- request,
198
- top_k,
199
- include_servers=True,
200
- include_agents=False,
201
- include_functions=False,
202
- )
203
-
204
- async def route_to_agent(self, request: str, top_k: int = 1) -> List[LLMRouterResult[Agent]]:
205
- if not self.initialized:
206
- await self.initialize()
207
-
208
- return await self._route_with_llm(
209
- request,
210
- top_k,
211
- include_servers=False,
212
- include_agents=True,
213
- include_functions=False,
214
- )
215
-
216
- async def route_to_function(self, request: str, top_k: int = 1) -> List[LLMRouterResult[Callable]]:
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=False,
225
- include_functions=True,
226
- )
227
-
228
- async def _route_with_llm(
229
- self,
230
- request: str,
231
- top_k: int = 1,
232
- include_servers: bool = True,
233
- include_agents: bool = True,
234
- include_functions: bool = True,
235
- ) -> List[LLMRouterResult]:
236
- if not self.initialized:
237
- await self.initialize()
238
-
239
- routing_instruction = self.routing_instruction or DEFAULT_ROUTING_INSTRUCTION
240
-
241
- # Generate the categories context
242
- context = self._generate_context(
243
- include_servers=include_servers,
244
- include_agents=include_agents,
245
- include_functions=include_functions,
246
- )
247
-
248
- # Format the prompt with all the necessary information
249
- prompt = routing_instruction.format(context=context, request=request, top_k=top_k)
250
-
251
- response = await self.llm.generate_structured(
252
- message=prompt,
253
- response_model=StructuredResponse,
254
- )
255
-
256
- # Construct the result
257
- if not response or not response.categories:
258
- return []
259
-
260
- result: List[LLMRouterResult] = []
261
- for r in response.categories:
262
- router_category = self.categories.get(r.category)
263
- if not router_category:
264
- # TODO: log or raise an error
265
- continue
266
-
267
- result.append(
268
- LLMRouterResult(
269
- result=router_category.category,
270
- confidence=r.confidence,
271
- reasoning=r.reasoning,
272
- )
273
- )
274
-
275
- return result[:top_k]
276
-
277
- def _generate_context(
278
- self,
279
- include_servers: bool = True,
280
- include_agents: bool = True,
281
- include_functions: bool = True,
282
- ) -> str:
283
- """Generate a formatted context list of categories."""
284
-
285
- context_list = []
286
- idx = 1
287
-
288
- # Format all categories
289
- if include_servers:
290
- for category in self.server_categories.values():
291
- context_list.append(self.format_category(category, idx))
292
- idx += 1
293
-
294
- if include_agents:
295
- for category in self.agent_categories.values():
296
- context_list.append(self.format_category(category, idx))
297
- idx += 1
298
-
299
- if include_functions:
300
- for category in self.function_categories.values():
301
- context_list.append(self.format_category(category, idx))
302
- idx += 1
303
-
304
- return "\n\n".join(context_list)
File without changes
@@ -1,292 +0,0 @@
1
- from collections import defaultdict
2
- from typing import TYPE_CHECKING, Callable, Dict, Generic, List, Optional
3
-
4
- from mcp.types import (
5
- CallToolRequest,
6
- CallToolResult,
7
- EmbeddedResource,
8
- TextContent,
9
- TextResourceContents,
10
- Tool,
11
- )
12
- from pydantic import AnyUrl, BaseModel, ConfigDict
13
-
14
- from mcp_agent.agents.agent import Agent
15
- from mcp_agent.human_input.types import HumanInputCallback
16
- from mcp_agent.logging.logger import get_logger
17
- from mcp_agent.workflows.llm.augmented_llm import (
18
- AugmentedLLM,
19
- MessageParamT,
20
- MessageT,
21
- )
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
- ) -> None:
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(self, name: str, arguments: dict | None = None) -> CallToolResult:
109
- if not self.initialized:
110
- await self.initialize()
111
-
112
- if name in self._function_tool_map:
113
- tool = self._function_tool_map[name]
114
- result = await tool.run(arguments)
115
-
116
- logger.debug(f"Function tool {name} result:", data=result)
117
-
118
- if isinstance(result, Agent) or isinstance(result, SwarmAgent):
119
- resource = create_agent_resource(result)
120
- return CallToolResult(content=[resource])
121
- elif isinstance(result, AgentFunctionResult):
122
- resource = create_agent_function_result_resource(result)
123
- return CallToolResult(content=[resource])
124
- elif isinstance(result, str):
125
- # TODO: saqadri - this is likely meant for returning context variables
126
- return CallToolResult(content=[TextContent(type="text", text=result)])
127
- elif isinstance(result, dict):
128
- return CallToolResult(content=[TextContent(type="text", text=str(result))])
129
- else:
130
- logger.warning(f"Unknown result type: {result}, returning as text.")
131
- return CallToolResult(content=[TextContent(type="text", text=str(result))])
132
-
133
- return await super().call_tool(name, arguments)
134
-
135
-
136
- class AgentFunctionResult(BaseModel):
137
- """
138
- Encapsulates the possible return values for a Swarm agent function.
139
-
140
- Attributes:
141
- value (str): The result value as a string.
142
- agent (Agent): The agent instance, if applicable.
143
- context_variables (dict): A dictionary of context variables.
144
- """
145
-
146
- value: str = ""
147
- agent: Agent | None = None
148
- context_variables: dict = {}
149
-
150
- model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
151
-
152
-
153
- AgentFunctionReturnType = str | Agent | dict | AgentFunctionResult
154
- """A type alias for the return type of a Swarm agent function."""
155
-
156
- AgentFunctionCallable = Callable[[], AgentFunctionReturnType]
157
-
158
-
159
- async def create_transfer_to_agent_tool(agent: "Agent", agent_function: Callable[[], None]) -> Tool:
160
- return Tool(
161
- name="transfer_to_agent",
162
- description="Transfer control to the agent",
163
- agent_resource=create_agent_resource(agent),
164
- agent_function=agent_function,
165
- )
166
-
167
-
168
- async def create_agent_function_tool(agent_function: "AgentFunctionCallable") -> Tool:
169
- return Tool(
170
- name="agent_function",
171
- description="Agent function",
172
- agent_resource=None,
173
- agent_function=agent_function,
174
- )
175
-
176
-
177
- class Swarm(AugmentedLLM[MessageParamT, MessageT], Generic[MessageParamT, MessageT]):
178
- """
179
- Handles orchestrating agents that can use tools via MCP servers.
180
-
181
- MCP version of the OpenAI Swarm class (https://github.com/openai/swarm.)
182
- """
183
-
184
- # TODO: saqadri - streaming isn't supported yet because the underlying AugmentedLLM classes don't support it
185
- def __init__(self, agent: SwarmAgent, context_variables: Dict[str, str] = None) -> None:
186
- """
187
- Initialize the LLM planner with an agent, which will be used as the
188
- starting point for the workflow.
189
- """
190
- super().__init__(agent=agent)
191
- self.context_variables = defaultdict(str, context_variables or {})
192
- self.instruction = agent.instruction(self.context_variables) if isinstance(agent.instruction, Callable) else agent.instruction
193
- logger.debug(
194
- f"Swarm initialized with agent {agent.name}",
195
- data={
196
- "context_variables": self.context_variables,
197
- "instruction": self.instruction,
198
- },
199
- )
200
-
201
- async def get_tool(self, tool_name: str) -> Tool | None:
202
- """Get the schema for a tool by name."""
203
- result = await self.aggregator.list_tools()
204
- for tool in result.tools:
205
- if tool.name == tool_name:
206
- return tool
207
-
208
- return None
209
-
210
- async def pre_tool_call(self, tool_call_id: str | None, request: CallToolRequest) -> CallToolRequest | bool:
211
- if not self.aggregator:
212
- # If there are no agents, we can't do anything, so we should bail
213
- return False
214
-
215
- tool = await self.get_tool(request.params.name)
216
- if not tool:
217
- logger.warning(f"Warning: Tool '{request.params.name}' not found in agent '{self.aggregator.name}' tools. Proceeding with original request params.")
218
- return request
219
-
220
- # If the tool has a "context_variables" parameter, we set it to our context variables state
221
- if "context_variables" in tool.inputSchema:
222
- logger.debug(
223
- f"Setting context variables on tool_call '{request.params.name}'",
224
- data=self.context_variables,
225
- )
226
- request.params.arguments["context_variables"] = self.context_variables
227
-
228
- return request
229
-
230
- async def post_tool_call(self, tool_call_id: str | None, request: CallToolRequest, result: CallToolResult) -> CallToolResult:
231
- contents = []
232
- for content in result.content:
233
- if isinstance(content, AgentResource):
234
- # Set the new agent as the current agent
235
- await self.set_agent(content.agent)
236
- contents.append(TextContent(type="text", text=content.resource.text))
237
- elif isinstance(content, AgentFunctionResult):
238
- logger.info(
239
- "Updating context variables with new context variables from agent function result",
240
- data=content.context_variables,
241
- )
242
- self.context_variables.update(content.context_variables)
243
- if content.agent:
244
- # Set the new agent as the current agent
245
- self.set_agent(content.agent)
246
-
247
- contents.append(TextContent(type="text", text=content.resource.text))
248
- else:
249
- contents.append(content)
250
-
251
- result.content = contents
252
- return result
253
-
254
- async def set_agent(
255
- self,
256
- agent: SwarmAgent,
257
- ) -> None:
258
- logger.info(f"Switching from agent '{self.aggregator.name}' -> agent '{agent.name if agent else 'NULL'}'")
259
- if self.aggregator:
260
- # Close the current agent
261
- await self.aggregator.shutdown()
262
-
263
- # Initialize the new agent (if it's not None)
264
- self.aggregator = agent
265
-
266
- if not self.aggregator or isinstance(self.aggregator, DoneAgent):
267
- self.instruction = None
268
- return
269
-
270
- await self.aggregator.initialize()
271
- self.instruction = agent.instruction(self.context_variables) if callable(agent.instruction) else agent.instruction
272
-
273
- def should_continue(self) -> bool:
274
- """
275
- Returns True if the workflow should continue, False otherwise.
276
- """
277
- if not self.aggregator or isinstance(self.aggregator, DoneAgent):
278
- return False
279
-
280
- return True
281
-
282
-
283
- class DoneAgent(SwarmAgent):
284
- """
285
- A special agent that represents the end of a Swarm workflow.
286
- """
287
-
288
- def __init__(self) -> None:
289
- super().__init__(name="__done__", instruction="Swarm Workflow is complete.")
290
-
291
- async def call_tool(self, _name: str, _arguments: dict | None = None) -> CallToolResult:
292
- return CallToolResult(content=[TextContent(type="text", text="Workflow is complete.")])
@@ -1,42 +0,0 @@
1
- from mcp_agent.logging.logger import get_logger
2
- from mcp_agent.workflows.llm.augmented_llm import RequestParams
3
- from mcp_agent.workflows.llm.augmented_llm_anthropic import AnthropicAugmentedLLM
4
- from mcp_agent.workflows.swarm.swarm import Swarm
5
-
6
- logger = get_logger(__name__)
7
-
8
-
9
- class AnthropicSwarm(Swarm, AnthropicAugmentedLLM):
10
- """
11
- MCP version of the OpenAI Swarm class (https://github.com/openai/swarm.),
12
- using Anthropic's API as the LLM.
13
- """
14
-
15
- async def generate(self, message, request_params: RequestParams | None = None):
16
- params = self.get_request_params(
17
- request_params,
18
- default=RequestParams(
19
- model="claude-3-5-sonnet-20241022",
20
- maxTokens=8192,
21
- parallel_tool_calls=False,
22
- ),
23
- )
24
- iterations = 0
25
- response = None
26
- agent_name = str(self.aggregator.name) if self.aggregator else None
27
-
28
- while iterations < params.max_iterations and self.should_continue():
29
- response = await super().generate(
30
- message=message
31
- if iterations == 0
32
- else "Please resolve my original request. If it has already been resolved then end turn",
33
- request_params=params.model_copy(
34
- update={"max_iterations": 1}
35
- ), # TODO: saqadri - validate
36
- )
37
- logger.debug(f"Agent: {agent_name}, response:", data=response)
38
- agent_name = self.aggregator.name if self.aggregator else None
39
- iterations += 1
40
-
41
- # Return final response back
42
- return response
@@ -1,41 +0,0 @@
1
- from mcp_agent.logging.logger import get_logger
2
- from mcp_agent.workflows.llm.augmented_llm import RequestParams
3
- from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
4
- from mcp_agent.workflows.swarm.swarm import Swarm
5
-
6
- logger = get_logger(__name__)
7
-
8
-
9
- class OpenAISwarm(Swarm, OpenAIAugmentedLLM):
10
- """
11
- MCP version of the OpenAI Swarm class (https://github.com/openai/swarm.), using OpenAI's ChatCompletion as the LLM.
12
- """
13
-
14
- async def generate(self, message, request_params: RequestParams | None = None):
15
- params = self.get_request_params(
16
- request_params,
17
- default=RequestParams(
18
- model="gpt-4o",
19
- maxTokens=8192,
20
- parallel_tool_calls=False,
21
- ),
22
- )
23
- iterations = 0
24
- response = None
25
- agent_name = str(self.aggregator.name) if self.aggregator else None
26
-
27
- while iterations < params.max_iterations and self.should_continue():
28
- response = await super().generate(
29
- message=message
30
- if iterations == 0
31
- else "Please resolve my original request. If it has already been resolved then end turn",
32
- request_params=params.model_copy(
33
- update={"max_iterations": 1} # TODO: saqadri - validate
34
- ),
35
- )
36
- logger.debug(f"Agent: {agent_name}, response:", data=response)
37
- agent_name = self.aggregator.name if self.aggregator else None
38
- iterations += 1
39
-
40
- # Return final response back
41
- return response
File without changes
File without changes