@mcp-b/webmcp-ts-sdk 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 mcp-b contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # @mcp-b/webmcp-ts-sdk
2
+
3
+ > Browser-adapted Model Context Protocol TypeScript SDK
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@mcp-b/webmcp-ts-sdk?style=flat-square)](https://www.npmjs.com/package/@mcp-b/webmcp-ts-sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Overview
9
+
10
+ This package adapts the official [@modelcontextprotocol/sdk](https://www.npmjs.com/package/@modelcontextprotocol/sdk) for browser environments with modifications to support dynamic tool registration required by the [W3C Web Model Context API](https://github.com/webmachinelearning/webmcp) (`window.navigator.modelContext`).
11
+
12
+ ## Why This Package Exists
13
+
14
+ 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:
15
+
16
+ ```typescript
17
+ public registerCapabilities(capabilities: ServerCapabilities): void {
18
+ if (this.transport) {
19
+ throw new Error('Cannot register capabilities after connecting to transport');
20
+ }
21
+ ...
22
+ }
23
+ ```
24
+
25
+ For the Web Model Context API, this restriction is incompatible because:
26
+
27
+ 1. **Tools arrive dynamically** - Web pages call `window.navigator.modelContext.provideContext({ tools: [...] })` at any time
28
+ 2. **Transport must be ready immediately** - The MCP server/transport needs to be connected when the page loads
29
+ 3. **Asynchronous registration** - Tools are registered as the page's JavaScript executes, potentially long after initialization
30
+
31
+ This package solves the problem by **pre-registering tool capabilities** before the transport connects, allowing dynamic tool registration to work seamlessly.
32
+
33
+ ## Modifications from Official SDK
34
+
35
+ ### BrowserMcpServer Class
36
+
37
+ The `BrowserMcpServer` extends `McpServer` with these changes:
38
+
39
+ ```typescript
40
+ export class BrowserMcpServer extends BaseMcpServer {
41
+ constructor(serverInfo, options?) {
42
+ // Pre-register tool capabilities in constructor
43
+ const enhancedOptions = {
44
+ ...options,
45
+ capabilities: mergeCapabilities(options?.capabilities || {}, {
46
+ tools: { listChanged: true }
47
+ })
48
+ };
49
+ super(serverInfo, enhancedOptions);
50
+ }
51
+
52
+ async connect(transport: Transport) {
53
+ // Ensure capabilities are set before connecting
54
+ // This bypasses the "cannot register after connect" restriction
55
+ return super.connect(transport);
56
+ }
57
+ }
58
+ ```
59
+
60
+ **Key Difference**: Capabilities are registered **before** connecting, allowing tools to be added dynamically afterward.
61
+
62
+ ## What's Re-Exported
63
+
64
+ This package re-exports almost everything from the official SDK:
65
+
66
+ ### Types
67
+ - All MCP protocol types (`Tool`, `Resource`, `Prompt`, etc.)
68
+ - Request/response schemas
69
+ - Client and server capabilities
70
+ - Error codes and constants
71
+
72
+ ### Classes
73
+ - `Server` - Base server class (unchanged)
74
+ - `McpServer` - Aliased to `BrowserMcpServer` with our modifications
75
+
76
+ ### Utilities
77
+ - `Transport` interface
78
+ - `mergeCapabilities` helper
79
+ - Protocol version constants
80
+
81
+ ## Installation
82
+
83
+ ```bash
84
+ npm install @mcp-b/webmcp-ts-sdk
85
+ # or
86
+ pnpm add @mcp-b/webmcp-ts-sdk
87
+ ```
88
+
89
+ ## Usage
90
+
91
+ Use it exactly like the official SDK:
92
+
93
+ ```typescript
94
+ import { McpServer } from '@mcp-b/webmcp-ts-sdk';
95
+ import { TabServerTransport } from '@mcp-b/transports';
96
+
97
+ const server = new McpServer({
98
+ name: 'my-web-app',
99
+ version: '1.0.0'
100
+ });
101
+
102
+ // Connect transport first
103
+ const transport = new TabServerTransport({ allowedOrigins: ['*'] });
104
+ await server.connect(transport);
105
+
106
+ // Now you can register tools dynamically (this would fail with official SDK)
107
+ server.registerTool('my-tool', {
108
+ description: 'A dynamically registered tool',
109
+ inputSchema: { message: z.string() },
110
+ outputSchema: { result: z.string() }
111
+ }, async ({ message }) => {
112
+ return {
113
+ content: [{ type: 'text', text: `Echo: ${message}` }],
114
+ structuredContent: { result: `Echo: ${message}` }
115
+ };
116
+ });
117
+ ```
118
+
119
+ ## Architecture
120
+
121
+ ```
122
+ ┌─────────────────────────────────┐
123
+ │ @mcp-b/webmcp-ts-sdk │
124
+ │ │
125
+ │ ┌───────────────────────────┐ │
126
+ │ │ BrowserMcpServer │ │
127
+ │ │ (Modified behavior) │ │
128
+ │ └───────────┬───────────────┘ │
129
+ │ │ extends │
130
+ │ ▼ │
131
+ │ ┌───────────────────────────┐ │
132
+ │ │ @modelcontextprotocol/sdk │ │
133
+ │ │ (Official SDK) │ │
134
+ │ │ - Types │ │
135
+ │ │ - Protocol │ │
136
+ │ │ - Validation │ │
137
+ │ └───────────────────────────┘ │
138
+ └─────────────────────────────────┘
139
+ ```
140
+
141
+ ## Maintenance Strategy
142
+
143
+ This package is designed for **minimal maintenance**:
144
+
145
+ - ✅ **~50 lines** of custom code
146
+ - ✅ **Automatic updates** for types, protocol, validation via official SDK dependency
147
+ - ✅ **Single modification point** - only capability registration behavior
148
+ - ✅ **Type-safe** - no prototype hacks or unsafe casts
149
+
150
+ ### Syncing with Upstream
151
+
152
+ When the official SDK updates:
153
+
154
+ 1. Update the catalog version in `pnpm-workspace.yaml`
155
+ 2. Run `pnpm install` to get latest SDK
156
+ 3. Test that capability registration still works
157
+ 4. Update this README if SDK behavior changes
158
+
159
+ The modification is minimal and unlikely to conflict with upstream changes.
160
+
161
+ ## Related Packages
162
+
163
+ - [`@mcp-b/global`](../global) - W3C Web Model Context API implementation (uses this package)
164
+ - [`@mcp-b/transports`](../transports) - Browser-specific MCP transports
165
+ - [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) - Official MCP SDK
166
+
167
+ ## Resources
168
+
169
+ - [Web Model Context API Explainer](https://github.com/webmachinelearning/webmcp)
170
+ - [Model Context Protocol Spec](https://modelcontextprotocol.io/)
171
+ - [Official MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
172
+
173
+ ## License
174
+
175
+ MIT - see [LICENSE](../../LICENSE) for details
176
+
177
+ ## Support
178
+
179
+ - [GitHub Issues](https://github.com/WebMCP-org/npm-packages/issues)
180
+ - [Documentation](https://docs.mcp-b.ai)
@@ -0,0 +1,34 @@
1
+ import { Server, ServerOptions } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { mergeCapabilities } from "@modelcontextprotocol/sdk/shared/protocol.js";
3
+ import { CallToolRequest, CallToolRequestSchema, CallToolResult, CallToolResultSchema, ClientCapabilities, ClientNotification, ClientRequest, ClientResult, CreateMessageRequest, CreateMessageRequestSchema, CreateMessageResult, CreateMessageResultSchema, ElicitRequest, ElicitRequestSchema, ElicitResult, ElicitResultSchema, ErrorCode, GetPromptRequest, GetPromptRequestSchema, GetPromptResult, GetPromptResultSchema, Implementation, Implementation as Implementation$1, InitializeRequest, InitializeRequestSchema, InitializeResult, InitializeResultSchema, JSONRPCMessage, LATEST_PROTOCOL_VERSION, ListPromptsRequest, ListPromptsRequestSchema, ListPromptsResult, ListPromptsResultSchema, ListResourcesRequest, ListResourcesRequestSchema, ListResourcesResult, ListResourcesResultSchema, ListToolsRequest, ListToolsRequestSchema, ListToolsResult, ListToolsResultSchema, LoggingLevel, LoggingLevelSchema, LoggingMessageNotification, McpError, Notification, Prompt, PromptMessage, ReadResourceRequest, ReadResourceRequestSchema, ReadResourceResult, ReadResourceResultSchema, Request, Resource, ResourceContents, ResourceTemplate, Result, SUPPORTED_PROTOCOL_VERSIONS, ServerCapabilities, ServerNotification, ServerRequest, ServerResult, Tool, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { Transport, Transport as Transport$1 } from "@modelcontextprotocol/sdk/shared/transport.js";
6
+
7
+ //#region src/browser-server.d.ts
8
+
9
+ /**
10
+ * Browser-optimized MCP Server for Web Model Context API (window.agent).
11
+ *
12
+ * This class extends McpServer to support dynamic tool registration after
13
+ * transport connection, which is required for the Web Model Context API
14
+ * where tools are registered via window.agent.provideContext() at any time.
15
+ *
16
+ * Key differences from base McpServer:
17
+ * - Pre-registers tool capabilities before connection
18
+ * - Allows tools to be registered after transport is connected
19
+ * - Designed for browser environments where tools arrive asynchronously
20
+ */
21
+ declare class BrowserMcpServer extends McpServer {
22
+ constructor(serverInfo: Implementation$1, options?: ServerOptions);
23
+ /**
24
+ * Override connect to ensure tool request handlers are initialized
25
+ * BEFORE the transport connection is established.
26
+ *
27
+ * This prevents the "Cannot register capabilities after connecting to transport"
28
+ * error when tools are registered dynamically after connection.
29
+ */
30
+ connect(transport: Transport$1): Promise<void>;
31
+ }
32
+ //#endregion
33
+ export { BrowserMcpServer, BrowserMcpServer as McpServer, type CallToolRequest, CallToolRequestSchema, type CallToolResult, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CreateMessageRequest, CreateMessageRequestSchema, type CreateMessageResult, CreateMessageResultSchema, type ElicitRequest, ElicitRequestSchema, type ElicitResult, ElicitResultSchema, ErrorCode, type GetPromptRequest, GetPromptRequestSchema, type GetPromptResult, GetPromptResultSchema, type Implementation, type InitializeRequest, InitializeRequestSchema, type InitializeResult, InitializeResultSchema, type JSONRPCMessage, LATEST_PROTOCOL_VERSION, type ListPromptsRequest, ListPromptsRequestSchema, type ListPromptsResult, ListPromptsResultSchema, type ListResourcesRequest, ListResourcesRequestSchema, type ListResourcesResult, ListResourcesResultSchema, type ListToolsRequest, ListToolsRequestSchema, type ListToolsResult, ListToolsResultSchema, type LoggingLevel, LoggingLevelSchema, type LoggingMessageNotification, type McpError, type Notification, type Prompt, type PromptMessage, type ReadResourceRequest, ReadResourceRequestSchema, type ReadResourceResult, ReadResourceResultSchema, type Request, type Resource, type ResourceContents, type ResourceTemplate, type Result, SUPPORTED_PROTOCOL_VERSIONS, Server, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult, type Tool, type ToolAnnotations, type Transport, mergeCapabilities };
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/browser-server.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AAkBA;;;;;;;;;cAAa,gBAAA,SAAyB,SAAA;0BACZ,4BAA0B;;;;;;;;qBAqBhB,cAAY"}
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { mergeCapabilities, mergeCapabilities as mergeCapabilities$1 } from "@modelcontextprotocol/sdk/shared/protocol.js";
3
+ import { CallToolRequestSchema, CallToolResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, ElicitRequestSchema, ElicitResultSchema, ErrorCode, GetPromptRequestSchema, GetPromptResultSchema, InitializeRequestSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsRequestSchema, ListPromptsResultSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListToolsRequestSchema, ListToolsResultSchema, LoggingLevelSchema, ReadResourceRequestSchema, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS } from "@modelcontextprotocol/sdk/types.js";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+
6
+ //#region src/browser-server.ts
7
+ /**
8
+ * Browser-optimized MCP Server for Web Model Context API (window.agent).
9
+ *
10
+ * This class extends McpServer to support dynamic tool registration after
11
+ * transport connection, which is required for the Web Model Context API
12
+ * where tools are registered via window.agent.provideContext() at any time.
13
+ *
14
+ * Key differences from base McpServer:
15
+ * - Pre-registers tool capabilities before connection
16
+ * - Allows tools to be registered after transport is connected
17
+ * - Designed for browser environments where tools arrive asynchronously
18
+ */
19
+ var BrowserMcpServer = class extends McpServer {
20
+ constructor(serverInfo, options) {
21
+ const enhancedOptions = {
22
+ ...options,
23
+ capabilities: mergeCapabilities$1(options?.capabilities || {}, { tools: { listChanged: true } })
24
+ };
25
+ super(serverInfo, enhancedOptions);
26
+ }
27
+ /**
28
+ * Override connect to ensure tool request handlers are initialized
29
+ * BEFORE the transport connection is established.
30
+ *
31
+ * This prevents the "Cannot register capabilities after connecting to transport"
32
+ * error when tools are registered dynamically after connection.
33
+ */
34
+ async connect(transport) {
35
+ this.setToolRequestHandlers();
36
+ return super.connect(transport);
37
+ }
38
+ };
39
+
40
+ //#endregion
41
+ export { BrowserMcpServer, BrowserMcpServer as McpServer, CallToolRequestSchema, CallToolResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, ElicitRequestSchema, ElicitResultSchema, ErrorCode, GetPromptRequestSchema, GetPromptResultSchema, InitializeRequestSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsRequestSchema, ListPromptsResultSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListToolsRequestSchema, ListToolsResultSchema, LoggingLevelSchema, ReadResourceRequestSchema, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, Server, mergeCapabilities };
42
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["BaseMcpServer","enhancedOptions: ServerOptions","mergeCapabilities"],"sources":["../src/browser-server.ts"],"sourcesContent":["import type { ServerOptions } from '@modelcontextprotocol/sdk/server/index.js';\nimport { McpServer as BaseMcpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { mergeCapabilities } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type { Implementation } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Browser-optimized MCP Server for Web Model Context API (window.agent).\n *\n * This class extends McpServer to support dynamic tool registration after\n * transport connection, which is required for the Web Model Context API\n * where tools are registered via window.agent.provideContext() at any time.\n *\n * Key differences from base McpServer:\n * - Pre-registers tool capabilities before connection\n * - Allows tools to be registered after transport is connected\n * - Designed for browser environments where tools arrive asynchronously\n */\nexport class BrowserMcpServer extends BaseMcpServer {\n constructor(serverInfo: Implementation, options?: ServerOptions) {\n // Ensure tools capability is registered from the start\n const enhancedOptions: ServerOptions = {\n ...options,\n capabilities: mergeCapabilities(options?.capabilities || {}, {\n tools: {\n listChanged: true,\n },\n }),\n };\n\n super(serverInfo, enhancedOptions);\n }\n\n /**\n * Override connect to ensure tool request handlers are initialized\n * BEFORE the transport connection is established.\n *\n * This prevents the \"Cannot register capabilities after connecting to transport\"\n * error when tools are registered dynamically after connection.\n */\n override async connect(transport: Transport): Promise<void> {\n // Call setToolRequestHandlers() BEFORE connecting the transport\n // This will:\n // 1. Register tool capabilities (won't throw since transport isn't connected yet)\n // 2. Set up ListTools and CallTool request handlers\n // 3. Set _toolHandlersInitialized = true\n //\n // After this, any future registerTool() calls will skip registerCapabilities()\n // because _toolHandlersInitialized is true, allowing dynamic tool registration\n\n // Type-safe access to private method - we need to call this internal method\n // to initialize tool handlers before connecting\n (this as unknown as { setToolRequestHandlers: () => void }).setToolRequestHandlers();\n\n // Now connect with the transport\n return super.connect(transport);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAa,mBAAb,cAAsCA,UAAc;CAClD,YAAY,YAA4B,SAAyB;EAE/D,MAAMC,kBAAiC;GACrC,GAAG;GACH,cAAcC,oBAAkB,SAAS,gBAAgB,EAAE,EAAE,EAC3D,OAAO,EACL,aAAa,MACd,EACF,CAAC;GACH;AAED,QAAM,YAAY,gBAAgB;;;;;;;;;CAUpC,MAAe,QAAQ,WAAqC;AAY1D,EAAC,KAA2D,wBAAwB;AAGpF,SAAO,MAAM,QAAQ,UAAU"}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@mcp-b/webmcp-ts-sdk",
3
+ "version": "1.0.1",
4
+ "description": "TypeScript SDK adapter for Model Context Protocol with dynamic tool registration support for browsers",
5
+ "keywords": [
6
+ "mcp",
7
+ "model-context-protocol",
8
+ "browser",
9
+ "typescript",
10
+ "sdk",
11
+ "adapter",
12
+ "web-model-context",
13
+ "navigator.modelContext",
14
+ "w3c"
15
+ ],
16
+ "homepage": "https://github.com/MiguelsPizza/WebMCP#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/MiguelsPizza/WebMCP/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/MiguelsPizza/WebMCP.git",
23
+ "directory": "packages/webmcp-ts-sdk"
24
+ },
25
+ "license": "MIT",
26
+ "author": "Alex Nahas",
27
+ "type": "module",
28
+ "exports": {
29
+ ".": {
30
+ "import": "./dist/index.js",
31
+ "types": "./dist/index.d.ts"
32
+ }
33
+ },
34
+ "main": "./dist/index.js",
35
+ "module": "./dist/index.js",
36
+ "types": "./dist/index.d.ts",
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "dependencies": {
41
+ "@modelcontextprotocol/sdk": "1.15.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^22.15.21",
45
+ "tsdown": "^0.15.10",
46
+ "typescript": "^5.8.3"
47
+ },
48
+ "engines": {
49
+ "node": ">=18"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
54
+ },
55
+ "scripts": {
56
+ "build": "tsdown",
57
+ "check": "biome check --write .",
58
+ "clean": "rm -rf dist .turbo",
59
+ "format": "biome format --write .",
60
+ "lint": "biome lint --write .",
61
+ "publish:dry": "pnpm publish --access public --dry-run",
62
+ "publish:npm": "pnpm publish --access public",
63
+ "typecheck": "tsc --noEmit",
64
+ "version:major": "pnpm version major --no-git-tag-version",
65
+ "version:minor": "pnpm version minor --no-git-tag-version",
66
+ "version:patch": "pnpm version patch --no-git-tag-version"
67
+ }
68
+ }