# XMCPX - Twitter/X MCP Server

XMCPX is a Model Context Protocol (MCP) server that provides Twitter/X integration for AI agents. It enables agents to interact with Twitter through a standardized protocol, supporting operations like posting tweets, searching, following users, and more.

## Features

- 🔐 **Cookie-based authentication** with persistent session management
- 🤖 **Full Twitter API integration** via agent-twitter-client
- 🔄 **Automatic session recovery** and cookie refresh
- 📊 **Database-backed session persistence** (PostgreSQL/Supabase)
- 🎯 **Grok AI integration** for X's native AI assistant
- 🚀 **MCP-compliant** stdio communication protocol
- 🛡️ **Rate limiting** and error handling
- 📱 **Telegram raid coordination** for community engagement campaigns
- 🏆 **Leaderboards and gamification** for raid participants
- ✅ **Participation verification** with point rewards

## Installation

```bash
npm install @promptordie/xmcpx
```

## Quick Start

### 1. Set up environment variables

Create a `.env` file with your Twitter credentials:

```env
# Twitter Authentication
TWITTER_USERNAME=your_username
TWITTER_PASSWORD=your_password
TWITTER_EMAIL=your_email@example.com
AUTH_METHOD=cookies

# Database (optional, for session persistence)
DATABASE_URL=postgresql://user:pass@host:5432/db

# Server Configuration
PORT=3011
NODE_ENV=production
```

### 2. Using with ElizaOS

Add XMCPX to your ElizaOS character configuration:

```typescript
import { Character } from "@elizaos/core";

export const characterWithMCP: Character = {
  name: "YourAgent",
  // ... other character settings
  
  plugins: [
    "@elizaos/plugin-mcp",
    // ... other plugins
  ],
  
  settings: {
    mcp: {
      servers: {
        xmcpx: {
          type: 'stdio',
          command: 'npx',
          args: ['@promptordie/xmcpx'],
          env: {
            TWITTER_USERNAME: process.env.TWITTER_USERNAME,
            TWITTER_PASSWORD: process.env.TWITTER_PASSWORD,
            TWITTER_EMAIL: process.env.TWITTER_EMAIL,
            AUTH_METHOD: 'cookies',
            DATABASE_URL: process.env.DATABASE_URL,
          }
        }
      }
    }
  }
};
```

### 3. Standalone Usage

Run XMCPX as a standalone MCP server:

```bash
npx @promptordie/xmcpx
```

The server will authenticate with Twitter and be ready to accept MCP commands via stdio.

## Available Tools

XMCPX provides the following MCP tools:

### Core Twitter Operations
- `postTweet` - Post a new tweet
- `replyToTweet` - Reply to an existing tweet
- `retweet` - Retweet a tweet
- `likeTweet` - Like or unlike a tweet
- `deleteTweet` - Delete your own tweet

### User Management
- `followUser` - Follow or unfollow a user
- `getUserProfile` - Get user profile information
- `blockUser` - Block or unblock a user
- `muteUser` - Mute or unmute a user

### Search & Discovery
- `searchTweets` - Search for tweets
- `getTrending` - Get trending topics
- `getTimeline` - Get home timeline
- `getMentions` - Get mentions of authenticated user

### Grok AI Integration
- `askGrok` - Ask questions to Grok AI on X

### Telegram Raid Coordination
- `start_telegram_raid` - Start a new raid campaign
- `monitor_telegram_raid` - Monitor active raid progress
- `get_raid_leaderboard` - View top raid participants
- `verify_raid_participation` - Verify user participation
- `end_telegram_raid` - End a raid and get final stats

## Authentication Flow

XMCPX uses a smart authentication system:

1. **Initial Login**: Uses username/password to authenticate
2. **Cookie Collection**: Captures authentication cookies
3. **Session Persistence**: Stores cookies in database (if configured)
4. **Auto-Recovery**: Automatically refreshes expired sessions

## Database Configuration (Optional)

For persistent sessions across restarts, configure a PostgreSQL database:

```sql
CREATE TABLE IF NOT EXISTS twitter_sessions (
  id SERIAL PRIMARY KEY,
  username VARCHAR(255) UNIQUE NOT NULL,
  cookies TEXT,
  csrf_token VARCHAR(255),
  auth_token VARCHAR(255),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `TWITTER_USERNAME` | Twitter username | Yes |
| `TWITTER_PASSWORD` | Twitter password | Yes |
| `TWITTER_EMAIL` | Twitter email | Yes |
| `AUTH_METHOD` | Authentication method (use 'cookies') | Yes |
| `DATABASE_URL` | PostgreSQL connection string | No |
| `PORT` | HTTP health check port | No |
| `NODE_ENV` | Environment (development/production) | No |
| `LOG_LEVEL` | Logging level (info/debug/error) | No |
| `GOOGLE_GENERATIVE_AI_API_KEY` | Google AI key for enhanced features | No |

## Error Handling

XMCPX includes comprehensive error handling:
- Automatic retry with exponential backoff
- Session recovery on authentication failures
- Graceful degradation when database is unavailable
- Detailed error messages in MCP responses

## Development

```bash
# Clone the repository
git clone https://github.com/anubis/xmcpx.git
cd xmcpx

# Install dependencies
npm install

# Build the project
npm run build

# Run in development mode
npm run dev
```

## Testing

```bash
# Run tests
npm test

# Test MCP interface
npm run test:interface

# Test cookie authentication
npm run test:cookies
```

## Docker Support

```dockerfile
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build
CMD ["node", "build/index.js"]
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License - see LICENSE file for details

## Support

For issues and questions:
- GitHub Issues: [github.com/anubis/xmcpx/issues](https://github.com/anubis/xmcpx/issues)
- Documentation: [docs.anubis.chat](https://docs.anubis.chat)

## Acknowledgments

Built with:
- [agent-twitter-client](https://github.com/ai16z/agent-twitter-client) for Twitter integration
- [Model Context Protocol SDK](https://github.com/anthropics/model-context-protocol) for MCP implementation
- [ElizaOS](https://github.com/elizaos/elizaos) for agent framework compatibility