Sponsored by Deepsite.site

MCP Web Worker Demo

Created By
weolopez9 months ago
mcp demo, client and server as web workers from a web UI
Content

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
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
WindsurfThe new purpose-built IDE to harness magic
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
CursorThe AI Code Editor
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Tavily Mcp
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Playwright McpPlaywright MCP server
Serper MCP ServerA Serper MCP Server
ChatWiseThe second fastest AI chatbot™
Amap Maps高德地图官方 MCP Server
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
DeepChatYour AI Partner on Desktop