#!/usr/bin/env python3 """ MCP Sentiment Analysis using smolagents MCPClient. This script provides sentiment analysis using the proper MCP protocol implementation through the smolagents library. It's the fastest and most reliable solution. Performance: ~0.11 seconds per request Protocol: Native MCP via smolagents To run this script: pdm run python usage/sentiment_mcp.py Dependencies: - smolagents[mcp] (install with: pdm add "smolagents[mcp]") Based on Hugging Face MCP Course: https://huggingface.co/learn/mcp-course/unit2/gradio-client """ import time try: from smolagents.mcp_client import MCPClient SMOLAGENTS_AVAILABLE = True except ImportError: MCPClient = None SMOLAGENTS_AVAILABLE = False def test_mcp_sentiment_analysis(): """Test MCP connection using smolagents MCPClient.""" print("๐Ÿงช MCP Sentiment Analysis (smolagents)") print("=" * 45) print("Using smolagents.mcp_client.MCPClient for proper MCP connection.") print("Based on: https://huggingface.co/learn/mcp-course/unit2/gradio-client") print() if not SMOLAGENTS_AVAILABLE: print("โŒ smolagents not available") print("Install with: pdm add 'smolagents[mcp]'") return False print("โœ… smolagents imported successfully") # Test texts test_texts = [ "I love this product! It's amazing!", "This is terrible. I hate it.", "It's okay, nothing special.", "The weather is beautiful today!", "I'm feeling quite neutral about this.", ] mcp_client = None try: print("โณ Connecting to MCP server via smolagents...") # Use MCPClient with the SSE endpoint - this handles the protocol properly mcp_client = MCPClient( {"url": "https://freemansel-mcp-sentiment.hf.space/gradio_api/mcp/sse"} ) print("โœ… MCP client created successfully!") print("โณ Getting available tools...") tools = mcp_client.get_tools() print(f"โœ… Found {len(tools)} tools:") print("\n".join(f" โ€ข {tool.name}: {tool.description}" for tool in tools)) print() # Test sentiment analysis with each text for i, text in enumerate(test_texts, 1): print(f"Test {i}: '{text}'") start_time = time.time() try: # Find the sentiment analysis tool sentiment_tool = None for tool in tools: if "sentiment" in tool.name.lower(): sentiment_tool = tool break if sentiment_tool: print(f" โณ Using tool: {sentiment_tool.name}") # Call the tool with the text result = sentiment_tool(text=text) elapsed = time.time() - start_time print(f" โœ… Result: {result}") print(f" โฑ๏ธ Time: {elapsed:.2f}s") else: print(" โŒ No sentiment analysis tool found") # Let's try the first tool available if tools: print(f" ๐Ÿ”„ Trying first available tool: {tools[0].name}") result = tools[0](text=text) elapsed = time.time() - start_time print(f" โœ… Result: {result}") print(f" โฑ๏ธ Time: {elapsed:.2f}s") except Exception as e: # pylint: disable=broad-except elapsed = time.time() - start_time print(f" โŒ Error after {elapsed:.2f}s: {e}") print() print("๐ŸŽ‰ MCP sentiment analysis completed!") return True except Exception as e: # pylint: disable=broad-except print(f"โŒ Failed to connect with smolagents: {e}") print(f"Error type: {type(e).__name__}") print("\nTroubleshooting:") print("1. Make sure smolagents is installed: pdm add 'smolagents[mcp]'") print("2. Check that the MCP server endpoint is accessible") print("3. The server might be having protocol issues") return False finally: if mcp_client: try: mcp_client.disconnect() print("โœ… MCP client disconnected properly") except Exception as e: # pylint: disable=broad-except print(f"โš ๏ธ Disconnect warning: {e}") def check_smolagents(): """Check if smolagents is available.""" if SMOLAGENTS_AVAILABLE: print("โœ… smolagents is available") return True print("โŒ smolagents not found") print("Install with: pdm add 'smolagents[mcp]'") return False if __name__ == "__main__": print("๐Ÿš€ MCP Sentiment Analysis with smolagents") print("Using the approach from Hugging Face MCP Course") print("=" * 60) # First check if smolagents is available if not check_smolagents(): print("\nPlease install smolagents:") print("pdm add 'smolagents[mcp]'") exit(1) # Now try the MCP connection success = test_mcp_sentiment_analysis() if success: print("\n๐ŸŽ‰ Success! smolagents MCPClient works!") print("This confirms the MCP server is working with the proper client.") print("The issue was using the low-level MCP client instead of smolagents.") else: print("\nโš ๏ธ smolagents approach had issues.") print("This suggests the MCP server itself might have protocol problems.") print( "Try the Gradio client solution: pdm run python usage/sentiment_gradio.py" )