mcp-sentiment / usage /sentiment_mcp_core_usage.py
phil71x
feat: Introduce new sentiment analysis scripts and rename other scripts . Enhance documentation
23d394c
#!/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"
)