Skip to content

Sample MCP Server - TypeScript (real-time-collaboration-server) #904

@crivetimihai

Description

@crivetimihai

Overview

Create a sample MCP Server in TypeScript that provides real-time collaboration capabilities including document sharing, live cursors, presence awareness, and conflict resolution using modern web technologies.

Server Specifications

Server Details

  • Name: real-time-collaboration-server
  • Language: TypeScript 5.3+
  • Location: mcp-servers/typescript/real-time-collaboration-server/
  • Purpose: Demonstrate real-time collaboration patterns via MCP

Core Features

  • Real-time document synchronization
  • Operational Transformation (OT) for conflict resolution
  • User presence and awareness
  • Live cursors and selections
  • Version control and history
  • WebSocket-based communication

Tools Provided

1. create_document

Create a new collaborative document

interface CreateDocumentRequest {
  documentId: string;
  title: string;
  content?: string;
  documentType: 'text' | 'markdown' | 'json' | 'code';
  metadata?: Record<string, any>;
  permissions?: DocumentPermissions;
  versionControl?: boolean;
}

interface DocumentPermissions {
  public: boolean;
  allowedUsers?: string[];
  readOnly?: boolean;
  requireAuth?: boolean;
}

2. join_session

Join a collaborative editing session

interface JoinSessionRequest {
  documentId: string;
  userId: string;
  userName: string;
  userColor?: string;
  cursor?: { line: number; column: number };
  readOnly?: boolean;
}

3. apply_operation

Apply operational transformation operations

interface ApplyOperationRequest {
  documentId: string;
  userId: string;
  operation: Operation;
  revision: number;
  timestamp?: number;
}

interface Operation {
  type: 'insert' | 'delete' | 'retain' | 'format';
  position?: number;
  content?: string;
  length?: number;
  attributes?: Record<string, any>;
}

4. update_cursor

Update user cursor position and selection

interface UpdateCursorRequest {
  documentId: string;
  userId: string;
  cursor: CursorPosition;
  selection?: SelectionRange;
  timestamp?: number;
}

interface CursorPosition {
  line: number;
  column: number;
  offset: number;
}

interface SelectionRange {
  start: CursorPosition;
  end: CursorPosition;
}

5. get_document_history

Retrieve document version history

interface DocumentHistoryRequest {
  documentId: string;
  fromRevision?: number;
  toRevision?: number;
  limit?: number;
  includeOperations?: boolean;
  includeSnapshots?: boolean;
}

6. manage_presence

Manage user presence and awareness

interface PresenceRequest {
  documentId: string;
  userId: string;
  status: 'active' | 'away' | 'offline';
  metadata?: {
    name: string;
    avatar?: string;
    color: string;
    lastSeen?: string;
  };
}

7. resolve_conflicts

Handle and resolve editing conflicts

interface ConflictResolutionRequest {
  documentId: string;
  conflictingOperations: Operation[];
  strategy: 'last_writer_wins' | 'operational_transform' | 'three_way_merge';
  userId: string;
  baseRevision: number;
}

8. broadcast_event

Broadcast custom events to all session participants

interface BroadcastEventRequest {
  documentId: string;
  eventType: string;
  payload: Record<string, any>;
  targetUsers?: string[];  // If omitted, broadcast to all
  excludeUsers?: string[];
  priority?: 'low' | 'normal' | 'high';
}

Implementation Requirements

Directory Structure

mcp-servers/typescript/real-time-collaboration-server/
├── src/
│   ├── index.ts
│   ├── server.ts
│   ├── collaboration/
│   │   ├── document-manager.ts
│   │   ├── operation-transformer.ts
│   │   ├── conflict-resolver.ts
│   │   └── session-manager.ts
│   ├── presence/
│   │   ├── presence-tracker.ts
│   │   ├── cursor-manager.ts
│   │   └── awareness-handler.ts
│   ├── persistence/
│   │   ├── document-store.ts
│   │   ├── version-control.ts
│   │   └── history-manager.ts
│   ├── websocket/
│   │   ├── websocket-server.ts
│   │   ├── message-handler.ts
│   │   └── connection-manager.ts
│   ├── utils/
│   │   ├── operational-transform.ts
│   │   ├── diff-algorithm.ts
│   │   └── text-operations.ts
│   └── types/
│       ├── document.ts
│       ├── operations.ts
│       └── collaboration.ts
├── tests/
│   ├── unit/
│   ├── integration/
│   └── collaboration/
├── package.json
├── tsconfig.json
├── jest.config.js
├── README.md
└── examples/
    ├── text-editor.html
    ├── collaborative-coding.ts
    └── document-sharing.ts

Dependencies

{
  "dependencies": {
    "@types/node": "^20.10.0",
    "ws": "^8.14.0",
    "@types/ws": "^8.5.0",
    "uuid": "^9.0.0",
    "y-websocket": "^1.5.0",
    "yjs": "^13.6.0",
    "socket.io": "^4.7.0",
    "redis": "^4.6.0",
    "sqlite3": "^5.1.0",
    "diff-match-patch": "^1.0.5",
    "fast-json-patch": "^3.1.1",
    "joi": "^17.12.0"
  },
  "devDependencies": {
    "@types/jest": "^29.5.0",
    "@types/uuid": "^9.0.0",
    "jest": "^29.7.0",
    "ts-jest": "^29.1.0",
    "typescript": "^5.3.0",
    "nodemon": "^3.0.0",
    "concurrently": "^8.2.0"
  }
}

Configuration

// config.ts
interface CollaborationConfig {
  websocket: {
    port: number;
    maxConnections: number;
    heartbeatInterval: number;
    connectionTimeout: number;
  };
  
  documents: {
    maxDocumentSize: string;
    maxActiveDocuments: number;
    autoSaveInterval: number;
    historyRetention: number; // days
  };
  
  operations: {
    maxOperationsPerSecond: number;
    transformationStrategy: 'ot' | 'crdt';
    conflictResolution: 'automatic' | 'manual';
  };
  
  presence: {
    presenceTimeout: number;
    cursorUpdateThrottle: number;
    maxCursorsPerDocument: number;
  };
  
  storage: {
    type: 'memory' | 'sqlite' | 'redis';
    connectionString?: string;
    snapshotInterval: number;
  };
}

Usage Examples

Document Collaboration Workflow

# Create a new document
echo '{
  "method": "tools/call",
  "params": {
    "name": "create_document",
    "arguments": {
      "documentId": "doc_123",
      "title": "Shared Notes",
      "content": "# Meeting Notes\n\n",
      "documentType": "markdown",
      "permissions": {
        "public": false,
        "allowedUsers": ["user1", "user2", "user3"]
      }
    }
  }
}' | real-time-collaboration-server

# Join collaborative session
echo '{
  "method": "tools/call",
  "params": {
    "name": "join_session",
    "arguments": {
      "documentId": "doc_123",
      "userId": "user1",
      "userName": "Alice Smith",
      "userColor": "#ff6b6b"
    }
  }
}' | real-time-collaboration-server

Real-time Editing Operations

# Apply text insertion
echo '{
  "method": "tools/call",
  "params": {
    "name": "apply_operation",
    "arguments": {
      "documentId": "doc_123",
      "userId": "user1",
      "operation": {
        "type": "insert",
        "position": 15,
        "content": "Important discussion points:\n- Item 1\n- Item 2\n"
      },
      "revision": 1
    }
  }
}' | real-time-collaboration-server

# Update cursor position
echo '{
  "method": "tools/call",
  "params": {
    "name": "update_cursor",
    "arguments": {
      "documentId": "doc_123",
      "userId": "user1",
      "cursor": {
        "line": 5,
        "column": 10,
        "offset": 65
      },
      "selection": {
        "start": {"line": 5, "column": 10, "offset": 65},
        "end": {"line": 5, "column": 16, "offset": 71}
      }
    }
  }
}' | real-time-collaboration-server

Presence and Awareness

# Update user presence
echo '{
  "method": "tools/call",
  "params": {
    "name": "manage_presence",
    "arguments": {
      "documentId": "doc_123",
      "userId": "user1", 
      "status": "active",
      "metadata": {
        "name": "Alice Smith",
        "color": "#ff6b6b",
        "avatar": "https://example.com/avatar1.jpg"
      }
    }
  }
}' | real-time-collaboration-server

Version Control and History

# Get document history
echo '{
  "method": "tools/call",
  "params": {
    "name": "get_document_history",
    "arguments": {
      "documentId": "doc_123",
      "limit": 50,
      "includeOperations": true,
      "includeSnapshots": true
    }
  }
}' | real-time-collaboration-server

Advanced Features

  • Operational Transformation: Conflict-free collaborative editing
  • CRDT Support: Conflict-free Replicated Data Types option
  • Undo/Redo: Multi-user undo/redo with operation reversal
  • Document Branching: Create document branches for parallel editing
  • Access Control: Fine-grained permissions and role management
  • Analytics: Collaboration metrics and usage analytics

Real-time Communication

  • WebSocket Protocol: Low-latency bi-directional communication
  • Message Queuing: Redis-based message persistence
  • Presence Broadcasting: Real-time user activity updates
  • Event Streaming: Custom event broadcasting system
  • Connection Recovery: Automatic reconnection and state sync

Conflict Resolution Strategies

  • Last Writer Wins: Simple timestamp-based resolution
  • Operational Transform: Mathematical conflict resolution
  • Three-Way Merge: Git-style merge with common ancestor
  • Manual Resolution: User-guided conflict resolution

Performance Optimizations

  • Operation Batching: Batch multiple operations for efficiency
  • Cursor Throttling: Limit cursor update frequency
  • Snapshot Compression: Efficient document state storage
  • Connection Pooling: Optimize WebSocket connections
  • Memory Management: Efficient garbage collection

Testing Requirements

  • Unit tests for operational transformation algorithms
  • Integration tests for real-time collaboration scenarios
  • Concurrent editing stress tests
  • Conflict resolution validation tests
  • WebSocket connection and reconnection tests
  • Performance tests with multiple simultaneous users

Acceptance Criteria

  • TypeScript MCP server with 8+ collaboration tools
  • Real-time document synchronization with operational transformation
  • User presence and cursor tracking
  • WebSocket-based real-time communication
  • Document version control and history
  • Conflict resolution with multiple strategies
  • Multi-user session management
  • Custom event broadcasting system
  • Comprehensive test suite for concurrent scenarios (>90% coverage)
  • Performance optimization for multiple simultaneous users
  • Complete documentation with collaboration examples

Priority

High - Demonstrates real-time web application patterns and collaboration workflows

Use Cases

  • Collaborative document editing (Google Docs style)
  • Real-time code collaboration (VS Code Live Share style)
  • Collaborative design tools (Figma style)
  • Multi-user forms and surveys
  • Real-time chat and messaging
  • Collaborative project planning
  • Live presentation and annotation tools
  • Multi-user gaming and interactive experiences

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestmcp-serversMCP Server SamplesoicOpen Innovation Community ContributionstypescriptTypeScript programming language

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions