MCP-SERVER

ASTRAX-ai/MCP-SERVER

3.1

If you are the rightful owner of MCP-SERVER and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

The MCP Server acts as a middleware executor, facilitating the final stage of transaction processing after agent reasoning is complete.

MCP Server - Executor & Orchestrator

Clean, modular MCP Server yang berfungsi sebagai middleware executor tahap akhir setelah agent reasoning selesai.

🎯 Fitur Utama

  • Express JS Framework - Server HTTP yang cepat dan reliable
  • Redis Upstash - Pub/Sub untuk komunikasi real-time
  • X402 Simulation - Mock eksekusi rebalance transaksi
  • Clean Architecture - Modular services dan routes
  • Logging - Timestamp logger untuk tracking
  • Error Handling - Comprehensive error management

📁 Struktur Project

├── src/
│   ├── index.js                 # Entry utama Express
│   ├── routes/
│   │   └── mcp.route.js         # Route untuk endpoint MCP
│   ├── services/
│   │   ├── redis.service.js     # Redis Upstash client & Pub/Sub
│   │   ├── job.service.js       # Job management (CRUD)
│   │   └── x402.simulation.js   # X402 rebalance simulation
│   └── utils/
│       └── logger.js            # Timestamp logger
│
├── .env                         # Environment variables
├── package.json
└── README.md

🚀 Quick Start

1. Install Dependencies

npm install

2. Konfigurasi Environment

Edit .env:

PORT=4002
NODE_ENV=development
UPSTASH_REDIS_URL=rediss://default:<password>@<host>:6379

3. Run Server

Development (dengan auto-reload):

npm run dev

Production:

npm start

Server akan berjalan di http://localhost:4002

📡 API Endpoints

1. Health Check

GET /health

Response:

{
  "success": true,
  "message": "MCP Server is healthy",
  "timestamp": "2025-11-12T10:30:00.000Z"
}

2. Confirm Rebalance (Main)

POST /api/v1/mcp/confirm
Content-Type: application/json

{
  "jobId": "123e4567-e89b-12d3-a456-426614174000"
}

Response Success:

{
  "success": true,
  "message": "Job confirmed and executed",
  "jobId": "123e4567-e89b-12d3-a456-426614174000",
  "status": "result",
  "result": {
    "txHash": "0x1234567890abcdef",
    "jobId": "123e4567-e89b-12d3-a456-426614174000",
    "userPublicKey": "...",
    "rebalanceResult": {
      "previousRatio": "95% TOKEN A / 5% SOL",
      "newRatio": "90% TOKEN A / 10% SOL",
      "tokensSwapped": {
        "from": "TOKEN A",
        "to": "SOL",
        "amount": "5%"
      }
    },
    "executedAt": "2025-11-12T10:30:00.000Z",
    "blockNumber": 12345,
    "status": "success"
  }
}

3. Sign Transaction

POST /api/v1/mcp/sign-transaction
Content-Type: application/json

{
  "jobId": "123e4567-e89b-12d3-a456-426614174000",
  "signature": "signature_from_wallet"
}

Response:

{
  "success": true,
  "message": "Transaction signed successfully",
  "jobId": "123e4567-e89b-12d3-a456-426614174000",
  "status": "success"
}

4. Get Job Status

GET /api/v1/mcp/job/:jobId

Response:

{
  "success": true,
  "data": {
    "jobId": "123e4567-e89b-12d3-a456-426614174000",
    "status": "success",
    "data": { ... },
    "createdAt": "2025-11-12T10:25:00.000Z",
    "updatedAt": "2025-11-12T10:30:00.000Z",
    "result": { ... }
  }
}

🔄 Flow Diagram

┌─────────────┐
│   Frontend  │
└──────┬──────┘
       │ POST /api/v1/mcp/confirm
       │ (dengan jobId)
       │
       ▼
┌──────────────────────┐
│   MCP Server         │
│ ┌────────────────┐   │
│ │ 1. Get Job     │   │
│ │    from Redis  │   │
│ └────────────────┘   │
│ ┌────────────────┐   │
│ │ 2. Validate    │   │
│ │    Job Data    │   │
│ └────────────────┘   │
│ ┌────────────────┐   │
│ │ 3. Run X402    │   │
│ │    Simulation  │   │
│ └────────────────┘   │
│ ┌────────────────┐   │
│ │ 4. Update Job  │   │
│ │    Status      │   │
│ └────────────────┘   │
│ ┌────────────────┐   │
│ │ 5. Publish     │   │
│ │    to Redis    │   │
│ └────────────────┘   │
└──────┬───────────────┘
       │ Publish: rebalance:status
       │
       ▼
┌──────────────────────┐
│  Redis Pub/Sub       │
│  (Upstash)           │
└──────┬───────────────┘
       │ Subscribe
       │
       ▼
┌──────────────────────┐
│  Frontend (WebSocket)│
│  - Show sign tx btn  │
│  - Update status     │
└──────────────────────┘

🔧 Service Documentation

Redis Service (src/services/redis.service.js)

Methods:

  • subscribe(channel, callback) - Subscribe ke channel
  • publish(channel, data) - Publish message
  • get(key) - Get value dari Redis
  • set(key, value, expiration) - Set value dengan TTL (optional)
  • del(key) - Delete key
  • close() - Close connection

Usage:

const { publish, get, set } = require('./services/redis.service');

// Publish
await publish('my:channel', { data: 'value' });

// Get
const value = await get('my:key');

// Set dengan TTL 1 jam
await set('my:key', JSON.stringify(data), 3600);

Job Service (src/services/job.service.js)

Methods:

  • getJobById(jobId) - Get job data
  • updateJobStatus(jobId, status, result) - Update status
  • createJob(jobId, data) - Create new job
  • deleteJob(jobId) - Delete job

Usage:

const jobService = require('./services/job.service');

// Get job
const job = await jobService.getJobById(jobId);

// Update status
await jobService.updateJobStatus(jobId, 'success', resultData);

X402 Simulation (src/services/x402.simulation.js)

Methods:

  • run(job) - Run simulation
  • validateJob(job) - Validate job data
  • generateTxHash() - Generate mock tx hash

Usage:

const x402Sim = require('./services/x402.simulation');

// Validate
if (x402Sim.validateJob(job)) {
  // Run simulation
  const result = await x402Sim.run(job);
}

🔐 Environment Variables

# Server
PORT=4002
NODE_ENV=development
LOG_LEVEL=debug

# Upstash Redis
UPSTASH_REDIS_URL=rediss://default:<password>@<host>:6379
UPSTASH_REDIS_TOKEN=<optional>

📊 Logging

Logger otomatis menambahkan timestamp dan level untuk setiap log:

[2025-11-12T10:30:00.123Z] [INFO] Server started
[2025-11-12T10:30:01.456Z] [DEBUG] Getting job from Redis
[2025-11-12T10:30:02.789Z] [ERROR] Redis connection failed

🧪 Testing API dengan cURL

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

# Confirm rebalance
curl -X POST http://localhost:4002/api/v1/mcp/confirm \
  -H "Content-Type: application/json" \
  -d '{"jobId":"test-job-123"}'

# Get job status
curl http://localhost:4002/api/v1/mcp/job/test-job-123

# Sign transaction
curl -X POST http://localhost:4002/api/v1/mcp/sign-transaction \
  -H "Content-Type: application/json" \
  -d '{"jobId":"test-job-123","signature":"sig_xyz"}'

🛠 Development

Scripts

  • npm start - Run production server
  • npm run dev - Run development dengan auto-reload (nodemon)

Adding New Features

  1. New Service:

    • Create file di src/services/
    • Export module methods
    • Import di route atau service lain
  2. New Route:

    • Add endpoint di src/routes/mcp.route.js
    • Follow naming convention: /api/v1/mcp/<action>
  3. New Utils:

    • Create file di src/utils/
    • Reusable functions untuk digunakan di services

📝 Notes

  • Modular: Setiap service handling satu tanggung jawab
  • Scalable: Redis Pub/Sub untuk komunikasi antar services
  • Error Handling: Try-catch di setiap function
  • Logging: Comprehensive logging untuk debugging

📄 License

MIT