Skip to main content
Glama
oshimayoan

Tokopedia MCP Server

by oshimayoan
README.md
# Tokopedia MCP Server

A Model Context Protocol (MCP) server that provides AI assistants with tools to interact with Tokopedia's product search and order management APIs. This server offers both MCP tool integration and a web interface for easy setup and monitoring.

## Features

- **Product Search**: Search Tokopedia products with advanced filtering options
- **Filter & Sort Discovery**: Get available filters and sorting options for any search query
- **Order History**: Retrieve user's order history with pagination support
- **Dual Interface**: MCP protocol for AI assistants + HTTP web interface
- **Docker Support**: Containerized deployment with multi-stage builds
- **Session Management**: Support for authenticated Tokopedia sessions

## Available Tools

### `search_product`

Search for products on Tokopedia with comprehensive filtering options.

**Parameters:**

- `query` (string): The search query
- `orderBy` (optional): Sort order (23=relevance, 3=price low-high, 4=price high-low)
- `condition` (optional): Product condition (1=new, 2=used)
- `rating` (optional): Minimum rating (1-5, comma-separated for multiple)
- `priceMin` (optional): Minimum price
- `priceMax` (optional): Maximum price
- `location` (optional): Location ID (comma-separated for multiple)

### `get_available_product_filters_and_sorts`

Retrieve available filters and sorting options for a specific search query.

**Parameters:**

- `query` (string): The search query

### `get_order_history`

Get user's order history from Tokopedia (requires authenticated session).

**Parameters:**

- `page` (number): Page number for pagination
- `limit` (number): Number of orders per page

## Setup

### Prerequisites

- [Bun](https://bun.sh) (for local development)
- [Docker](https://docker.com) (for containerized deployment)
- Tokopedia session cookie (for authenticated features)

### Environment Variables

Create a `.env` file in the project root:

```env
# Required for order history and personalized features
TOKO_SESSION=your_tokopedia_session_cookie_here

# Optional: Custom port (defaults to 3000)
PORT=3000
```

To get your `TOKO_SESSION`:

1. Log into [Tokopedia](https://www.tokopedia.com) in your browser
2. Open browser dev tools (F12)
3. Go to Application/Storage → Cookies → tokopedia.com
4. Copy the entire cookie string (all cookies concatenated with semicolons)

### Local Development

1. **Install dependencies:**

   ```bash
   bun install
   ```

2. **Build the project:**

   ```bash
   bun run build
   ```

3. **Run the server:**

   ```bash
   bun run serve
   # or directly: node build/index.js
   ```

4. **Access the web interface:**
   Open [http://localhost:3000](http://localhost:3000) in your browser

### Docker Deployment

#### Option 1: Build and run locally

```bash
# Build the Docker image
docker build -t tokopedia-mcp .

# Run with environment variables
docker run -d \
  --name tokopedia-mcp \
  -p 3000:3000 \
  -e TOKO_SESSION="your_session_cookie_here" \
  tokopedia-mcp
```

#### Option 2: Docker Compose

Create `docker-compose.yml`:

```yaml
version: '3.8'
services:
  tokopedia-mcp:
    build: .
    ports:
      - '3000:3000'
    environment:
      - TOKO_SESSION=${TOKO_SESSION}
      - PORT=3000
    restart: unless-stopped
```

Run with:

```bash
docker-compose up -d
```

### Remote Deployment

The server can be deployed to any platform that supports Node.js or Docker:

- **Railway**: Connect your GitHub repo and deploy automatically
- **Render**: Use the included Dockerfile for container deployment
- **Fly.io**: Deploy with `flyctl deploy` using Docker
- **DigitalOcean App Platform**: Deploy directly from GitHub
- **AWS/GCP/Azure**: Use container services or App Engine

For cloud deployment, make sure to:

1. Set the `TOKO_SESSION` environment variable
2. Configure the correct `PORT` if needed
3. Ensure the MCP endpoint `/mcp` is accessible

## Usage Examples

### cURL Examples

#### Search Products

```bash
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "search_product",
      "arguments": {
        "query": "laptop gaming",
        "orderBy": 4,
        "priceMin": 5000000,
        "priceMax": 15000000
      }
    }
  }'
```

#### Get Available Filters

```bash
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_available_product_filters_and_sorts",
      "arguments": {
        "query": "smartphone"
      }
    }
  }'
```

#### Get Order History

```bash
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "get_order_history",
      "arguments": {
        "page": 1,
        "limit": 10
      }
    }
  }'
```

### MCP Client Integration

#### Claude Desktop Integration

Add to your Claude Desktop configuration:

```bash
claude mcp add tokopedia http://localhost:3000/mcp
```

Or manually add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "tokopedia": {
      "command": "node",
      "args": ["/path/to/tokopedia-mcp/build/index.js"],
      "env": {
        "TOKO_SESSION": "your_session_cookie_here"
      }
    }
  }
}
```

#### Cursor Integration

1. Install the MCP extension in Cursor
2. Add server configuration:
   ```json
   {
     "tokopedia": {
       "url": "http://localhost:3000/mcp",
       "type": "http"
     }
   }
   ```

## API Schema & Payloads

### Search Product Schema

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_product",
    "arguments": {
      "query": "string (required)",
      "orderBy": "number (optional: 23|3|4)",
      "condition": "number (optional: 1|2)",
      "rating": "string (optional: '1,2,3,4,5')",
      "priceMin": "number (optional)",
      "priceMax": "number (optional)",
      "location": "string (optional: comma-separated IDs)"
    }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Products for laptop gaming:\n\nName: ASUS ROG Strix G15\nPrice: Rp 12.999.000\nRating: 4.8\nURL: https://www.tokopedia.com/...\n---\n..."
      }
    ]
  }
}
```

### Get Filters Schema

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_available_product_filters_and_sorts",
    "arguments": {
      "query": "string (required)"
    }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Filters and sorts for smartphone:\n\n{\n  \"filter\": [...],\n  \"sort\": [...]\n}"
      }
    ]
  }
}
```

### Order History Schema

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "get_order_history",
    "arguments": {
      "page": "number (required)",
      "limit": "number (required)"
    }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Order history for page 1:\n\nOrder ID: abc123\nName: Product Name\nPrice: Rp 500.000\nStatus: completed\nURL: https://www.tokopedia.com/...\nPurchased At: 2024-01-15\n---\n..."
      }
    ]
  }
}
```

## MCP Registration Commands

### Claude Desktop

```bash
# Add server via CLI
claude mcp add tokopedia http://localhost:3000/mcp

# Or add with custom configuration
claude mcp add tokopedia http://localhost:3000/mcp --config '{
  "env": {
    "TOKO_SESSION": "your_session_here"
  }
}'
```

### Cursor

1. Open Cursor Settings → Extensions → MCP
2. Add new server:
   - **Name**: `tokopedia`
   - **URL**: `http://localhost:3000/mcp`
   - **Type**: `HTTP`

## Development

### Project Structure

```
src/
├── index.ts              # Main entry point
├── server/
│   ├── app.ts           # Express app setup
│   ├── mcp.ts           # MCP server and tools
│   └── routes.ts        # HTTP routes
├── templates/           # HTML templates for web UI
├── types/              # TypeScript type definitions
└── utils/
    ├── template-renderer.ts
    └── tokopedia-api.ts # Tokopedia API integration
```

### Building

```bash
# TypeScript compilation + template copying
bun run build

# Development with watch mode
bun --watch src/index.ts
```

### Testing Tools

You can test individual tools using the web interface or cURL commands shown above.

## Troubleshooting

### Common Issues

**1. "Failed to retrieve search data"**

- Check your internet connection
- Verify Tokopedia is accessible from your network
- Try without filters first to test basic connectivity

**2. "Failed to retrieve order history" / Authentication errors**

- Ensure `TOKO_SESSION` environment variable is set correctly
- Session cookies may expire - get a fresh session from your browser
- Make sure you're logged into Tokopedia in the browser where you got the session

**3. Port already in use**

- Change the PORT environment variable: `PORT=3001`
- Or kill the process using the port: `lsof -ti:3000 | xargs kill`

**4. Docker build issues**

- Make sure Docker daemon is running
- Clear Docker cache: `docker system prune -a`
- Check that all source files are included in the build context

**5. MCP connection issues**

- Verify the server is running and accessible
- Check firewall settings if accessing remotely
- Ensure the MCP client supports HTTP transport

### Debug Mode

Set environment variable for verbose logging:

```bash
DEBUG=1 node build/index.js
```

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and test thoroughly
4. Commit your changes: `git commit -m 'Add amazing feature'`
5. Push to the branch: `git push origin feature/amazing-feature`
6. Open a Pull Request

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Disclaimer

This project is not officially affiliated with Tokopedia. It's an unofficial tool that interacts with Tokopedia's public APIs. Please use responsibly and in accordance with Tokopedia's Terms of Service.