Spaces:
Runtime error
Runtime error
File size: 5,974 Bytes
48a7f49 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# MCP Sentiment Analysis - Solution
## Problem Summary
Your original `working_mcp_test.py` script was hanging because of an issue with the MCP (Model Context Protocol) connection process. Specifically:
1. β
**STDIO client connection** - This worked fine (0.0s)
2. β
**ClientSession creation** - This also worked fine
3. β **Session initialization** - This was timing out after 30-45 seconds
The issue was in the `session.initialize()` step, which handles the MCP protocol handshake between your client and the remote server.
## Root Cause
The problem was using the **wrong MCP client**:
- β **Low-level `mcp.ClientSession`** - requires manual protocol handling and times out
- β
**High-level `smolagents.mcp_client.MCPClient`** - handles all protocol complexity automatically
Based on the [Hugging Face MCP Course](https://huggingface.co/learn/mcp-course/unit2/gradio-client), the `smolagents` library provides the proper high-level interface for MCP connections.
## β
PRIMARY SOLUTION: smolagents MCPClient
**This is the best solution** - fast, reliable, and uses proper MCP protocol.
### Installation
```bash
pdm add "smolagents[mcp]"
```
### Code: `usage/sentiment_mcp.py`
```python
#!/usr/bin/env python3
"""
MCP Sentiment Analysis using smolagents MCPClient.
To run this script:
pdm run python usage/sentiment_mcp.py
"""
import time
from smolagents.mcp_client import MCPClient
def analyze_sentiment_mcp(text):
"""Analyze sentiment using MCP protocol."""
mcp_client = None
try:
mcp_client = MCPClient(
{"url": "https://freemansel-mcp-sentiment.hf.space/gradio_api/mcp/sse"}
)
tools = mcp_client.get_tools()
sentiment_tool = tools[0] # The sentiment analysis tool
result = sentiment_tool(text=text)
return result
finally:
if mcp_client:
mcp_client.disconnect()
def main():
test_texts = [
"I love this product! It's amazing!",
"This is terrible. I hate it.",
"It's okay, nothing special.",
]
for i, text in enumerate(test_texts, 1):
print(f"Test {i}: '{text}'")
start_time = time.time()
result = analyze_sentiment_mcp(text)
elapsed = time.time() - start_time
print(f" π Polarity: {result['polarity']}")
print(f" π Subjectivity: {result['subjectivity']}")
print(f" π Assessment: {result['assessment']}")
print(f" β±οΈ Time: {elapsed:.2f}s")
print()
if __name__ == "__main__":
main()
```
### Results with smolagents
```
Test 1: 'I love this product! It's amazing!'
π Polarity: 0.69
π Subjectivity: 0.75
π Assessment: positive
β±οΈ Time: 0.11s
Test 2: 'This is terrible. I hate it.'
π Polarity: -0.9
π Subjectivity: 0.95
π Assessment: negative
β±οΈ Time: 0.11s
```
**Performance:** ~0.11 seconds per request! π
## π BACKUP SOLUTION: Gradio Client
If you prefer not to use MCP protocol, the Gradio client approach also works reliably.
### File: `usage/sentiment_gradio.py`
```python
#!/usr/bin/env python3
"""
Gradio Sentiment Analysis (Backup Solution).
To run this script:
pdm run python usage/sentiment_gradio.py
"""
import time
from gradio_client import Client
def analyze_sentiment_gradio(text):
"""Analyze sentiment using Gradio client."""
client = Client("https://freemansel-mcp-sentiment.hf.space")
result = client.predict(text, api_name="/predict")
return result
def main():
test_texts = [
"I love this product! It's amazing!",
"This is terrible. I hate it.",
"It's okay, nothing special.",
]
client = Client("https://freemansel-mcp-sentiment.hf.space")
for i, text in enumerate(test_texts, 1):
print(f"Test {i}: '{text}'")
start_time = time.time()
result = client.predict(text, api_name="/predict")
elapsed = time.time() - start_time
print(f" π Polarity: {result.get('polarity', 'N/A')}")
print(f" π Subjectivity: {result.get('subjectivity', 'N/A')}")
print(f" π Assessment: {result.get('assessment', 'N/A')}")
print(f" β±οΈ Time: {elapsed:.2f}s")
print()
if __name__ == "__main__":
main()
```
**Performance:** ~1.3 seconds per request.
## Comparison
| Method | Setup | Speed | Protocol | Recommended |
|--------|-------|-------|----------|-------------|
| **smolagents MCP** | `pdm add "smolagents[mcp]"` | **0.11s** | β
Native MCP | β **Best** |
| Gradio Client | `gradio_client` (already installed) | 1.3s | Direct API | β
Good backup |
| Low-level MCP | β | β Timeout | β Broken | β Don't use |
## Running the Solutions
### Primary (smolagents):
```bash
cd /c/Users/phil7/Code/mcp-sentiment
pdm add "smolagents[mcp]" # If not already installed
pdm run python usage/sentiment_mcp.py
```
### Backup (Gradio):
```bash
cd /c/Users/phil7/Code/mcp-sentiment
pdm run python usage/sentiment_gradio.py
```
### Debugging:
```bash
# If you have import issues
pdm run python usage/debug_imports.py
```
## Key Learnings
1. **Use High-Level Clients**: Always prefer `smolagents.MCPClient` over low-level `mcp.ClientSession`
2. **Follow Official Docs**: The [Hugging Face MCP Course](https://huggingface.co/learn/mcp-course/unit2/gradio-client) provides the correct approach
3. **MCP Works Great**: When used properly, MCP is actually faster than direct API calls!
4. **Protocol Abstraction Matters**: High-level libraries handle complex protocol details
## Conclusion
The **smolagents MCPClient** is the optimal solution, providing:
- β
**Fastest performance** (0.11s vs 1.3s)
- β
**Proper MCP protocol usage**
- β
**No connection issues**
- β
**Clean, maintainable code**
The original issue was simply using the wrong level of MCP client. The Hugging Face documentation showed us the right way! π |