|
| 1 | +""" |
| 2 | +Observability Example MCP App |
| 3 | +
|
| 4 | +This example demonstrates a very basic MCP app with observability features using OpenTelemetry. |
| 5 | +
|
| 6 | +mcp-agent automatically instruments workflows (runs, tasks/activities), tool calls, LLM calls, and more, |
| 7 | +allowing you to trace and monitor the execution of your app. You can also add custom tracing spans as needed. |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +import asyncio |
| 12 | +from typing import List, Optional |
| 13 | + |
| 14 | +from opentelemetry import trace |
| 15 | + |
| 16 | +from mcp_agent.agents.agent import Agent |
| 17 | +from mcp_agent.app import MCPApp |
| 18 | +from mcp_agent.core.context import Context as AppContext |
| 19 | +from mcp_agent.executor.workflow import Workflow |
| 20 | +from mcp_agent.server.app_server import create_mcp_server_for_app |
| 21 | +from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM |
| 22 | +from mcp_agent.workflows.parallel.parallel_llm import ParallelLLM |
| 23 | + |
| 24 | +app = MCPApp(name="observability_example_app") |
| 25 | + |
| 26 | + |
| 27 | +# You can always explicitly trace using opentelemetry as usual |
| 28 | +def get_magic_number(original_number: int = 0) -> int: |
| 29 | + tracer = trace.get_tracer(__name__) |
| 30 | + with tracer.start_as_current_span("some_tool_function") as span: |
| 31 | + span.set_attribute("example.attribute", "value") |
| 32 | + result = 42 + original_number |
| 33 | + span.set_attribute("result", result) |
| 34 | + return result |
| 35 | + |
| 36 | + |
| 37 | +# Workflows (runs, tasks/activities), tool calls, LLM calls, etc. are automatically traced by mcp-agent |
| 38 | +@app.workflow_task() |
| 39 | +async def gather_sources(query: str) -> list[str]: |
| 40 | + app.context.logger.info("Gathering sources", data={"query": query}) |
| 41 | + return [f"https://example.com/search?q={query}"] |
| 42 | + |
| 43 | + |
| 44 | +@app.workflow |
| 45 | +class ResearchWorkflow(Workflow[None]): |
| 46 | + @app.workflow_run |
| 47 | + async def run(self, topic: str) -> List[str]: |
| 48 | + sources = await self.context.executor.execute(gather_sources, topic) |
| 49 | + self.context.logger.info( |
| 50 | + "Workflow completed", data={"topic": topic, "sources": sources} |
| 51 | + ) |
| 52 | + return sources |
| 53 | + |
| 54 | + |
| 55 | +@app.async_tool(name="grade_story_async") |
| 56 | +async def grade_story_async(story: str, app_ctx: Optional[AppContext] = None) -> str: |
| 57 | + """ |
| 58 | + Async variant of grade_story that starts a workflow run and returns IDs. |
| 59 | + Args: |
| 60 | + story: The student's short story to grade |
| 61 | + app_ctx: Optional MCPApp context for accessing app resources and logging |
| 62 | + """ |
| 63 | + |
| 64 | + context = app_ctx or app.context |
| 65 | + await context.info(f"[grade_story_async] Received input: {story}") |
| 66 | + |
| 67 | + magic_number = get_magic_number(10) |
| 68 | + await context.info(f"[grade_story_async] Magic number computed: {magic_number}") |
| 69 | + |
| 70 | + proofreader = Agent( |
| 71 | + name="proofreader", |
| 72 | + instruction="""Review the short story for grammar, spelling, and punctuation errors. |
| 73 | + Identify any awkward phrasing or structural issues that could improve clarity. |
| 74 | + Provide detailed feedback on corrections.""", |
| 75 | + ) |
| 76 | + |
| 77 | + fact_checker = Agent( |
| 78 | + name="fact_checker", |
| 79 | + instruction="""Verify the factual consistency within the story. Identify any contradictions, |
| 80 | + logical inconsistencies, or inaccuracies in the plot, character actions, or setting. |
| 81 | + Highlight potential issues with reasoning or coherence.""", |
| 82 | + ) |
| 83 | + |
| 84 | + style_enforcer = Agent( |
| 85 | + name="style_enforcer", |
| 86 | + instruction="""Analyze the story for adherence to style guidelines. |
| 87 | + Evaluate the narrative flow, clarity of expression, and tone. Suggest improvements to |
| 88 | + enhance storytelling, readability, and engagement.""", |
| 89 | + ) |
| 90 | + |
| 91 | + grader = Agent( |
| 92 | + name="grader", |
| 93 | + instruction="""Compile the feedback from the Proofreader and Fact Checker |
| 94 | + into a structured report. Summarize key issues and categorize them by type. |
| 95 | + Provide actionable recommendations for improving the story, |
| 96 | + and give an overall grade based on the feedback.""", |
| 97 | + ) |
| 98 | + |
| 99 | + parallel = ParallelLLM( |
| 100 | + fan_in_agent=grader, |
| 101 | + fan_out_agents=[proofreader, fact_checker, style_enforcer], |
| 102 | + llm_factory=OpenAIAugmentedLLM, |
| 103 | + context=context, |
| 104 | + ) |
| 105 | + |
| 106 | + await context.info("[grade_story_async] Starting parallel LLM") |
| 107 | + |
| 108 | + try: |
| 109 | + result = await parallel.generate_str( |
| 110 | + message=f"Student short story submission: {story}", |
| 111 | + ) |
| 112 | + except Exception as e: |
| 113 | + await context.error(f"[grade_story_async] Error generating result: {e}") |
| 114 | + return "" |
| 115 | + |
| 116 | + if not result: |
| 117 | + await context.error("[grade_story_async] No result from parallel LLM") |
| 118 | + return "" |
| 119 | + |
| 120 | + return result |
| 121 | + |
| 122 | + |
| 123 | +# NOTE: This main function is useful for local testing but will be ignored in the cloud deployment. |
| 124 | +async def main(): |
| 125 | + async with app.run() as agent_app: |
| 126 | + mcp_server = create_mcp_server_for_app(agent_app) |
| 127 | + await mcp_server.run_sse_async() |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + asyncio.run(main()) |
0 commit comments