[ORGANIZE MCP EXAMPLES]

pull/1054/head
Kye Gomez 4 days ago
parent 30b94c0d6b
commit 438029dbe5

@ -27,48 +27,66 @@ def create_sample_agent():
# Example 1: Simple output transformation callback # Example 1: Simple output transformation callback
def transform_output_callback(output: Any, task: str, metadata: Dict) -> Dict: def transform_output_callback(
output: Any, task: str, metadata: Dict
) -> Dict:
"""Transform the agent output into a structured format. """Transform the agent output into a structured format.
Args: Args:
output: The original output from the agent output: The original output from the agent
task: The task that was executed task: The task that was executed
metadata: Job metadata including execution count, timestamp, etc. metadata: Job metadata including execution count, timestamp, etc.
Returns: Returns:
Dict: Transformed output with additional metadata Dict: Transformed output with additional metadata
""" """
return { return {
"original_output": output, "original_output": output,
"transformed_at": datetime.fromtimestamp(metadata["timestamp"]).isoformat(), "transformed_at": datetime.fromtimestamp(
metadata["timestamp"]
).isoformat(),
"execution_number": metadata["execution_count"], "execution_number": metadata["execution_count"],
"task_executed": task, "task_executed": task,
"job_status": "running" if metadata["is_running"] else "stopped", "job_status": (
"uptime_seconds": metadata["uptime"] if metadata["start_time"] else 0 "running" if metadata["is_running"] else "stopped"
),
"uptime_seconds": (
metadata["uptime"] if metadata["start_time"] else 0
),
} }
# Example 2: Output filtering and enhancement callback # Example 2: Output filtering and enhancement callback
def filter_and_enhance_callback(output: Any, task: str, metadata: Dict) -> Dict: def filter_and_enhance_callback(
output: Any, task: str, metadata: Dict
) -> Dict:
"""Filter and enhance the output based on execution count and content. """Filter and enhance the output based on execution count and content.
Args: Args:
output: The original output from the agent output: The original output from the agent
task: The task that was executed task: The task that was executed
metadata: Job metadata metadata: Job metadata
Returns: Returns:
Dict: Filtered and enhanced output Dict: Filtered and enhanced output
""" """
# Only include outputs that contain certain keywords # Only include outputs that contain certain keywords
if isinstance(output, str): if isinstance(output, str):
if any(keyword in output.lower() for keyword in ["important", "key", "significant", "trend"]): if any(
keyword in output.lower()
for keyword in [
"important",
"key",
"significant",
"trend",
]
):
enhanced_output = { enhanced_output = {
"content": output, "content": output,
"priority": "high", "priority": "high",
"execution_id": metadata["execution_count"], "execution_id": metadata["execution_count"],
"timestamp": metadata["timestamp"], "timestamp": metadata["timestamp"],
"analysis_type": "priority_content" "analysis_type": "priority_content",
} }
else: else:
enhanced_output = { enhanced_output = {
@ -76,7 +94,7 @@ def filter_and_enhance_callback(output: Any, task: str, metadata: Dict) -> Dict:
"priority": "normal", "priority": "normal",
"execution_id": metadata["execution_count"], "execution_id": metadata["execution_count"],
"timestamp": metadata["timestamp"], "timestamp": metadata["timestamp"],
"analysis_type": "standard_content" "analysis_type": "standard_content",
} }
else: else:
enhanced_output = { enhanced_output = {
@ -84,43 +102,45 @@ def filter_and_enhance_callback(output: Any, task: str, metadata: Dict) -> Dict:
"priority": "unknown", "priority": "unknown",
"execution_id": metadata["execution_count"], "execution_id": metadata["execution_count"],
"timestamp": metadata["timestamp"], "timestamp": metadata["timestamp"],
"analysis_type": "non_string_content" "analysis_type": "non_string_content",
} }
return enhanced_output return enhanced_output
# Example 3: Real-time monitoring callback # Example 3: Real-time monitoring callback
class MonitoringCallback: class MonitoringCallback:
"""Callback class that provides real-time monitoring capabilities.""" """Callback class that provides real-time monitoring capabilities."""
def __init__(self): def __init__(self):
self.output_history = [] self.output_history = []
self.error_count = 0 self.error_count = 0
self.success_count = 0 self.success_count = 0
self.last_execution_time = None self.last_execution_time = None
def __call__(self, output: Any, task: str, metadata: Dict) -> Dict: def __call__(
self, output: Any, task: str, metadata: Dict
) -> Dict:
"""Monitor and track execution metrics. """Monitor and track execution metrics.
Args: Args:
output: The original output from the agent output: The original output from the agent
task: The task that was executed task: The task that was executed
metadata: Job metadata metadata: Job metadata
Returns: Returns:
Dict: Output with monitoring information Dict: Output with monitoring information
""" """
current_time = time.time() current_time = time.time()
# Calculate execution time # Calculate execution time
if self.last_execution_time: if self.last_execution_time:
execution_time = current_time - self.last_execution_time execution_time = current_time - self.last_execution_time
else: else:
execution_time = 0 execution_time = 0
self.last_execution_time = current_time self.last_execution_time = current_time
# Track success/error # Track success/error
if output and output != "Error": if output and output != "Error":
self.success_count += 1 self.success_count += 1
@ -128,7 +148,7 @@ class MonitoringCallback:
else: else:
self.error_count += 1 self.error_count += 1
status = "error" status = "error"
# Store in history (keep last 100) # Store in history (keep last 100)
monitoring_data = { monitoring_data = {
"output": output, "output": output,
@ -138,40 +158,49 @@ class MonitoringCallback:
"timestamp": metadata["timestamp"], "timestamp": metadata["timestamp"],
"task": task, "task": task,
"metrics": { "metrics": {
"success_rate": self.success_count / (self.success_count + self.error_count), "success_rate": self.success_count
"total_executions": self.success_count + self.error_count, / (self.success_count + self.error_count),
"total_executions": self.success_count
+ self.error_count,
"error_count": self.error_count, "error_count": self.error_count,
"success_count": self.success_count "success_count": self.success_count,
} },
} }
self.output_history.append(monitoring_data) self.output_history.append(monitoring_data)
if len(self.output_history) > 100: if len(self.output_history) > 100:
self.output_history.pop(0) self.output_history.pop(0)
return monitoring_data return monitoring_data
def get_summary(self) -> Dict: def get_summary(self) -> Dict:
"""Get monitoring summary.""" """Get monitoring summary."""
return { return {
"total_executions": self.success_count + self.error_count, "total_executions": self.success_count + self.error_count,
"success_count": self.success_count, "success_count": self.success_count,
"error_count": self.error_count, "error_count": self.error_count,
"success_rate": self.success_count / (self.success_count + self.error_count) if (self.success_count + self.error_count) > 0 else 0, "success_rate": (
self.success_count
/ (self.success_count + self.error_count)
if (self.success_count + self.error_count) > 0
else 0
),
"history_length": len(self.output_history), "history_length": len(self.output_history),
"last_execution_time": self.last_execution_time "last_execution_time": self.last_execution_time,
} }
# Example 4: API integration callback # Example 4: API integration callback
def api_webhook_callback(output: Any, task: str, metadata: Dict) -> Dict: def api_webhook_callback(
output: Any, task: str, metadata: Dict
) -> Dict:
"""Callback that could send output to an external API. """Callback that could send output to an external API.
Args: Args:
output: The original output from the agent output: The original output from the agent
task: The task that was executed task: The task that was executed
metadata: Job metadata metadata: Job metadata
Returns: Returns:
Dict: Output with API integration metadata Dict: Output with API integration metadata
""" """
@ -182,45 +211,47 @@ def api_webhook_callback(output: Any, task: str, metadata: Dict) -> Dict:
"job_id": metadata["job_id"], "job_id": metadata["job_id"],
"execution_id": metadata["execution_count"], "execution_id": metadata["execution_count"],
"timestamp": metadata["timestamp"], "timestamp": metadata["timestamp"],
"task": task "task": task,
} }
# Simulate API call (replace with actual HTTP request) # Simulate API call (replace with actual HTTP request)
logger.info(f"Would send to API: {json.dumps(api_payload, indent=2)}") logger.info(
f"Would send to API: {json.dumps(api_payload, indent=2)}"
)
return { return {
"output": output, "output": output,
"api_status": "sent", "api_status": "sent",
"api_payload": api_payload, "api_payload": api_payload,
"execution_id": metadata["execution_count"] "execution_id": metadata["execution_count"],
} }
def main(): def main():
"""Demonstrate different callback usage patterns.""" """Demonstrate different callback usage patterns."""
logger.info("🚀 Starting Callback CronJob Examples") logger.info("🚀 Starting Callback CronJob Examples")
# Create the agent # Create the agent
agent = create_sample_agent() agent = create_sample_agent()
# Example 1: Simple transformation callback # Example 1: Simple transformation callback
logger.info("📝 Example 1: Simple Output Transformation") logger.info("📝 Example 1: Simple Output Transformation")
transform_cron = CronJob( transform_cron = CronJob(
agent=agent, agent=agent,
interval="15seconds", interval="15seconds",
job_id="transform-example", job_id="transform-example",
callback=transform_output_callback callback=transform_output_callback,
) )
# Example 2: Filtering and enhancement callback # Example 2: Filtering and enhancement callback
logger.info("🔍 Example 2: Output Filtering and Enhancement") logger.info("🔍 Example 2: Output Filtering and Enhancement")
filter_cron = CronJob( filter_cron = CronJob(
agent=agent, agent=agent,
interval="20seconds", interval="20seconds",
job_id="filter-example", job_id="filter-example",
callback=filter_and_enhance_callback callback=filter_and_enhance_callback,
) )
# Example 3: Monitoring callback # Example 3: Monitoring callback
logger.info("📊 Example 3: Real-time Monitoring") logger.info("📊 Example 3: Real-time Monitoring")
monitoring_callback = MonitoringCallback() monitoring_callback = MonitoringCallback()
@ -228,85 +259,98 @@ def main():
agent=agent, agent=agent,
interval="25seconds", interval="25seconds",
job_id="monitoring-example", job_id="monitoring-example",
callback=monitoring_callback callback=monitoring_callback,
) )
# Example 4: API integration callback # Example 4: API integration callback
logger.info("🌐 Example 4: API Integration") logger.info("🌐 Example 4: API Integration")
api_cron = CronJob( api_cron = CronJob(
agent=agent, agent=agent,
interval="30seconds", interval="30seconds",
job_id="api-example", job_id="api-example",
callback=api_webhook_callback callback=api_webhook_callback,
) )
# Start all cron jobs # Start all cron jobs
logger.info("▶️ Starting all cron jobs...") logger.info("▶️ Starting all cron jobs...")
# Start them in separate threads to run concurrently # Start them in separate threads to run concurrently
import threading import threading
def run_cron(cron_job, task): def run_cron(cron_job, task):
try: try:
cron_job.run(task=task) cron_job.run(task=task)
except KeyboardInterrupt: except KeyboardInterrupt:
cron_job.stop() cron_job.stop()
# Start each cron job in its own thread # Start each cron job in its own thread
threads = [] threads = []
tasks = [ tasks = [
"Analyze the current market trends and provide key insights", "Analyze the current market trends and provide key insights",
"What are the most important factors affecting today's economy?", "What are the most important factors affecting today's economy?",
"Provide a summary of recent technological developments", "Provide a summary of recent technological developments",
"Analyze the impact of current events on business operations" "Analyze the impact of current events on business operations",
] ]
for i, (cron_job, task) in enumerate([ for i, (cron_job, task) in enumerate(
(transform_cron, tasks[0]), [
(filter_cron, tasks[1]), (transform_cron, tasks[0]),
(monitoring_cron, tasks[2]), (filter_cron, tasks[1]),
(api_cron, tasks[3]) (monitoring_cron, tasks[2]),
]): (api_cron, tasks[3]),
]
):
thread = threading.Thread( thread = threading.Thread(
target=run_cron, target=run_cron,
args=(cron_job, task), args=(cron_job, task),
daemon=True, daemon=True,
name=f"cron-thread-{i}" name=f"cron-thread-{i}",
) )
thread.start() thread.start()
threads.append(thread) threads.append(thread)
logger.info("✅ All cron jobs started successfully!") logger.info("✅ All cron jobs started successfully!")
logger.info("📊 Press Ctrl+C to stop and see monitoring summary") logger.info("📊 Press Ctrl+C to stop and see monitoring summary")
try: try:
# Let them run for a while # Let them run for a while
time.sleep(120) # Run for 2 minutes time.sleep(120) # Run for 2 minutes
# Show monitoring summary # Show monitoring summary
logger.info("📈 Monitoring Summary:") logger.info("📈 Monitoring Summary:")
logger.info(json.dumps(monitoring_callback.get_summary(), indent=2)) logger.info(
json.dumps(monitoring_callback.get_summary(), indent=2)
)
# Show execution stats for each cron job # Show execution stats for each cron job
for cron_job, name in [ for cron_job, name in [
(transform_cron, "Transform"), (transform_cron, "Transform"),
(filter_cron, "Filter"), (filter_cron, "Filter"),
(monitoring_cron, "Monitoring"), (monitoring_cron, "Monitoring"),
(api_cron, "API") (api_cron, "API"),
]: ]:
stats = cron_job.get_execution_stats() stats = cron_job.get_execution_stats()
logger.info(f"{name} Cron Stats: {json.dumps(stats, indent=2)}") logger.info(
f"{name} Cron Stats: {json.dumps(stats, indent=2)}"
)
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info("⏹️ Stopping all cron jobs...") logger.info("⏹️ Stopping all cron jobs...")
# Stop all cron jobs # Stop all cron jobs
for cron_job in [transform_cron, filter_cron, monitoring_cron, api_cron]: for cron_job in [
transform_cron,
filter_cron,
monitoring_cron,
api_cron,
]:
cron_job.stop() cron_job.stop()
# Show final monitoring summary # Show final monitoring summary
logger.info("📊 Final Monitoring Summary:") logger.info("📊 Final Monitoring Summary:")
logger.info(json.dumps(monitoring_callback.get_summary(), indent=2)) logger.info(
json.dumps(monitoring_callback.get_summary(), indent=2)
)
if __name__ == "__main__": if __name__ == "__main__":

@ -6,7 +6,6 @@ in CronJob to customize output while the job is running.
""" """
import json import json
import time
from datetime import datetime from datetime import datetime
from loguru import logger from loguru import logger
@ -26,42 +25,46 @@ def create_simple_agent():
def simple_callback(output, task, metadata): def simple_callback(output, task, metadata):
"""Simple callback that adds metadata to the output. """Simple callback that adds metadata to the output.
Args: Args:
output: The original output from the agent output: The original output from the agent
task: The task that was executed task: The task that was executed
metadata: Job metadata (execution count, timestamp, etc.) metadata: Job metadata (execution count, timestamp, etc.)
Returns: Returns:
dict: Enhanced output with metadata dict: Enhanced output with metadata
""" """
return { return {
"agent_output": output, "agent_output": output,
"execution_number": metadata["execution_count"], "execution_number": metadata["execution_count"],
"timestamp": datetime.fromtimestamp(metadata["timestamp"]).isoformat(), "timestamp": datetime.fromtimestamp(
metadata["timestamp"]
).isoformat(),
"task": task, "task": task,
"job_id": metadata["job_id"] "job_id": metadata["job_id"],
} }
def main(): def main():
"""Demonstrate basic callback usage.""" """Demonstrate basic callback usage."""
logger.info("🚀 Starting Simple Callback Example") logger.info("🚀 Starting Simple Callback Example")
# Create agent and cron job with callback # Create agent and cron job with callback
agent = create_simple_agent() agent = create_simple_agent()
cron_job = CronJob( cron_job = CronJob(
agent=agent, agent=agent,
interval="10seconds", interval="10seconds",
job_id="simple-callback-example", job_id="simple-callback-example",
callback=simple_callback callback=simple_callback,
) )
logger.info("▶️ Starting cron job with callback...") logger.info("▶️ Starting cron job with callback...")
logger.info("📝 The callback will enhance each output with metadata") logger.info(
"📝 The callback will enhance each output with metadata"
)
logger.info("⏹️ Press Ctrl+C to stop") logger.info("⏹️ Press Ctrl+C to stop")
try: try:
# Start the cron job # Start the cron job
cron_job.run( cron_job.run(
@ -70,7 +73,7 @@ def main():
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info("⏹️ Stopping cron job...") logger.info("⏹️ Stopping cron job...")
cron_job.stop() cron_job.stop()
# Show execution statistics # Show execution statistics
stats = cron_job.get_execution_stats() stats = cron_job.get_execution_stats()
logger.info("📊 Final Statistics:") logger.info("📊 Final Statistics:")

@ -1,4 +1,3 @@
# crypto_price_server.py
from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp import FastMCP
import requests import requests
@ -113,4 +112,4 @@ def get_htx_crypto_price(symbol: str) -> str:
if __name__ == "__main__": if __name__ == "__main__":
mcp.run(transport="sse") mcp.run()

@ -36,12 +36,13 @@ def get_reward(input: str) -> int:
"excellent", "excellent",
"perfect", "perfect",
] ]
if any(word in input.lower() for word in words): if any(word in input.lower() for word in words):
return 1 return 1
else: else:
return 0 return 0
def get_agent_judge_prompt() -> str: def get_agent_judge_prompt() -> str:
""" """
Returns the main system prompt for the agent judge. Returns the main system prompt for the agent judge.
@ -373,7 +374,7 @@ class AgentJudge:
return get_reward(self.conversation.get_str()) return get_reward(self.conversation.get_str())
else: else:
return self.conversation.get_str() return self.conversation.get_str()
except Exception as e: except Exception as e:
error_message = f"AgentJudge: {self.agent_name} encountered an error: {e}\n Traceback: {traceback.format_exc()}" error_message = f"AgentJudge: {self.agent_name} encountered an error: {e}\n Traceback: {traceback.format_exc()}"
raise AgentJudgeExecutionError(error_message) raise AgentJudgeExecutionError(error_message)

@ -260,16 +260,16 @@ class CronJob:
""" """
try: try:
logger.debug(f"Executing task for job {self.job_id}") logger.debug(f"Executing task for job {self.job_id}")
# Execute the agent # Execute the agent
if isinstance(self.agent, Callable): if isinstance(self.agent, Callable):
original_output = self.agent.run(task=task, **kwargs) original_output = self.agent.run(task=task, **kwargs)
else: else:
original_output = self.agent(task, **kwargs) original_output = self.agent(task, **kwargs)
# Increment execution count # Increment execution count
self.execution_count += 1 self.execution_count += 1
# Prepare metadata for callback # Prepare metadata for callback
metadata = { metadata = {
"job_id": self.job_id, "job_id": self.job_id,
@ -278,22 +278,28 @@ class CronJob:
"task": task, "task": task,
"kwargs": kwargs, "kwargs": kwargs,
"start_time": self.start_time, "start_time": self.start_time,
"is_running": self.is_running "is_running": self.is_running,
} }
# Apply callback if provided # Apply callback if provided
if self.callback: if self.callback:
try: try:
customized_output = self.callback(original_output, task, metadata) customized_output = self.callback(
logger.debug(f"Callback applied to job {self.job_id}, execution {self.execution_count}") original_output, task, metadata
)
logger.debug(
f"Callback applied to job {self.job_id}, execution {self.execution_count}"
)
return customized_output return customized_output
except Exception as callback_error: except Exception as callback_error:
logger.warning(f"Callback failed for job {self.job_id}: {callback_error}") logger.warning(
f"Callback failed for job {self.job_id}: {callback_error}"
)
# Return original output if callback fails # Return original output if callback fails
return original_output return original_output
return original_output return original_output
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Task execution failed for job {self.job_id}: {str(e)}" f"Task execution failed for job {self.job_id}: {str(e)}"
@ -406,17 +412,17 @@ class CronJob:
def set_callback(self, callback: Callable[[Any, str, dict], Any]): def set_callback(self, callback: Callable[[Any, str, dict], Any]):
"""Set or update the callback function for output customization. """Set or update the callback function for output customization.
Args: Args:
callback: Function to customize output processing. callback: Function to customize output processing.
Signature: callback(output: Any, task: str, metadata: dict) -> Any Signature: callback(output: Any, task: str, metadata: dict) -> Any
""" """
self.callback = callback self.callback = callback
logger.info(f"Callback updated for job {self.job_id}") logger.info(f"Callback updated for job {self.job_id}")
def get_execution_stats(self) -> dict: def get_execution_stats(self) -> dict:
"""Get execution statistics for the cron job. """Get execution statistics for the cron job.
Returns: Returns:
dict: Statistics including execution count, start time, running status, etc. dict: Statistics including execution count, start time, running status, etc.
""" """
@ -425,8 +431,12 @@ class CronJob:
"is_running": self.is_running, "is_running": self.is_running,
"execution_count": self.execution_count, "execution_count": self.execution_count,
"start_time": self.start_time, "start_time": self.start_time,
"uptime": time.time() - self.start_time if self.start_time else 0, "uptime": (
"interval": self.interval time.time() - self.start_time
if self.start_time
else 0
),
"interval": self.interval,
} }

Loading…
Cancel
Save