Cover image
Try Now
2025-03-30

MCP演示,客户端和服务器作为Web UI的Web工作人员

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.

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

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

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

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

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

  • Lists Tailwind CSS classes in monospaced font

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

  • lumpenspace
  • Take an adjectivised noun, and create images making it progressively more adjective!

  • https://appia.in
  • Siri Shortcut Finder – your go-to place for discovering amazing Siri Shortcuts with ease

  • Daren White
  • A supportive coach for mastering all Spanish tenses.

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

  • apappascs
  • 发现市场上最全面,最新的MCP服务器集合。该存储库充当集中式枢纽,提供了广泛的开源和专有MCP服务器目录,并提供功能,文档链接和贡献者。

  • ShrimpingIt
  • MCP系列GPIO Expander的基于Micropython I2C的操作,源自ADAFRUIT_MCP230XX

  • jae-jae
  • MCP服务器使用剧作《无头浏览器》获取网页内容。

  • HiveNexus
  • 一个适用于中小型团队的AI聊天机器人,支持DeepSeek,Open AI,Claude和Gemini等车型。 专为中小团队设计的ai聊天应用,支持deepSeek,打开ai,claude,双子座等模型。

  • ravitemer
  • 一个功能强大的Neovim插件,用于管理MCP(模型上下文协议)服务器

  • patruff
  • Ollama和MCP服务器之间的桥梁,使本地LLMS可以使用模型上下文协议工具

    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!