Cover image
Try Now
2025-03-30

mcp demo, client and server as web workers from a web UI

3 years

Works with Finder

1

Github Watches

1

Github Forks

0

Github Stars

MCP Web Worker Demo

This demo showcases a Model Context Protocol (MCP) client implementation using a Shared Web Worker architecture. It demonstrates how to use MCP in a browser environment with a decoupled architecture using pure JavaScript with no build requirements.

Implementation Components

1. Worker Implementation (worker.js)

  • Contains the implementation for an MCP client in a worker context
  • Demonstrates the worker-side message handling patterns for MCP
  • Implements a simplified MCP client without external dependencies

2. Client Wrapper (mcp-client.js)

  • Provides a simplified API for the main thread to communicate with the worker
  • Handles connection, initialization, and method calls
  • Decouples the communication protocol from the actual MCP implementation

3. Mock Server (server.js)

  • Demo server implementation for testing
  • Provides tools, resources, and prompts
  • Implements MCP request handlers

4. Demo UI (index.html)

  • Interactive interface to test all MCP features
  • Demonstrates client capabilities like tool calling, resource reading, and prompt retrieval
  • Shows connection state and server information

5. Testing Tools

  • Minimal Worker (minimal-worker.js) - A simplified shared worker for compatibility testing
  • Diagnostics - Connection status indicators and detailed logging

Message Protocol

The implementation uses a custom message protocol to communicate between the main thread and the worker context:

  1. Connection Messages

    • { type: 'connection', connectionId, status } - Worker to main thread
    • { type: 'init', clientInfo } - Main thread to worker
    • { type: 'close', connectionId } - Main thread to worker
  2. MCP Messages

    • { type: 'mcp', messageType: 'transport', payload } - For raw MCP protocol messages
    • { type: 'mcp', messageType: 'method', method, params, requestId } - Method calls
    • { type: 'mcp', messageType: 'result', method, result, requestId } - Method results
    • { type: 'mcp', messageType: 'error', error, requestId } - Error responses
    • { type: 'mcp', messageType: 'status', status } - Status updates

Benefits of the Worker-Based Architecture

  1. Performance

    • Offloads MCP processing to a background thread
    • Main UI thread remains responsive during complex operations
  2. Shared State

    • Single worker instance serves multiple tabs/windows
    • Shared connection and state across browser contexts
  3. Decoupled Design

    • MCP implementation details are isolated in the worker
    • Main thread only needs to know the messaging API
    • Easier to update or replace either component
  4. Security

    • MCP code runs in a separate context
    • Resource isolation between UI and protocol handling

How to Run the Demo

  1. Make sure the SDK is built:

    # From the typescript-sdk root directory
    npm run build
    
  2. Start a web server:

    # From the typescript-sdk/webworker-demo directory
    ./start.sh
    

    This script starts a simple HTTP server on port 3000. Alternatively, you can use:

    # From the typescript-sdk root directory
    npx http-server -p 3000
    
  3. Open a web browser (Chrome or Edge recommended) and navigate to:

    http://localhost:3000/webworker-demo/
    

    IMPORTANT: Make sure you're accessing the site via http://localhost:3000 and not file:// protocol. SharedWorkers have restrictions when loaded from the file system.

  4. Click "Connect to MCP" button to establish the connection

    • The tools, resources, and prompts should load automatically
    • If there are any issues, check the browser's console for detailed logs
  5. Use the tabs to explore different MCP features:

    • Tools: List and call available tools (try the "hello" tool with your name)
    • Resources: List and read resources (check out the readme file)
    • Prompts: List and retrieve prompts (try the greeting prompt)

Implementation Notes

  • This demo uses a self-contained implementation with no external dependencies
  • All code runs directly in the browser with no build step required
  • All modern JavaScript features are used (ES modules, async/await, etc.)
  • The worker implements a client and connects to a mock server running in the same context

Browser Compatibility Requirements

This demo strictly requires a browser that supports:

  • Shared Web Workers - This is a hard requirement (Chrome, Edge, and Opera are known to work)
  • ES Modules
  • Async/await
  • Other ES6+ features

If your browser doesn't support SharedWorker, you'll see an error message. Unlike many demos, this implementation doesn't provide a fallback to other technologies - it's designed to showcase the specific advantages of using SharedWorker for MCP clients.

Browsers Known to Support SharedWorker:

  • Chrome
  • Edge (Chromium-based)
  • Opera
  • Android Chrome

Browsers with Limited or No Support:

  • Firefox (disabled by default but can be enabled via about:config)
  • Safari (limited support)
  • iOS Safari (no support)

Troubleshooting

If you encounter issues running the demo:

  1. Failed to fetch worker script:

    • Make sure you're accessing the demo through a web server at http://localhost:3000/webworker-demo/
    • Do not try to load the demo from the file system (file://)
    • Ensure the SDK is built with npm run build from the main directory
    • Check your browser console for specific error messages
    • The demo will try multiple worker script paths automatically to find one that works
  2. SharedWorker not supported:

    • Use Chrome or Edge which have good SharedWorker support
    • The demo will display a clear error if your browser doesn't support SharedWorker
    • The demo purposely does not implement a fallback for non-supporting browsers
  3. Module import errors:

    • The worker and server use regular imports without requiring external libraries
    • Make sure you're accessing via HTTP server, not directly from filesystem
    • Check the browser console for specific import path errors
  4. Console errors:

    • Look for "SharedWorker" or "MCP" related errors in the browser console
    • The implementation includes extensive logging for debugging purposes
    • The worker diagnostics panel shows connection status and script path
  5. Blank page or no tools/resources showing:

    • Check the browser console (F12 or Cmd+Option+I) for detailed error messages
    • Make sure your browser has JavaScript enabled
    • Try clearing your browser cache and refreshing the page
  6. Path resolution issues:

    • The worker attempts to load from multiple paths:
      1. ./minimal-worker.js - relative path to minimal worker
      2. /webworker-demo/minimal-worker.js - absolute path to minimal worker
      3. ./worker.js - relative path to full worker
      4. /webworker-demo/worker.js - absolute path to full worker
    • The worker diagnostics panel will show which path successfully loaded

相关推荐

  • NiKole Maxwell
  • I craft unique cereal names, stories, and ridiculously cute Cereal Baby images.

  • Emmet Halm
  • Converts Figma frames into front-end code for various mobile frameworks.

  • https://maiplestudio.com
  • Find Exhibitors, Speakers and more

  • Yusuf Emre Yeşilyurt
  • I find academic articles and books for research and literature reviews.

  • https://suefel.com
  • Latest advice and best practices for custom GPT development.

  • Carlos Ferrin
  • Encuentra películas y series en plataformas de streaming.

  • Joshua Armstrong
  • Confidential guide on numerology and astrology, based of GG33 Public information

  • https://zenepic.net
  • Embark on a thrilling diplomatic quest across a galaxy on the brink of war. Navigate complex politics and alien cultures to forge peace and avert catastrophe in this immersive interstellar adventure.

  • https://reddgr.com
  • Delivers concise Python code and interprets non-English comments

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • 林乔安妮
  • A fashion stylist GPT offering outfit suggestions for various scenarios.

  • 田中 楓太
  • A virtual science instructor for engaging and informative lessons.

  • ariofarmani
  • Test repository for GitHub MCP server functionality

  • 1Panel-dev
  • 💬 MaxKB is an open-source AI assistant for enterprise. It seamlessly integrates RAG pipelines, supports robust workflows, and provides MCP tool-use capabilities.

  • ShrimpingIt
  • Micropython I2C-based manipulation of the MCP series GPIO expander, derived from Adafruit_MCP230xx

  • Mintplex-Labs
  • The all-in-one Desktop & Docker AI application with built-in RAG, AI agents, No-code agent builder, MCP compatibility, and more.

  • GLips
  • MCP server to provide Figma layout information to AI coding agents like Cursor

    Reviews

    2 (1)
    Avatar
    user_2Un0yJcP
    2025-04-16

    I’ve been using the mcp-worker by weolopez for several months now, and it's been a game-changer for my workflow. The seamless integration and efficiency it offers align perfectly with my needs. Anyone looking for a reliable worker utility should definitely check it out. More details can be found at https://github.com/weolopez/mcp-worker. Highly recommended!