Twitter-MCP-Server-For-Claude
1
Github Watches
2
Github Forks
0
Github Stars
Building a Twitter Trends Analysis MCP Server for Claude
This tutorial will guide you through creating a Model Context Protocol (MCP) server that connects Twitter's trending topics with Claude's analysis capabilities. The server will fetch real-time Twitter trends and use Claude to analyze them for business opportunities.
Prerequisites
- Python 3.8 or higher
- Claude Desktop installed
- Twitter Developer Account with API access
- Basic understanding of Python
Part 1: Setting Up the Environment
- Create a new project directory:
mkdir twitter-trends-mcp
cd twitter-trends-mcp
- Set up a virtual environment:
python -m venv .venv
.venv\Scripts\activate # On Windows
- Install required packages:
pip install tweepy mcp python-dotenv hatchling
Part 2: Project Structure
Create the following directory structure:
twitter-trends-mcp/
├── pyproject.toml
├── twitter_server_run.py
├── src/
│ └── twitter_trends_mcp/
│ ├── __init__.py
│ └── server.py
Part 3: Configuration Files
- Create
pyproject.tomlin the root directory:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "twitter-trends-mcp"
version = "0.1.0"
description = "Twitter Trends MCP Server"
requires-python = ">=3.8"
dependencies = [
"tweepy",
"mcp",
"python-dotenv"
]
[tool.hatch.build]
packages = ["src/twitter_trends_mcp"]
include = ["src/twitter_trends_mcp/*"]
[project.scripts]
twitter-trends-server = "twitter_trends_mcp:main"
- Create
src/twitter_trends_mcp/__init__.py:
"""Twitter Trends MCP Server package."""
import asyncio
from . import server
def main():
"""Main entry point for the package."""
asyncio.run(server.main())
__all__ = ['main', 'server']
- Create entry point file
twitter_server_run.py:
#!/usr/bin/env python
import os
import sys
import logging
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('twitter_server.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger('twitter-trends-mcp')
# Add the src directory to the Python path
src_path = str(Path(__file__).parent / "src")
sys.path.insert(0, src_path)
logger.info(f"Python path: {sys.path}")
try:
from twitter_trends_mcp.server import main
logger.info("Successfully imported server module")
except Exception as e:
logger.error(f"Error importing server module: {e}")
raise
if __name__ == "__main__":
try:
logger.info("Starting server...")
import asyncio
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Server stopped by user")
except Exception as e:
logger.error(f"Server error: {e}")
raise
Part 4: Twitter API Setup
- Go to Twitter Developer Portal
- Create a new project and app
- Get your API credentials:
- API Key
- API Secret
- Access Token
- Access Token Secret
- Bearer Token
Part 5: MCP Server Implementation
Create src/twitter_trends_mcp/server.py with the complete server code, including:
- API client initialization
- Trend fetching logic
- Resource and tool handlers
- Analysis integration with Claude
Key components:
# Initialize Twitter clients
client_v2 = tweepy.Client(...)
auth = tweepy.OAuthHandler(...)
api_v1 = tweepy.API(auth)
# Define server capabilities
app = Server("twitter-trends-server")
# Implement handlers
@app.list_resources()
async def list_resources() -> list[Resource]: ...
@app.read_resource()
async def read_resource(uri: AnyUrl) -> str: ...
@app.list_tools()
async def list_tools() -> list[Tool]: ...
@app.call_tool()
async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]: ...
Part 6: Claude Desktop Configuration
-
Locate your Claude Desktop config file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
- Windows:
-
Update the configuration:
{
"mcpServers": {
"twitter-trends": {
"command": "C:\\Users\\YOUR_USERNAME\\twitter-trends-mcp\\.venv\\Scripts\\python.exe",
"args": ["C:\\Users\\YOUR_USERNAME\\twitter-trends-mcp\\twitter_server_run.py"],
"env": {
"PYTHONPATH": "C:\\Users\\YOUR_USERNAME\\twitter-trends-mcp\\src",
"PYTHONUNBUFFERED": "1"
},
"cwd": "C:\\Users\\YOUR_USERNAME\\twitter-trends-mcp"
}
}
}
Part 7: Running and Testing
- Install the package:
pip install -e .
- Run server:
python twitter_server_run.py
-
In Claude Desktop:
- Click the 🔌 icon
- Look for "twitter-trends"
- Try: "Analyze current Twitter trends for SaaS opportunities"
-
Monitor logs:
Get-Content twitter_server.log -Wait
Troubleshooting Tips
-
Common Issues:
- Module not found: Check PYTHONPATH
- Connection errors: Verify paths in config
- API errors: Validate credentials
- Server not responding: Check logs
-
Log Locations:
- Server:
twitter_server.log - Claude:
%APPDATA%\Claude\Logs\mcp*.log
- Server:
Features
- Real-time trend fetching
- Category-based analysis
- Business opportunity identification
- AI-powered insights
- Detailed logging
Best Practices
- Use absolute paths
- Keep credentials secure
- Monitor logs
- Test incrementally
- Use virtual environments
Next Steps
- Add trend history
- Implement sentiment analysis
- Support more regions
- Add business metrics
- Enhance analysis categories
相关推荐
I craft unique cereal names, stories, and ridiculously cute Cereal Baby images.
I find academic articles and books for research and literature reviews.
Evaluator for marketplace product descriptions, checks for relevancy and keyword stuffing.
Confidential guide on numerology and astrology, based of GG33 Public information
Advanced software engineer GPT that excels through nailing the basics.
Descubra la colección más completa y actualizada de servidores MCP en el mercado. Este repositorio sirve como un centro centralizado, que ofrece un extenso catálogo de servidores MCP de código abierto y propietarios, completos con características, enlaces de documentación y colaboradores.
La aplicación AI de escritorio todo en uno y Docker con trapo incorporado, agentes de IA, creador de agentes sin código, compatibilidad de MCP y más.
Plataforma de automatización de flujo de trabajo de código justo con capacidades de IA nativas. Combine el edificio visual con código personalizado, auto-anfitrión o nube, más de 400 integraciones.
Manipulación basada en Micrypthon I2C del expansor GPIO de la serie MCP, derivada de AdaFruit_MCP230xx
🧑🚀 全世界最好的 llM 资料总结(数据处理、模型训练、模型部署、 O1 模型、 MCP 、小语言模型、视觉语言模型) | Resumen de los mejores recursos del mundo.
Una lista curada de servidores de protocolo de contexto del modelo (MCP)
Espejo dehttps: //github.com/agentience/practices_mcp_server
Reviews
user_mgUm2Acz
I've been using MCP Server Example for a few months now, and it's been a game-changer. The seamless integration and intuitive interface make managing servers incredibly straightforward. The detailed documentation provided by the author, pHo9UBenaA, is also top-notch, ensuring even beginners can get up to speed quickly. Highly recommended! Check it out here: https://mcp.so/server/mcp-server-example/pHo9UBenaA