# TrendMoon MCP Server

A Model Context Protocol (MCP) server for accessing cryptocurrency and social trend data through the TrendMoon API.

## 🚀 Features

- **Library Usage**: Import and use in your own code
- **Standalone Server**: Deploy as autonomous server
- **Dual Transport**: STDIO and HTTP + Streamable support
- **Complete Tools**: Access to crypto data, messages, users, and social trends
- **Built-in Prompt**: Automated cryptocurrency performance analysis

## 📦 Installation

### As NPM Library
```bash 
npm install @trendmoon/mcp-server
```

### Global Usage
```bash
npm install -g @trendmoon/mcp-server
trendmoon-mcp-server serve [options]
```

## 🔧 Usage

### 📚 Library Mode

```typescript
import { TrendmoonMcpServer } from '@trendmoon/mcp-server';

// Create server instance
const mcpServer = new TrendmoonMcpServer({
    name: 'my-app-mcp',
    version: '1.0.0'
});

// Get MCP server for integration in your app
const server = mcpServer.getMcpServer();

// Access TrendMoon services directly
const services = mcpServer.getServices();
const coinData = await services.coin.getCoinDetails({ symbol: 'BTC' });
```

### 🖥️ Standalone Server Mode

#### CLI Options
```bash
trendmoon-mcp-server serve [options]

Options:
  -t, --transport <type>  Transport type (stdio|http) (default: "stdio")
  -p, --port <number>     HTTP port (default: "3000") 
  -h, --host <host>       HTTP host (default: "0.0.0.0")
  --no-cors              Disable CORS
```

#### STDIO Mode (for AI integration)
```bash
trendmoon-mcp-server serve --transport stdio
```

#### HTTP Mode (for web/API)
```bash
trendmoon-mcp-server serve --transport http --port 3000
```

### 🌐 HTTP Mode - Endpoints

- **POST /mcp** : Main MCP endpoint (JSON-RPC over Streamable HTTP)
- **GET /mcp** : Server-to-client notifications via SSE (requires session)
- **DELETE /mcp** : Session termination (requires session)
- **POST /** : Legacy compatibility endpoint (redirects to /mcp)
- **GET /health** : Server health check
- **GET /info** : Server information and usage details
- **Protocol**: Streamable HTTP (modern MCP transport)

For MCP Inspector, use: `http://localhost:PORT/mcp`

## 🔧 Available Tools

### Cryptocurrencies
- `searchCoins` : Search cryptocurrencies
- `getCoinDetails` : Get cryptocurrency details
- `getPlatforms` : List available platforms

### Technical Analysis (Binance)
- `getHistoricalPrice` : Historical prices with MACD
- `checkEMAPosition` : Position relative to EMA 20/50

### Social Data
- `getSocialTrend` : Crypto social trends
- `getProjectSummary` : AI project summary
- `getKeywordTrend` : Keyword trends
- `searchSocialPosts` : Search social posts
- `getSocialTrends` : Multiple social trends
- `getTopicPosts` : Posts related to specific topics
- `getTopicNews` : News related to specific topics

### Messages and Chats
- `getMessagesForChat` : Chat messages
- `searchMessages` : Search messages
- `getChatByUsername` : Chat details

### Users
- `searchUsers` : Search users
- `getUserByIdentifier` : User details

### Categories and Activity
- Tools for categories and chat activity

## 📊 Built-in Prompt

The server includes an `analyzeCoinPerformance` prompt that automatically combines:

- Cryptocurrency details
- Social trends
- AI project summary

```typescript
// Library usage
const analysis = await mcpServer.getMcpServer().prompt("analyzeCoinPerformance", { 
    symbol: "BTC", 
    timeframe: "24h" // 1h, 24h, 7d, 30d
});
```

## 🧪 Testing and Development

### MCP Inspector
```bash
npm run inspect:direct
```
Opens MCP Inspector interface at http://127.0.0.1:6274

### HTTP Testing
```bash
# Start in HTTP mode
npm run start:http:dev

# Test main MCP endpoint
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

# Test legacy endpoint (compatibility)
curl -X POST http://localhost:3000/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}'

# Health check
curl http://localhost:3000/health

# Server info
curl http://localhost:3000/info
```

### MCP Inspector Connection
When running in HTTP mode, you can connect MCP Inspector to:
```
http://localhost:3000/mcp
```

## 📁 Project Structure

```
src/
├── lib/                    # Library code
│   ├── server/
│   │   ├── TrendmoonMcpServer.ts
│   │   └── types.ts
│   ├── tools/             # MCP tools
│   └── index.ts          # Main library export
├── standalone/            # Standalone server code
│   ├── http/
│   │   └── HttpTransport.ts
│   ├── stdio/
│   │   └── StdioTransport.ts
│   └── server.ts
├── cli.ts                # Command line interface
└── index.ts             # Root entry point
```

## 🔑 Configuration

### Environment Variables

The server supports various environment variables for configuration. Copy `.env.example` to `.env` and configure as needed:

```bash
# TrendMoon API Configuration
TRENDMOON_API_URL=https://api.qa.trendmoon.ai
TRENDMOON_API_KEY=xxxxxxxxx

# LLM Configuration (for AI features)
LLM_API_KEY="sk-xxxx"
LLM_BASE_URL="https://openrouter.ai/api/v1"
LLM_MODEL_NAME="openai/gpt-3.5-turbo"

# Debug and Development
DEBUG_MODE=false
```

#### Environment Variables Reference

| Variable | Description | Required | Default          |
|----------|-------------|----------|------------------|
| `TRENDMOON_API_URL` | TrendMoon API base URL | No       | https://api.qa.trendmoon.ai |
| `TRENDMOON_API_KEY` | Your TrendMoon API key for authentication | Yes      | -          |
| `LLM_API_KEY` | API key for LLM provider (OpenRouter, OpenAI, etc.) | Yes      | -                |
| `LLM_BASE_URL` | Base URL for LLM API calls | No       | https://api.openai.com/v1                 |
| `LLM_MODEL_NAME` | Model name to use for AI features | No       | gpt-3.5-turbo                 |
| `DEBUG_MODE` | Enable debug logging and verbose output | No       | `false`          |

#### API Key Setup

1. **TrendMoon API Key**:
    - Sign up at [TrendMoon](https://trendmoon.app)
    - Get your API key from the dashboard
    - Set `TRENDMOON_API_KEY` environment variable

2. **LLM API Key** (for enhanced AI features):
    - For OpenRouter: Get key from [OpenRouter](https://openrouter.ai/)
    - For direct OpenAI: Get key from [OpenAI](https://platform.openai.com/)
    - Set `LLM_API_KEY` and configure `LLM_BASE_URL` accordingly

#### Environment Setup Examples

**Development (.env)**:
```bash
TRENDMOON_API_URL=https://api.qa.trendmoon.ai
TRENDMOON_API_KEY=your-dev-api-key
LLM_API_KEY="sk-your-openrouter-key"
LLM_BASE_URL="https://openrouter.ai/api/v1"
LLM_MODEL_NAME="openai/gpt-3.5-turbo"
DEBUG_MODE=true
```

**Production**:
```bash
TRENDMOON_API_URL=https://api.trendmoon.app
TRENDMOON_API_KEY=your-prod-api-key
LLM_API_KEY="sk-your-production-key"
LLM_BASE_URL="https://openrouter.ai/api/v1"
LLM_MODEL_NAME="openai/gpt-4"
DEBUG_MODE=false
```

## 🚀 Deployment

### Docker
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
EXPOSE 3000
CMD ["npm", "run", "start:http"]
```

### Docker Compose
```yaml
version: '3.8'
services:
  trendmoon-mcp:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - TRENDMOON_API_URL=https://api.trendmoon.app
      - TRENDMOON_API_KEY=xxxxxxx
      - LLM_API_KEY=sk-your-api-key
      - LLM_BASE_URL=https://openrouter.ai/api/v1
      - LLM_MODEL_NAME=openai/gpt-4
      - DEBUG_MODE=false
    restart: unless-stopped
```

## 📈 Usage Examples

### Integration in Your App
```typescript
import { TrendmoonMcpServer, startStandaloneServer } from '@trendmoon/mcp-server';

// Library mode
const mcpServer = new TrendmoonMcpServer();
const tools = await mcpServer.getMcpServer().tools.list();

// Programmatic standalone server
await startStandaloneServer({
    transport: 'http',
    http: { port: 3000 },
    server: { name: 'my-custom-server' }
});
```

### Bitcoin Analysis
```bash
# Via CLI
trendmoon-mcp-server serve --transport http &

# Via curl (preferred endpoint)
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "getCoinDetails",
    "arguments": {"symbol": "BTC"}
  }
}'

# Via legacy endpoint (for compatibility)
curl -X POST http://localhost:3000/ \
-H "Content-Type: application/json" \
-d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {"name": "test-client", "version": "1.0.0"}
  }
}'
```

### MCP Inspector Usage
1. Start the server in HTTP mode:
   ```bash
   trendmoon-mcp-server serve --transport http --port 3000
   ```

2. Open MCP Inspector and connect to:
   ```
   http://localhost:3000/mcp
   ```

### Server Information
```bash
curl http://localhost:3000/info
```
Response includes server details, endpoints, active sessions, and usage instructions.

## 🔧 API Reference

### Standard MCP Methods

- `tools/list` : List all available tools
- `tools/call` : Execute a tool with parameters
- `prompts/list` : List all available prompts
- `prompts/get` : Get a specific prompt

### Response Format
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "..."
      }
    ]
  }
}
```

### HTTP Endpoints Details

#### Health Check Response
```json
{
  "status": "ready",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "server": "TrendMoon MCP Server",
  "transport": "Streamable HTTP",
  "sessions": 0,
  "mcpConnected": true
}
```

#### Info Endpoint Response
```json
{
  "name": "TrendMoon MCP Server",
  "version": "1.0.0",
  "transport": "Streamable HTTP",
  "endpoints": {
    "mcp": "/mcp (POST, GET, DELETE)",
    "health": "/health",
    "info": "/info"
  },
  "activeSessions": 0,
  "protocol": "MCP Streamable HTTP Transport",
  "mcpConnected": true,
  "usage": {
    "initialize": "POST /mcp with initialize request",
    "requests": "POST /mcp with mcp-session-id header",
    "notifications": "GET /mcp with mcp-session-id header (SSE)",
    "terminate": "DELETE /mcp with mcp-session-id header"
  }
}
```

### Session Management

The HTTP transport uses session-based communication:

1. **Initialize**: Send `initialize` request to `POST /mcp`
2. **Session ID**: Server responds with a session ID in headers
3. **Subsequent requests**: Include `mcp-session-id` header
4. **SSE notifications**: Use `GET /mcp` with session ID
5. **Terminate**: Use `DELETE /mcp` with session ID

## 🛠️ Development

### Prerequisites

- Node.js 18+
- TypeScript 5.8+
- npm

### Development Setup
```bash
git clone https://github.com/trendmoon/mcp-server.git
cd mcp-server
npm install
cp .env.example .env
# Edit .env with your API keys and configuration
npm run build
```

### Development Scripts
```bash
npm run dev              # STDIO mode
npm run dev:http         # HTTP mode (port 3008)
npm run build           # Build
npm run lint            # Linting
npm test               # Tests
npm run inspect:direct # MCP Inspector
```

## 📊 Monitoring

### Available Metrics

- Number of active connections
- Requests per second
- Errors by endpoint
- Average response time
- Active MCP sessions

### Health Check
```bash
curl http://localhost:3000/health
```

### Server Information
```bash
curl http://localhost:3000/info
```

## 🤝 Contributing

1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📝 Changelog

### v1.0.0
- ✨ Initial release
- 🚀 STDIO and HTTP transport support
- 🔧 Complete tools for crypto and social data
- 📊 Built-in analyzeCoinPerformance prompt
- 🔥 Streamable HTTP support with session management
- 📚 Library and standalone server usage
- 🌐 Health check and info endpoints
- 🔄 Legacy compatibility endpoint

## 📄 License

MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgements

- [Model Context Protocol](https://modelcontextprotocol.io/) for the framework
- [TrendMoon API](https://trendmoon.app) for the data
- The open source community

## 📞 Support

- 📧 Email: support@trendmoon.app
- 💬 Discord: [TrendMoon Community](https://discord.gg/trendmoon)
- 🐛 Issues: [GitHub Issues](https://github.com/trendmoon/mcp-server/issues)

---

Made with ❤️ by the TrendMoon team

## 📦 Publishing to NPM

This package uses GitHub Actions for automated publishing. To release a new version:

1. Update the version in `package.json`:
```bash
npm version patch  # For bug fixes
npm version minor  # For new features
npm version major  # For breaking changes
```

2. Create a new release in GitHub:
   - Go to the GitHub repository
   - Click on "Releases" > "Create a new release"
   - Use tag version format `v1.0.1` (matching your package.json version)
   - Add release notes
   - Publish the release

3. The GitHub Action will automatically:
   - Build the package
   - Run tests
   - Publish to npm

For manual publishing:
```bash
# Ensure you're logged in
npm login

# Check what will be included in the package
npm pack --dry-run

# Publish the package
npm publish --access public
```

**Note**: You must have appropriate npm access to the @trendmoon organization to publish.