Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@mcp-b/webmcp-ts-sdk

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mcp-b/webmcp-ts-sdk

Browser-adapted MCP TypeScript SDK - Dynamic tool registration for W3C Web Model Context API and AI agent integration

latest
Source
npmnpm
Version
3.0.0
Version published
Weekly downloads
11K
-17.83%
Maintainers
1
Weekly downloads
 
Created
Source

@mcp-b/webmcp-ts-sdk

Browser-adapted MCP TypeScript SDK - Dynamic tool registration for AI agents like Claude, ChatGPT, and Gemini

npm version npm downloads License: MIT TypeScript Minimal Code

Full Documentation | Quick Start

@mcp-b/webmcp-ts-sdk adapts the official MCP TypeScript SDK for browser environments, enabling dynamic tool registration required by the W3C Web Model Context API. This allows AI agents like Claude, ChatGPT, Gemini, Cursor, and Copilot to interact with browser-based applications.

Why Use @mcp-b/webmcp-ts-sdk?

FeatureBenefit
Dynamic Tool RegistrationRegister tools after transport connection - required for browser apps
Minimal OverheadOnly ~50 lines of custom code on top of official SDK
Full SDK CompatibilityRe-exports all types, classes, and utilities from official SDK
Type-SafeNo prototype hacks - clean TypeScript extension
Auto-UpdatesTypes and protocol follow official SDK automatically

Overview

This package adapts the official @modelcontextprotocol/sdk for browser environments with modifications to support dynamic tool registration required by the W3C Web Model Context API (window.navigator.modelContext).

Why This Package Exists

The official MCP TypeScript SDK has a restriction that prevents registering server capabilities (like tools) after a transport connection is established. This is enforced by this check in the Server class:

public registerCapabilities(capabilities: ServerCapabilities): void {
    if (this.transport) {
        throw new Error('Cannot register capabilities after connecting to transport');
    }
    ...
}

For the Web Model Context API, this restriction is incompatible because:

  • Tools arrive dynamically - Web pages call window.navigator.modelContext.registerTool(...) at any time
  • Transport must be ready immediately - The MCP server/transport needs to be connected when the page loads
  • Asynchronous registration - Tools are registered as the page's JavaScript executes, potentially long after initialization

This package solves the problem by pre-registering tool capabilities before the transport connects, allowing dynamic tool registration to work seamlessly.

Compatibility note:

  • BrowserMcpServer.registerTool(tool, options?) accepts the WebMCP April 23, 2026 draft signature, including options.signal (AbortSignal) for unregistration. When the signal aborts, both the server-side registration and the mirrored native registration are removed.
  • The same call still returns a deprecated { unregister } compatibility handle so existing MCP-B integrations do not break, even though spec/native runtimes return undefined. The handle will be removed in the next major version — prefer options.signal.
  • unregisterTool(name) was removed from the WebMCP draft on April 23, 2026 in favor of the AbortSignal flow. It is kept on BrowserMcpServer with a one-time deprecation warning to interoperate with current Chrome Beta 147 (which still ships the string-name API). It will be removed in the next major version.
  • provideContext() and clearContext() were removed from the WebMCP draft on March 5, 2026 and are not exposed by BrowserMcpServer.

Modifications from Official SDK

BrowserMcpServer Class

The BrowserMcpServer extends McpServer with these changes:

export class BrowserMcpServer extends BaseMcpServer {
  constructor(serverInfo, options?) {
    // Pre-register tool capabilities in constructor
    const enhancedOptions = {
      ...options,
      capabilities: mergeCapabilities(options?.capabilities || {}, {
        tools: { listChanged: true },
      }),
    };
    super(serverInfo, enhancedOptions);
  }

  async connect(transport: Transport) {
    // Ensure capabilities are set before connecting
    // This bypasses the "cannot register after connect" restriction
    return super.connect(transport);
  }
}

Key Difference: Capabilities are registered before connecting, allowing tools to be added dynamically afterward.

What's Re-Exported

This package re-exports almost everything from the official SDK:

Types

  • All MCP protocol types (Tool, Resource, Prompt, etc.)
  • Request/response schemas
  • Client and server capabilities
  • Error codes and constants

Classes

  • Server - Base server class (unchanged)
  • McpServer - Aliased to BrowserMcpServer with our modifications

Utilities

  • Transport interface
  • mergeCapabilities helper
  • Protocol version constants

Installation

npm install @mcp-b/webmcp-ts-sdk
# or
pnpm add @mcp-b/webmcp-ts-sdk

Usage

Use it exactly like the official SDK:

import { McpServer } from '@mcp-b/webmcp-ts-sdk';
import { TabServerTransport } from '@mcp-b/transports';

const server = new McpServer({
  name: 'my-web-app',
  version: '1.0.0',
});

// Connect transport first
const transport = new TabServerTransport({ allowedOrigins: ['*'] });
await server.connect(transport);

// Now you can register tools dynamically (this would fail with official SDK)
server.registerTool(
  'my-tool',
  {
    description: 'A dynamically registered tool',
    inputSchema: { message: z.string() },
    // Output schemas enable structured, type-safe AI responses
    outputSchema: { result: z.string() },
  },
  async ({ message }) => {
    return {
      content: [{ type: 'text', text: `Echo: ${message}` }],
      // structuredContent must match the outputSchema
      structuredContent: { result: `Echo: ${message}` },
    };
  }
);

// Example with complex output schema
server.registerTool(
  'analyze-data',
  {
    description: 'Analyze data and return structured results',
    inputSchema: {
      data: z.array(z.number()),
      operation: z.enum(['sum', 'average', 'stats']),
    },
    outputSchema: {
      result: z.number(),
      operation: z.string(),
      metadata: z.object({
        count: z.number(),
        min: z.number().optional(),
        max: z.number().optional(),
      }),
    },
  },
  async ({ data, operation }) => {
    const stats = calculateStats(data, operation);
    return {
      content: [{ type: 'text', text: `Result: ${stats.result}` }],
      structuredContent: stats,
    };
  }
);

Architecture

┌─────────────────────────────────┐
│  @mcp-b/webmcp-ts-sdk           │
│                                 │
│  ┌───────────────────────────┐  │
│  │ BrowserMcpServer          │  │
│  │ (Modified behavior)        │  │
│  └───────────┬───────────────┘  │
│              │ extends          │
│              ▼                  │
│  ┌───────────────────────────┐  │
│  │ @modelcontextprotocol/sdk │  │
│  │ (Official SDK)             │  │
│  │ - Types                    │  │
│  │ - Protocol                 │  │
│  │ - Validation               │  │
│  └───────────────────────────┘  │
└─────────────────────────────────┘

Maintenance Strategy

This package is designed for minimal maintenance:

  • ~50 lines of custom code
  • Automatic updates for types, protocol, validation via official SDK dependency
  • Single modification point - only capability registration behavior
  • Type-safe - no prototype hacks or unsafe casts

Syncing with Upstream

When the official SDK updates:

  • Update the catalog version in pnpm-workspace.yaml
  • Run pnpm install to get latest SDK
  • Test that capability registration still works
  • Update this README if SDK behavior changes

The modification is minimal and unlikely to conflict with upstream changes.

Frequently Asked Questions

Why can't I use the official SDK directly?

The official SDK throws an error if you try to register tools after connecting a transport. Browsers need dynamic registration because tools arrive asynchronously as the page loads.

Is this a fork of the official SDK?

No - it's a thin adapter (~50 lines) that extends the official SDK. All types, protocol handling, and validation come from the upstream package.

Will this break when the official SDK updates?

Unlikely. The modification is minimal and isolated. When upstream updates, just update your dependencies - the wrapper adapts automatically.

When should I use this vs @mcp-b/global?

Use @mcp-b/global for the standard navigator.modelContext API. Use this package directly only if you need low-level control over the MCP server.

Resources

License

MIT - see LICENSE for details

Support

Keywords

adapter

FAQs

Package last updated on 29 May 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts