# How to Integrate TREK with Other Systems: REST API, WebSocket, Plugins, and MCP

> Learn how to integrate TREK with other systems using its REST API, WebSocket, plugins, and MCP. This guide covers key integration mechanisms for seamless connectivity.

- Repository: [Maurice/TREK](https://github.com/mauriceboe/TREK)
- Tags: how-to-guide
- Published: 2026-07-10

---

**TREK provides four primary integration mechanisms: a standard REST API for CRUD operations, WebSocket endpoints for real-time synchronization, a plugin architecture for external Node.js processes, and the Modular Control Protocol (MCP) for OAuth2.1-protected AI integrations.**

TREK is a self-hosted, real-time collaborative travel planner built on NestJS. According to the source code in `mauriceboe/TREK`, the application exposes multiple integration points that allow external systems to read and modify travel data, receive live updates, and extend core functionality without modifying the main codebase.

## REST API Integration

The TREK backend follows standard NestJS patterns, exposing HTTP endpoints under `/api` for core domain operations. In [`dist/engine.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/engine.ts), the application bootstrap configures CORS and initializes the global validation pipe, while [`dist/app.module.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/app.module.ts) registers the TypeORM connection to the SQLite database at `./data/travel.db` and loads the controller layer.

To integrate with the REST API, obtain a **JSON Web Token (JWT)** or **Personal Access Token (PAT)** from the TREK admin panel and include it in the `Authorization: Bearer <token>` header.

```typescript
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  headers: { Authorization: `Bearer ${process.env.TREK_TOKEN}` },
});

async function fetchTrips() {
  const { data } = await api.get('/trips');
  return data;
}

fetchTrips().then(console.log).catch(console.error);

```

**Key configuration:** The allowed origins for CORS are read from the `ALLOWED_ORIGINS` environment variable in [`dist/engine.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/engine.ts), splitting on commas to support multiple domains.

## Real-Time WebSocket Integration

For systems requiring live updates, TREK exposes a WebSocket endpoint at `ws://localhost:3000/ws` as documented in [`wiki/Real-Time-Collaboration.md`](https://github.com/mauriceboe/TREK/blob/main/wiki/Real-Time-Collaboration.md). This is the same channel used by the React frontend for collaborative editing.

The connection requires authentication via a PAT sent as a JSON message immediately after opening:

```typescript
import WebSocket from 'ws';

const ws = new WebSocket('ws://localhost:3000/ws');

ws.on('open', () => {
  // Authenticate using a personal access token
  ws.send(JSON.stringify({ 
    type: 'auth', 
    token: process.env.TREK_TOKEN 
  }));
});

ws.on('message', (raw) => {
  const msg = JSON.parse(raw.toString());
  if (msg.type === 'event' && msg.event === 'trip_update') {
    console.log('Real-time update:', msg.payload);
  }
});

```

Messages follow a strict JSON protocol defined in the wiki documentation, with events like `trip_update`, `reservation_created`, and `user_joined` broadcast to all connected clients.

## Plugin Architecture

TREK supports external plugins that run as separate processes (or Docker containers) and communicate with the main server via the same WebSocket endpoint. According to [`wiki/Plugins.md`](https://github.com/mauriceboe/TREK/blob/main/wiki/Plugins.md), plugins authenticate using PATs and subscribe to specific event types.

This architecture allows you to build integrations—such as pushing new reservations to a corporate accounting system—without modifying the core NestJS application:

```typescript
import WebSocket from 'ws';

const ws = new WebSocket('ws://localhost:3000/ws');

ws.on('open', () => {
  ws.send(JSON.stringify({ 
    type: 'auth', 
    token: process.env.TREK_PLUGIN_TOKEN 
  }));
});

ws.on('message', (raw) => {
  const msg = JSON.parse(raw.toString());
  if (msg.type === 'event' && msg.event === 'reservation_created') {
    // Push to external ERP
    await pushToAccountingSystem(msg.payload);
  }
});

```

Plugins are ideal for long-running background tasks and integration with legacy systems that cannot support WebSocket clients directly.

## MCP (Modular Control Protocol) Integration

For AI assistants and third-party services requiring granular permissions, TREK implements the **Modular Control Protocol** documented in [`wiki/MCP.md`](https://github.com/mauriceboe/TREK/blob/main/wiki/MCP.md). This OAuth 2.1-based API allows scoped access to resources like `trip:read`, `trip:write`, and `place:admin`.

The `@trek/mcp` SDK abstracts the authentication flow and HTTP requests:

```typescript
import { MCPClient } from '@trek/mcp';

const client = new MCPClient({
  clientId: 'my-ai-assistant',
  clientSecret: 's3cr3t',
  scopes: ['trip:read', 'trip:write'],
});

await client.authenticate();

const trips = await client.get('/trips');
console.log('Accessible trips:', trips);

```

MCP endpoints are protected by the OAuth server implemented within the NestJS application, ensuring that external tools can only access data explicitly permitted by the user.

## Authentication and Security

All integration points share a unified authentication layer:

- **REST API and WebSocket:** Accept JWTs or PATs via the `Authorization` header or initial message payload.
- **MCP:** Requires OAuth 2.1 client credentials with explicit scope grants.
- **CORS:** Configured in [`dist/engine.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/engine.ts) via the `ALLOWED_ORIGINS` environment variable, supporting comma-separated domains for development and production environments.

The [`package.json`](https://github.com/mauriceboe/TREK/blob/main/package.json) lists critical dependencies including `@nestjs/common`, `@nestjs/core`, and `ws` (WebSocket library), which external integrations must respect when building clients.

## Summary

- **REST API:** Standard HTTP endpoints under `/api` secured with Bearer tokens, bootstrapped in [`dist/engine.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/engine.ts).
- **WebSocket:** Real-time bi-directional communication at `ws://localhost:3000/ws` using JSON message formats.
- **Plugins:** External Node.js processes that authenticate via PAT and subscribe to events over WebSocket.
- **MCP:** OAuth 2.1-protected API for fine-grained, scope-limited access ideal for AI integrations.

## Frequently Asked Questions

### Does TREK support webhooks for external notifications?

No, TREK does not implement traditional HTTP webhooks. Instead, use the **WebSocket** endpoint or **Plugin architecture** to receive real-time events. The WebSocket connection in [`dist/engine.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/engine.ts) broadcasts internal events to all authenticated clients, which is the preferred method for push notifications.

### What database does TREK use for integrations?

TREK uses **SQLite** by default, configured in [`dist/app.module.ts`](https://github.com/mauriceboe/TREK/blob/main/dist/app.module.ts) with the database file at `./data/travel.db`. External systems should not read the SQLite file directly; instead, use the REST API or WebSocket interfaces to ensure data consistency and respect the business logic enforced by the NestJS application layer.

### How do I generate a Personal Access Token (PAT) for plugin authentication?

Personal Access Tokens are generated through the TREK admin interface (Settings > API Tokens). According to [`wiki/Plugins.md`](https://github.com/mauriceboe/TREK/blob/main/wiki/Plugins.md), these tokens are passed in the initial `auth` message when opening a WebSocket connection to `ws://localhost:3000/ws`. The server validates the token against the user database before permitting event subscriptions.

### Can I use the MCP client in a browser environment?

While the `@trek/mcp` SDK is designed for Node.js server environments, the underlying OAuth 2.1 flow can be implemented in browsers using the **Authorization Code Flow with PKCE**. Refer to [`wiki/MCP.md`](https://github.com/mauriceboe/TREK/blob/main/wiki/MCP.md) for the complete list of endpoints and scopes required to construct browser-compatible authentication requests.