test_mcp_server / tools /sentiment_tool.py
SrikanthNagelli's picture
initial commit
b0979b9
"""
Sentiment analysis tool for MCP server.
"""
from smolagents import Tool
from textblob import TextBlob
class SentimentTool(Tool):
"""Tool for analyzing text sentiment using TextBlob."""
def __init__(self):
self.name = "sentiment_analysis"
self.description = "Analyze the sentiment of the given text"
self.input_type = "object"
self.output_type = "object"
self.inputs = {
"text": {
"type": "string",
"description": "The text to analyze"
}
}
self.outputs = {
"polarity": {
"type": "number",
"description": "Sentiment polarity (-1 to 1)"
},
"subjectivity": {
"type": "number",
"description": "Sentiment subjectivity (0 to 1)"
},
"assessment": {
"type": "string",
"description": "Overall sentiment assessment"
}
}
self.required_inputs = ["text"]
self.is_initialized = True
def forward(self, text: str) -> dict:
"""Analyze sentiment and return structured results."""
try:
blob = TextBlob(text)
sentiment = blob.sentiment
# Determine assessment
if sentiment.polarity > 0.1:
assessment = "positive"
elif sentiment.polarity < -0.1:
assessment = "negative"
else:
assessment = "neutral"
return {
"polarity": round(sentiment.polarity, 3),
"subjectivity": round(sentiment.subjectivity, 3),
"assessment": assessment,
"text": text
}
except Exception as e:
return {"error": f"Failed to analyze sentiment: {str(e)}"}