|
| 1 | +import os |
| 2 | + |
| 3 | +from llama_index.core.agent.workflow import FunctionAgent |
| 4 | +from llama_index.core.workflow import ( |
| 5 | + StartEvent, |
| 6 | + StopEvent, |
| 7 | + Workflow, |
| 8 | + step, |
| 9 | +) |
| 10 | +from llama_index.llms.openai import OpenAI |
| 11 | +from llama_index.tools.mcp import McpToolSpec |
| 12 | +from mcp import ClientSession |
| 13 | +from mcp.client.sse import sse_client |
| 14 | + |
| 15 | + |
| 16 | +# Define events |
| 17 | +class UserQueryEvent(StartEvent): |
| 18 | + """Event representing a user query to the MCP agent.""" |
| 19 | + |
| 20 | + query: str |
| 21 | + |
| 22 | + |
| 23 | +class AgentResponseEvent(StopEvent): |
| 24 | + """Event representing the agent's response.""" |
| 25 | + |
| 26 | + response: str |
| 27 | + |
| 28 | + |
| 29 | +# Define the workflow |
| 30 | +class MCPAgentWorkflow(Workflow): |
| 31 | + """Workflow that uses MCP tools to respond to user queries.""" |
| 32 | + |
| 33 | + @step |
| 34 | + async def process_query(self, ev: UserQueryEvent) -> AgentResponseEvent: |
| 35 | + """Process the user query using the MCP-enabled agent.""" |
| 36 | + |
| 37 | + # Initialize MCP client and tools |
| 38 | + async with sse_client( |
| 39 | + url=os.getenv("UIPATH_MCP_SERVER_URL"), |
| 40 | + headers={"Authorization": f"Bearer {os.getenv('UIPATH_ACCESS_TOKEN')}"}, |
| 41 | + timeout=60, |
| 42 | + ) as (read, write): |
| 43 | + async with ClientSession(read, write) as client_session: |
| 44 | + await client_session.initialize() |
| 45 | + mcp_tool_spec = McpToolSpec(client=client_session) |
| 46 | + tools = await mcp_tool_spec.to_tool_list_async() |
| 47 | + |
| 48 | + # Initialize the agent |
| 49 | + self.agent = FunctionAgent( |
| 50 | + name="UiPath MCP Agent", |
| 51 | + description="An agent that can interact with MCP tools", |
| 52 | + llm=OpenAI(model="gpt-4o"), |
| 53 | + tools=tools, |
| 54 | + system_prompt="""You are a helpful assistant. |
| 55 | + You have access to various tools through MCP (Model Context Protocol). |
| 56 | + Use these tools to help users with their tasks. |
| 57 | +
|
| 58 | + Always be helpful and provide clear, actionable responses.""", |
| 59 | + ) |
| 60 | + |
| 61 | + response = await self.agent.run(user_msg=ev.query) |
| 62 | + |
| 63 | + return AgentResponseEvent(response=str(response)) |
| 64 | + |
| 65 | + |
| 66 | +workflow = MCPAgentWorkflow(timeout=300, verbose=True) |
0 commit comments