| 78 | |
| 79 | @cl.step(type="tool") |
| 80 | async def call_tool(tool_use): |
| 81 | tool_name = tool_use.name |
| 82 | tool_input = tool_use.input |
| 83 | |
| 84 | current_step = cl.context.current_step |
| 85 | current_step.name = tool_name |
| 86 | |
| 87 | # Identify which mcp is used |
| 88 | mcp_tools = cl.user_session.get("mcp_tools", {}) |
| 89 | mcp_name = None |
| 90 | |
| 91 | for connection_name, tools in mcp_tools.items(): |
| 92 | if any(tool.get("name") == tool_name for tool in tools): |
| 93 | mcp_name = connection_name |
| 94 | break |
| 95 | |
| 96 | if not mcp_name: |
| 97 | current_step.output = json.dumps( |
| 98 | {"error": f"Tool {tool_name} not found in any MCP connection"} |
| 99 | ) |
| 100 | return current_step.output |
| 101 | |
| 102 | mcp_session, _ = cl.context.session.mcp_sessions.get(mcp_name) |
| 103 | |
| 104 | if not mcp_session: |
| 105 | current_step.output = json.dumps( |
| 106 | {"error": f"MCP {mcp_name} not found in any MCP connection"} |
| 107 | ) |
| 108 | return current_step.output |
| 109 | |
| 110 | try: |
| 111 | current_step.output = await mcp_session.call_tool(tool_name, tool_input) |
| 112 | except Exception as e: |
| 113 | current_step.output = json.dumps({"error": str(e)}) |
| 114 | |
| 115 | return current_step.output |
| 116 | |
| 117 | |
| 118 | async def call_claude(chat_messages): |