Skip to content

Commit 3eaf948

Browse files
committed
Update AugmentedLLM interface to use CreateMessageResult and SamplingMessage types, add MCP-model provider type converters, and add a "Done" agent for Swarm workflow
1 parent 16b9ddb commit 3eaf948

File tree

24 files changed

+908
-486
lines changed

24 files changed

+908
-486
lines changed

examples/marimo_mcp_basic_agent/notebook.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def format_list_tools_result(list_tools_result: ListToolsResult):
3434
res += f"- **{tool.name}**: {tool.description}\n\n"
3535
return res
3636

37-
3837
tools_str = format_list_tools_result(tools)
3938
mo.accordion({"View tools": mo.md(tools_str)})
4039
return format_list_tools_result, tools_str
@@ -47,9 +46,10 @@ async def model(messages, config):
4746
response = await llm.generate_str(message.content)
4847
return mo.md(response)
4948

50-
5149
chatbot = mo.ui.chat(
52-
model, prompts=["What are some files in my filesystem", "Get google.com"], show_configuration_controls=False
50+
model,
51+
prompts=["What are some files in my filesystem", "Get google.com"],
52+
show_configuration_controls=False,
5353
)
5454
chatbot
5555
return chatbot, model
@@ -87,6 +87,7 @@ async def _(Agent, OpenAIAugmentedLLM):
8787
@app.cell
8888
def _():
8989
import marimo as mo
90+
9091
return (mo,)
9192

9293

examples/mcp_server_aggregator/main.py

-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ async def example_usage():
9090
arguments={"url": "https://jsonplaceholder.typicode.com/todos/1"},
9191
)
9292
logger.info(f"fetch result: {str(result)}")
93-
await asyncio.sleep(5)
9493
except Exception as e:
9594
logger.error("Error in example_usage:", data=e)
9695
finally:

examples/streamlit_mcp_basic_agent/main.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import asyncio
44
from mcp_agent.app import MCPApp
55
from mcp_agent.agents.agent import Agent
6+
from mcp_agent.workflows.llm.augmented_llm import RequestParams
67
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
78

89

@@ -52,7 +53,9 @@ async def main():
5253
with st.chat_message("assistant"):
5354
response = ""
5455
with st.spinner("Thinking..."):
55-
response = await llm.generate_str(message=prompt, use_history=True)
56+
response = await llm.generate_str(
57+
message=prompt, request_params=RequestParams(use_history=True)
58+
)
5659
st.markdown(response)
5760

5861
st.session_state["messages"].append({"role": "assistant", "content": response})

examples/streamlit_mcp_rag_agent/main.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from qdrant_client import QdrantClient
33
from mcp_agent.app import MCPApp
44
from mcp_agent.agents.agent import Agent
5+
from mcp_agent.workflows.llm.augmented_llm import RequestParams
56
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
67
from agent_state import get_agent_state
78
import streamlit as st
@@ -66,7 +67,7 @@ async def main():
6667
response = ""
6768
with st.spinner("Thinking..."):
6869
response = await state.llm.generate_str(
69-
message=prompt, use_history=True
70+
message=prompt, request_params=RequestParams(use_history=True)
7071
)
7172
st.markdown(response)
7273

examples/workflow_evaluator_optimizer/main.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from mcp_agent.app import MCPApp
44
from mcp_agent.agents.agent import Agent
5+
from mcp_agent.workflows.llm.augmented_llm import RequestParams
56
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
67

78
from mcp_agent.workflows.evaluator_optimizer.evaluator_optimizer import (
@@ -76,7 +77,7 @@ async def example_usage():
7677

7778
result = await evaluator_optimizer.generate_str(
7879
message=f"Write a cover letter for the following job posting: {job_posting}\n\nCandidate Details: {candidate_details}\n\nCompany information: {company_information}",
79-
model="gpt-4o",
80+
request_params=RequestParams(model="gpt-4o"),
8081
)
8182

8283
logger.info(f"{result}")
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,78 @@
1-
**Graded Report on 'The Battle of Glimmerwood'**
1+
# Graded Report: The Battle of Glimmerwood
22

3-
**Proofreading Feedback:**
4-
- Corrected various grammatical errors such as verb tense mismatches and subject-verb agreement.
5-
- Recommended consistent use of past tense for clarity.
6-
- Suggested improvements in comma usage and spelling verification to enhance sentence construction.
3+
## Proofreading Feedback
74

8-
**Factual and Logical Consistency Evaluation:**
9-
- Identified incongruities in the villagers' rapid response to the marauders without prior preparation context.
10-
- Highlighted the need for more background on Elara's leadership capabilities or motivation.
11-
- Suggested more detailed descriptions of magical elements like Glimmerfoxes and their roles.
12-
- Recommended clarification on the safeguarding methods for Glimmerstones and their significance.
5+
### Grammar, Spelling, and Punctuation Corrections:
136

14-
**APA Style Adherence:**
15-
- Ensured consistency with APA style for title, margins, font usage, and paragraph indentation.
16-
- Considered elements like running heads and page numbers depending on the document's purpose.
7+
1. **Spelling Errors:**
8+
- Correct "knowed" to "known."
9+
- Correct "shaterred" to "shattered."
10+
- Correct "attack" to "attacked."
11+
- Correct "aim" to "aimed."
12+
- Correct "choas" to "chaos."
13+
- Correct "aproached" to "approached."
14+
- Correct "captured" to "capture."
15+
- Correct "confirm" to "confirmed."
1716

18-
**Suggestions for Clarity and Engagement:**
19-
- Advocated for consistent verb tense usage and grammar refinement.
20-
- Encouraged use of vivid descriptions and varied sentence structures for engagement.
21-
- Suggested further character development and balanced pacing of events.
17+
2. **Grammar and Sentence Structure:**
18+
- Change "The villagers, who were live peacefully," to "The villagers, who lived peacefully," to correct verb tense.
19+
- Change "fur shimmer like moonlight" to "fur shimmered like moonlight" to match subject-verb agreement.
20+
- Change "Lead by the cunning Captain Thorn," to "Led by the cunning Captain Thorn," to use the correct past participle.
21+
- Adjust "which was believed to grant immortality" to "which were believed to grant immortality" to match noun-verb agreement with the plural "Glimmerstones."
22+
- Insert a conjunction for clarity: "a young girl named Elara stood her ground, she rallied the villagers" to "a young girl named Elara stood her ground and rallied the villagers."
23+
- Add a comma for clarity: "forests natural defenses" should be "forest's natural defenses".
24+
- Adjust "As the bandits aproached the village square, a herd of Glimmerfoxes emerged," to ensure clarity: "As the bandits approached the village square, a herd of Glimmerfoxes emerged, blinding them with their dazzling light. The villagers seized the opportunity to capture the invaders."
25+
- Adjust "The Glimmerstones true power" to "The Glimmerstones' true power" to indicate possession properly.
26+
- Change "and whispers of a hidden agenda linger among the villagers" to "while whispers of a hidden agenda lingered among the villagers" to ensure proper tense consistency and flow.
2227

23-
By addressing these points, the story's overall readability, coherence, and adherence to APA guidelines will be improved, enhancing the narrative's professional presentation.
28+
### Overall Suggestions:
29+
This story effectively uses imagery and fantasy elements to engage readers. However, addressing the above grammatical and structural issues will enhance clarity and reader enjoyment. Consider revisiting verb tenses for consistency throughout the story, and make sure all subject-verb agreements align appropriately. Additionally, watch out for spelling mistakes that could distract from the engaging narrative.
30+
31+
## Logical Consistency and Factual Review
32+
33+
### Logical Inconsistencies and Contradictions:
34+
35+
1. **Ambiguity in Characters' Knowledge and Abilities:**
36+
- The story mentions "the Glimmerstones which was believed to grant immortality," but then states "The Glimmerstone's true power was never confirmed." This presents a contradiction in terms of the villagers’ understanding and certainty about the Glimmerstones' powers. If their power was never confirmed, it's illogical for them to form a belief around immortality.
37+
38+
2. **Timeline and Setting Clarity:**
39+
- The event of rallying and trapping the bandits progresses rapidly without a clear timeline or logistical explanation of how Elara instantly organized defense with the villagers and forest creatures. The story transitions swiftly from the attack to victory, which lacks a detailed transition that leads readers through the progression of events.
40+
41+
3. **Plan and Execution Details:**
42+
- Elara rallies the villagers and devises a "clever plan" using the forest’s natural defenses. However, the story does not provide details about the plan's execution or the specific actions taken that would logically lead to trapping seasoned bandits. The lack of explanation weakens the plausibility of the villagers and a young girl overcoming notorious bandits.
43+
44+
4. **Defense Strategy and Capabilities:**
45+
- The narrative suggests using "the forest's natural defenses" and a blinding light from Glimmerfoxes to defeat the Dark Marauders. Yet, it does not explain the nature of these defenses or how the abilities of the Glimmerfoxes were tactically employed, leading to uncertainty around the feasibility of the villagers' defense strategy.
46+
47+
5. **Character Motivation and Consequences:**
48+
- The motivation behind the Dark Marauders seeking the Glimmerstones is clear, but there's ambiguity in the villagers' response and how the aftermath affects their lives and the perception of the imminent threat. The story ends by hinting at a hidden agenda but does not explore the implications or next steps, leaving a narrative gap.
49+
50+
By addressing these inconsistencies and providing additional context and explanations, the story can achieve greater coherence and believability.
51+
52+
## APA Style Evaluation
53+
54+
### Evaluation of APA Style Adherence:
55+
56+
#### 1. **Formatting:**
57+
- **Running Head & Header:** The story does not contain a running head or headers with page numbers, as suggested by APA formatting standards.
58+
- **Margins:** There's no information on margins since it's not formatted as a complete document.
59+
- **Title Page Elements:** The story lacks a proper title page that should include the title, author byline, and institutional affiliation according to APA guidelines.
60+
- **Heading Levels:** The document uses a single level of heading ("The Battle of Glimmerwood"). APA formatting suggests more structured headings if the document's complexity requires it, starting with Level 1 headings.
61+
62+
#### 2. **References and In-text Citations:**
63+
- **Reference List:** There is no reference list at the end of the story, which is essential in APA style when external sources are referenced (though this story appears to be fictional, any quotes or specific influences should be cited).
64+
- **In-text Citations:** There are no in-text citations in the narrative, which are necessary if any part of the content was inspired by or derived from specific works or documents.
65+
66+
### Suggestions for Improvement:
67+
68+
1. **Add a Title Page:** Including elements such as the story title, author's name, and institutional affiliation aligns with APA requirements for academic papers.
69+
70+
2. **Format Headers:** If turned into a proper document, incorporate a header with a running head and page numbers.
71+
72+
3. **Incorporate References:** If the story draws from any real-world factual content or existing literature, ensure to provide proper in-text citations and a reference list at the conclusion.
73+
74+
4. **Expand Headings (if necessary):** Structure the document with more detailed headings if broken into multiple sections, aligning them with APA style heading levels.
75+
76+
5. **Check Margins & Spacing:** Although not visible here, ensure document margins are set properly if it transitions into a word processor environment.
77+
78+
This evaluation should guide necessary changes to adhere to APA style for both formatting and referencing, enhancing both accessibility and professional presentation of the short story.

examples/workflow_orchestrator_worker/main.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from mcp_agent.app import MCPApp
55
from mcp_agent.agents.agent import Agent
6+
from mcp_agent.workflows.llm.augmented_llm import RequestParams
67
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
78
from mcp_agent.workflows.orchestrator.orchestrator import Orchestrator
89

@@ -158,7 +159,9 @@ async def example_usage():
158159
plan_type="full",
159160
)
160161

161-
result = await orchestrator.generate_str(message=task, model="gpt-4o")
162+
result = await orchestrator.generate_str(
163+
message=task, request_params=RequestParams(model="gpt-4o")
164+
)
162165
logger.info(f"{result}")
163166

164167

examples/workflow_parallel/main.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from mcp_agent.app import MCPApp
55
from mcp_agent.agents.agent import Agent
6+
from mcp_agent.workflows.llm.augmented_llm import RequestParams
67
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
78

89
# from mcp_agent.workflows.parallel.fan_in import FanIn
@@ -84,7 +85,8 @@ async def example_usage():
8485
)
8586

8687
result = await parallel.generate_str(
87-
message=f"Student short story submission: {SHORT_STORY}", model="gpt-4o"
88+
message=f"Student short story submission: {SHORT_STORY}",
89+
request_params=RequestParams(model="gpt-4o"),
8890
)
8991

9092
logger.info(f"{result}")

examples/workflow_swarm/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import os
33

44
from mcp_agent.app import MCPApp
5-
from mcp_agent.workflows.swarm.swarm import SwarmAgent
5+
from mcp_agent.workflows.swarm.swarm import DoneAgent, SwarmAgent
66
from mcp_agent.workflows.swarm.swarm_anthropic import AnthropicSwarm
77
from mcp_agent.human_input.handler import console_input_callback
88

@@ -41,7 +41,7 @@ def initiate_flight_credits():
4141

4242
def case_resolved():
4343
"""Resolve the case"""
44-
return "Case resolved. No further questions."
44+
return DoneAgent()
4545

4646

4747
# Agents

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ build-backend = "hatchling.build"
4949

5050
[dependency-groups]
5151
dev = [
52+
"anthropic>=0.42.0",
5253
"pre-commit>=4.0.1",
5354
"pydantic>=2.10.4",
5455
"pyyaml>=6.0.2",

src/mcp_agent/context.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@
3333
from mcp_agent.logging.logger import LoggingConfig
3434
from mcp_agent.logging.transport import create_transport
3535
from mcp_agent.mcp_server_registry import ServerRegistry
36+
from mcp_agent.workflows.llm.llm_selector import ModelSelector
3637

3738
if TYPE_CHECKING:
3839
from mcp_agent.human_input.types import HumanInputCallback
3940
from mcp_agent.executor.workflow_signal import SignalWaitCallback
40-
from mcp_agent.workflows.llm.llm_selector import ModelSelector
4141
else:
4242
# Runtime placeholders for the types
4343
HumanInputCallback = Any
@@ -55,7 +55,7 @@ class Context(BaseModel):
5555
human_input_handler: Optional[HumanInputCallback] = None
5656
signal_notification: Optional[SignalWaitCallback] = None
5757
upstream_session: Optional[ServerSession] = None # TODO: saqadri - figure this out
58-
model_selector: Optional["ModelSelector"] = None
58+
model_selector: Optional[ModelSelector] = None
5959

6060
# Registries
6161
server_registry: Optional[ServerRegistry] = None

src/mcp_agent/workflows/evaluator_optimizer/evaluator_optimizer.py

+10-47
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
MessageParamT,
99
MessageT,
1010
ModelT,
11+
RequestParams,
1112
)
1213
from mcp_agent.agents.agent import Agent
1314
from mcp_agent.logging.logger import get_logger
@@ -149,12 +150,7 @@ def __init__(
149150
async def generate(
150151
self,
151152
message: str | MessageParamT | List[MessageParamT],
152-
use_history: bool = True,
153-
max_iterations: int = 10,
154-
model: str = None,
155-
stop_sequences: List[str] = None,
156-
max_tokens: int = 2048,
157-
parallel_tool_calls: bool = True,
153+
request_params: RequestParams | None = None,
158154
) -> List[MessageT]:
159155
"""Generate an optimized response through evaluation-guided refinement"""
160156
refinement_count = 0
@@ -169,12 +165,7 @@ async def generate(
169165
await stack.enter_async_context(self.optimizer)
170166
response = await self.optimizer_llm.generate(
171167
message=message,
172-
use_history=use_history,
173-
max_iterations=max_iterations,
174-
model=model,
175-
stop_sequences=stop_sequences,
176-
max_tokens=max_tokens,
177-
parallel_tool_calls=parallel_tool_calls,
168+
request_params=request_params,
178169
)
179170

180171
best_response = response
@@ -199,8 +190,7 @@ async def generate(
199190
evaluation_result = await self.evaluator_llm.generate_structured(
200191
message=eval_prompt,
201192
response_model=EvaluationResult,
202-
model=model,
203-
max_tokens=max_tokens,
193+
request_params=request_params,
204194
)
205195

206196
# Track iteration
@@ -254,12 +244,7 @@ async def generate(
254244

255245
response = await self.optimizer_llm.generate(
256246
message=refinement_prompt,
257-
use_history=use_history,
258-
max_iterations=max_iterations,
259-
model=model,
260-
stop_sequences=stop_sequences,
261-
max_tokens=max_tokens,
262-
parallel_tool_calls=parallel_tool_calls,
247+
request_params=request_params,
263248
)
264249

265250
refinement_count += 1
@@ -269,22 +254,12 @@ async def generate(
269254
async def generate_str(
270255
self,
271256
message: str | MessageParamT | List[MessageParamT],
272-
use_history: bool = True,
273-
max_iterations: int = 10,
274-
model: str = None,
275-
stop_sequences: List[str] = None,
276-
max_tokens: int = 2048,
277-
parallel_tool_calls: bool = True,
257+
request_params: RequestParams | None = None,
278258
) -> str:
279259
"""Generate an optimized response and return it as a string"""
280260
response = await self.generate(
281261
message=message,
282-
use_history=use_history,
283-
max_iterations=max_iterations,
284-
model=model,
285-
stop_sequences=stop_sequences,
286-
max_tokens=max_tokens,
287-
parallel_tool_calls=parallel_tool_calls,
262+
request_params=request_params,
288263
)
289264

290265
return "\n".join(self.optimizer_llm.message_str(r) for r in response)
@@ -293,29 +268,17 @@ async def generate_structured(
293268
self,
294269
message: str | MessageParamT | List[MessageParamT],
295270
response_model: Type[ModelT],
296-
use_history: bool = True,
297-
max_iterations: int = 10,
298-
model: str = None,
299-
stop_sequences: List[str] = None,
300-
max_tokens: int = 2048,
301-
parallel_tool_calls: bool = True,
271+
request_params: RequestParams | None = None,
302272
) -> ModelT:
303273
"""Generate an optimized structured response"""
304274
response_str = await self.generate_str(
305-
message=message,
306-
use_history=use_history,
307-
max_iterations=max_iterations,
308-
model=model,
309-
stop_sequences=stop_sequences,
310-
max_tokens=max_tokens,
311-
parallel_tool_calls=parallel_tool_calls,
275+
message=message, request_params=request_params
312276
)
313277

314278
return await self.optimizer.generate_structured(
315279
message=response_str,
316280
response_model=response_model,
317-
model=model,
318-
max_tokens=max_tokens,
281+
request_params=request_params,
319282
)
320283

321284
def _build_eval_prompt(

0 commit comments

Comments
 (0)