@businessmaps/bifrost 0.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 +201 -0
- package/README.md +95 -0
- package/bin/bifrost +276 -0
- package/lib/websocket.js +329 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# @businessmaps/bifrost
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Business-Maps/mcp/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@businessmaps/bifrost)
|
|
5
|
+
|
|
6
|
+
MCP server that lets AI tools call functions running in your browser.
|
|
7
|
+
|
|
8
|
+
The daemon sits between any MCP client and your browser tab. It speaks JSON-RPC over stdio on one side and WebSocket on the other. Your browser app connects, registers tools, and the AI can call them. No dependencies, just Node 18+.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm i -g @businessmaps/bifrost
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
or without npm
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
curl -fsSL https://raw.githubusercontent.com/Business-Maps/mcp/main/install.sh | sh
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Then register it with your MCP client. For example:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
claude mcp add --transport stdio bifrost -- bifrost
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The MCP client starts the daemon automatically.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
Install the client library in your browser app:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm i @businessmaps/bifrost-browser
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Or use a CDN:
|
|
39
|
+
|
|
40
|
+
```html
|
|
41
|
+
<script src="https://unpkg.com/@businessmaps/bifrost-browser"></script>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
TypeScript types are included out of the box — no `@types` package needed.
|
|
45
|
+
|
|
46
|
+
Then register your tools:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { BifrostBrowser } from "@businessmaps/bifrost-browser";
|
|
50
|
+
|
|
51
|
+
const bridge = new BifrostBrowser({
|
|
52
|
+
port: 3099,
|
|
53
|
+
token: "TOKEN", // printed to stderr when daemon starts
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
bridge.registerTools([
|
|
57
|
+
{
|
|
58
|
+
name: "get_selection",
|
|
59
|
+
description: "Returns the user's text selection",
|
|
60
|
+
inputSchema: { type: "object", properties: {} },
|
|
61
|
+
handler: async () => window.getSelection().toString(),
|
|
62
|
+
},
|
|
63
|
+
]);
|
|
64
|
+
|
|
65
|
+
bridge.connect();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Handlers run in the browser -- full access to DOM, Canvas, IndexedDB, Clipboard, `fetch`, etc.
|
|
69
|
+
|
|
70
|
+
There's a working [live demo](https://business-maps.github.io/mcp/demo/) with five sample tools you can try right away.
|
|
71
|
+
|
|
72
|
+
## Auth
|
|
73
|
+
|
|
74
|
+
The daemon generates a token on startup and prints it to stderr. Pass it to the client — the token is sent via the `Sec-WebSocket-Protocol` header during the WebSocket handshake. Auth is always enabled.
|
|
75
|
+
|
|
76
|
+
## Multiple tabs
|
|
77
|
+
|
|
78
|
+
Each tab registers its own tools. Calls route to whoever owns the tool. Disconnecting a tab removes its tools.
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
The daemon reads its port from the `PORT` environment variable (default: `3099`).
|
|
83
|
+
|
|
84
|
+
## Dev
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
git clone https://github.com/Business-Maps/mcp.git && cd mcp
|
|
88
|
+
npm test # no install needed, no deps
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
[Architecture](docs/architecture.md) · [Client API](docs/client-api.md) · [Contributing](CONTRIBUTING.md)
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
Apache 2.0
|
package/bin/bifrost
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { createInterface } from "readline";
|
|
4
|
+
import { randomBytes } from "crypto";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import { dirname, join } from "path";
|
|
7
|
+
|
|
8
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
const { MiniWebSocketServer } = await import(
|
|
11
|
+
new URL(`file://${join(__dirname, "..", "lib", "websocket.js")}`)
|
|
12
|
+
).catch(() =>
|
|
13
|
+
import(new URL(`file://${join(__dirname, "websocket.js")}`))
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Config
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
const PORT = parseInt(process.env.PORT || "3099", 10);
|
|
20
|
+
const TIMEOUT_MS = 120_000;
|
|
21
|
+
const MAX_MESSAGE_SIZE = 1 * 1024 * 1024; // 1MB
|
|
22
|
+
const MAX_PENDING_CALLS = 100;
|
|
23
|
+
const MAX_CALLS_PER_MIN = 120;
|
|
24
|
+
const HEARTBEAT_INTERVAL = 30_000;
|
|
25
|
+
const HEARTBEAT_TIMEOUT = 10_000;
|
|
26
|
+
|
|
27
|
+
const ALLOWED_ORIGINS = new Set([
|
|
28
|
+
"http://localhost",
|
|
29
|
+
"http://127.0.0.1",
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
const AUTH_TOKEN = randomBytes(32).toString("base64url");
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// State
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
const connections = new Map();
|
|
38
|
+
const pendingCalls = new Map();
|
|
39
|
+
let connectionIdCounter = 0;
|
|
40
|
+
let callIdCounter = 0;
|
|
41
|
+
|
|
42
|
+
// rate limiting
|
|
43
|
+
const rateMap = new Map();
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// Utils
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
function now() { return Date.now(); }
|
|
49
|
+
|
|
50
|
+
function rateLimit(key) {
|
|
51
|
+
const bucket = rateMap.get(key) || { count: 0, ts: now() };
|
|
52
|
+
if (now() - bucket.ts > 60_000) {
|
|
53
|
+
bucket.count = 0;
|
|
54
|
+
bucket.ts = now();
|
|
55
|
+
}
|
|
56
|
+
bucket.count++;
|
|
57
|
+
rateMap.set(key, bucket);
|
|
58
|
+
return bucket.count <= MAX_CALLS_PER_MIN;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function safeParse(raw) {
|
|
62
|
+
if (typeof raw !== "string" || raw.length > MAX_MESSAGE_SIZE) return null;
|
|
63
|
+
try { return JSON.parse(raw); } catch { return null; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function safeSend(ws, obj) {
|
|
67
|
+
const data = JSON.stringify(obj);
|
|
68
|
+
if (ws.bufferedAmount > MAX_MESSAGE_SIZE) {
|
|
69
|
+
ws.close();
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
ws.send(data);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// MCP stdio
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
const rl = createInterface({ input: process.stdin });
|
|
80
|
+
|
|
81
|
+
function sendMcp(msg) {
|
|
82
|
+
process.stdout.write(JSON.stringify(msg) + "\n");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
rl.on("line", (line) => {
|
|
86
|
+
const msg = safeParse(line);
|
|
87
|
+
if (!msg) return;
|
|
88
|
+
handleMcp(msg);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
// MCP handler
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
function handleMcp(msg) {
|
|
95
|
+
const { method, id, params } = msg;
|
|
96
|
+
|
|
97
|
+
if (method === "initialize") {
|
|
98
|
+
sendMcp({
|
|
99
|
+
jsonrpc: "2.0",
|
|
100
|
+
id,
|
|
101
|
+
result: {
|
|
102
|
+
protocolVersion: "2024-11-05",
|
|
103
|
+
capabilities: { tools: { listChanged: true } },
|
|
104
|
+
serverInfo: { name: "bifrost", version: "secure" },
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (method === "tools/list") {
|
|
111
|
+
const tools = [];
|
|
112
|
+
for (const [cid, conn] of connections) {
|
|
113
|
+
for (const tool of conn.tools.values()) {
|
|
114
|
+
tools.push({
|
|
115
|
+
name: `${cid}:${tool.name}`, // namespaced
|
|
116
|
+
description: tool.description || "",
|
|
117
|
+
inputSchema: tool.inputSchema || {},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
sendMcp({ jsonrpc: "2.0", id, result: { tools } });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (method === "tools/call") {
|
|
127
|
+
const { name, arguments: args } = params;
|
|
128
|
+
|
|
129
|
+
const [connId, toolName] = name.split(":");
|
|
130
|
+
const conn = connections.get(connId);
|
|
131
|
+
|
|
132
|
+
if (!conn || !conn.tools.has(toolName)) {
|
|
133
|
+
sendMcp({
|
|
134
|
+
jsonrpc: "2.0",
|
|
135
|
+
id,
|
|
136
|
+
error: { code: -32000, message: "Tool not found" },
|
|
137
|
+
});
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (pendingCalls.size >= MAX_PENDING_CALLS) {
|
|
142
|
+
sendMcp({
|
|
143
|
+
jsonrpc: "2.0",
|
|
144
|
+
id,
|
|
145
|
+
error: { code: -32001, message: "Too many pending calls" },
|
|
146
|
+
});
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const callId = `c_${++callIdCounter}`;
|
|
151
|
+
|
|
152
|
+
const timer = setTimeout(() => {
|
|
153
|
+
pendingCalls.delete(callId);
|
|
154
|
+
}, TIMEOUT_MS);
|
|
155
|
+
|
|
156
|
+
pendingCalls.set(callId, { id, timer, connId });
|
|
157
|
+
|
|
158
|
+
safeSend(conn.ws, {
|
|
159
|
+
type: "tool_call",
|
|
160
|
+
callId,
|
|
161
|
+
name: toolName,
|
|
162
|
+
arguments: args,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
// WebSocket server
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
const wss = new MiniWebSocketServer({ port: PORT }, () => {
|
|
173
|
+
console.error(`Secure MCP bridge running on ws://localhost:${PORT}`);
|
|
174
|
+
console.error(`Auth token (use as header): ${AUTH_TOKEN}`);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
wss.on("connection", (ws, req) => {
|
|
178
|
+
// 🔐 Origin check
|
|
179
|
+
const origin = req.headers.origin;
|
|
180
|
+
if (origin && !ALLOWED_ORIGINS.has(origin)) {
|
|
181
|
+
ws.close();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 🔐 Header-based auth
|
|
186
|
+
const token = req.headers["sec-websocket-protocol"];
|
|
187
|
+
if (token !== AUTH_TOKEN) {
|
|
188
|
+
ws.close();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const connId = `conn_${++connectionIdCounter}`;
|
|
193
|
+
|
|
194
|
+
const conn = {
|
|
195
|
+
ws,
|
|
196
|
+
tools: new Map(),
|
|
197
|
+
lastPong: now(),
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
connections.set(connId, conn);
|
|
201
|
+
|
|
202
|
+
// heartbeat
|
|
203
|
+
const interval = setInterval(() => {
|
|
204
|
+
if (now() - conn.lastPong > HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT) {
|
|
205
|
+
ws.close();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
safeSend(ws, { type: "ping" });
|
|
209
|
+
}, HEARTBEAT_INTERVAL);
|
|
210
|
+
|
|
211
|
+
ws.on("message", (raw) => {
|
|
212
|
+
if (!rateLimit(connId)) return;
|
|
213
|
+
|
|
214
|
+
const msg = safeParse(raw);
|
|
215
|
+
if (!msg) return;
|
|
216
|
+
|
|
217
|
+
if (msg.type === "pong") {
|
|
218
|
+
conn.lastPong = now();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (msg.type === "register_tools") {
|
|
223
|
+
conn.tools.clear();
|
|
224
|
+
|
|
225
|
+
for (const tool of msg.tools || []) {
|
|
226
|
+
if (!tool.name) continue;
|
|
227
|
+
conn.tools.set(tool.name, tool);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
sendMcp({
|
|
231
|
+
jsonrpc: "2.0",
|
|
232
|
+
method: "notifications/tools/list_changed",
|
|
233
|
+
});
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (msg.type === "tool_result") {
|
|
238
|
+
const pending = pendingCalls.get(msg.callId);
|
|
239
|
+
if (!pending) return;
|
|
240
|
+
|
|
241
|
+
clearTimeout(pending.timer);
|
|
242
|
+
pendingCalls.delete(msg.callId);
|
|
243
|
+
|
|
244
|
+
sendMcp({
|
|
245
|
+
jsonrpc: "2.0",
|
|
246
|
+
id: pending.id,
|
|
247
|
+
result: {
|
|
248
|
+
content: [
|
|
249
|
+
{
|
|
250
|
+
type: "text",
|
|
251
|
+
text: JSON.stringify(msg.result ?? msg.error),
|
|
252
|
+
},
|
|
253
|
+
],
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
ws.on("close", () => {
|
|
260
|
+
clearInterval(interval);
|
|
261
|
+
|
|
262
|
+
for (const [id, p] of pendingCalls) {
|
|
263
|
+
if (p.connId === connId) {
|
|
264
|
+
clearTimeout(p.timer);
|
|
265
|
+
pendingCalls.delete(id);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
connections.delete(connId);
|
|
270
|
+
|
|
271
|
+
sendMcp({
|
|
272
|
+
jsonrpc: "2.0",
|
|
273
|
+
method: "notifications/tools/list_changed",
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
});
|
package/lib/websocket.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// Hardened Minimal WebSocket server (RFC 6455 compliant core)
|
|
3
|
+
// Zero dependencies
|
|
4
|
+
// ============================================================================
|
|
5
|
+
|
|
6
|
+
import { createServer } from "http";
|
|
7
|
+
import { createHash } from "crypto";
|
|
8
|
+
import { EventEmitter } from "events";
|
|
9
|
+
|
|
10
|
+
const GUID = "258EAFA5-E914-47DA-95CA-5AB5DC65C97B";
|
|
11
|
+
|
|
12
|
+
const MAX_PAYLOAD_SIZE = 100 * 1024 * 1024; // 100MB
|
|
13
|
+
const MAX_BUFFER_SIZE = 200 * 1024 * 1024; // 200MB total buffered
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// MiniWebSocket
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
export class MiniWebSocket extends EventEmitter {
|
|
19
|
+
constructor(socket) {
|
|
20
|
+
super();
|
|
21
|
+
this.socket = socket;
|
|
22
|
+
this.readyState = 1;
|
|
23
|
+
|
|
24
|
+
this._buffer = Buffer.alloc(0);
|
|
25
|
+
|
|
26
|
+
// fragmentation state
|
|
27
|
+
this._fragType = null;
|
|
28
|
+
this._fragBuffer = [];
|
|
29
|
+
|
|
30
|
+
socket.on("data", (c) => this._onData(c));
|
|
31
|
+
socket.on("close", () => this._handleClose());
|
|
32
|
+
socket.on("end", () => this._handleClose());
|
|
33
|
+
socket.on("error", (err) => {
|
|
34
|
+
this._handleClose();
|
|
35
|
+
this.emit("error", err);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// -------------------------------------------------------------------------
|
|
40
|
+
// Public API
|
|
41
|
+
// -------------------------------------------------------------------------
|
|
42
|
+
send(data) {
|
|
43
|
+
if (this.readyState !== 1) return;
|
|
44
|
+
|
|
45
|
+
const payload = Buffer.isBuffer(data)
|
|
46
|
+
? data
|
|
47
|
+
: Buffer.from(String(data));
|
|
48
|
+
|
|
49
|
+
this._writeFrame(0x1, payload);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
close(code = 1000) {
|
|
53
|
+
if (this.readyState !== 1) return;
|
|
54
|
+
this.readyState = 2;
|
|
55
|
+
|
|
56
|
+
const buf = Buffer.alloc(2);
|
|
57
|
+
buf.writeUInt16BE(code, 0);
|
|
58
|
+
|
|
59
|
+
this._writeFrame(0x8, buf);
|
|
60
|
+
this.socket.end();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// -------------------------------------------------------------------------
|
|
64
|
+
// Core frame processing
|
|
65
|
+
// -------------------------------------------------------------------------
|
|
66
|
+
_onData(chunk) {
|
|
67
|
+
this._buffer = Buffer.concat([this._buffer, chunk]);
|
|
68
|
+
|
|
69
|
+
if (this._buffer.length > MAX_BUFFER_SIZE) {
|
|
70
|
+
this._fail(1009, "buffer overflow");
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
while (true) {
|
|
75
|
+
const frame = this._decodeFrame(this._buffer);
|
|
76
|
+
if (!frame) break;
|
|
77
|
+
|
|
78
|
+
if (frame.error) {
|
|
79
|
+
this._fail(frame.code || 1002, frame.error);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
this._buffer = this._buffer.subarray(frame.totalLength);
|
|
84
|
+
this._handleFrame(frame);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
_handleFrame(f) {
|
|
89
|
+
const { opcode, payload, fin } = f;
|
|
90
|
+
|
|
91
|
+
// control frames
|
|
92
|
+
if (opcode === 0x8) {
|
|
93
|
+
// close
|
|
94
|
+
this.close();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (opcode === 0x9) {
|
|
99
|
+
// ping → pong
|
|
100
|
+
this._writeFrame(0xA, payload);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (opcode === 0xA) {
|
|
105
|
+
this.emit("pong");
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// fragmentation handling
|
|
110
|
+
if (opcode === 0x0) {
|
|
111
|
+
if (!this._fragType) return this._fail(1002, "unexpected continuation");
|
|
112
|
+
|
|
113
|
+
this._fragBuffer.push(payload);
|
|
114
|
+
|
|
115
|
+
if (fin) {
|
|
116
|
+
const full = Buffer.concat(this._fragBuffer);
|
|
117
|
+
this._emitMessage(this._fragType, full);
|
|
118
|
+
this._fragType = null;
|
|
119
|
+
this._fragBuffer = [];
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (opcode === 0x1 || opcode === 0x2) {
|
|
125
|
+
if (this._fragType) return this._fail(1002, "nested fragments");
|
|
126
|
+
|
|
127
|
+
if (!fin) {
|
|
128
|
+
this._fragType = opcode;
|
|
129
|
+
this._fragBuffer = [payload];
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
this._emitMessage(opcode, payload);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
this._fail(1002, "invalid opcode");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
_emitMessage(opcode, payload) {
|
|
141
|
+
if (opcode === 0x1) {
|
|
142
|
+
// text
|
|
143
|
+
try {
|
|
144
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
|
|
145
|
+
this.emit("message", text);
|
|
146
|
+
} catch {
|
|
147
|
+
this._fail(1007, "invalid utf8");
|
|
148
|
+
}
|
|
149
|
+
} else {
|
|
150
|
+
// binary
|
|
151
|
+
this.emit("message", payload);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// -------------------------------------------------------------------------
|
|
156
|
+
// Frame decode (STRICT)
|
|
157
|
+
// -------------------------------------------------------------------------
|
|
158
|
+
_decodeFrame(buf) {
|
|
159
|
+
if (buf.length < 2) return null;
|
|
160
|
+
|
|
161
|
+
const b0 = buf[0];
|
|
162
|
+
const b1 = buf[1];
|
|
163
|
+
|
|
164
|
+
const fin = (b0 & 0x80) !== 0;
|
|
165
|
+
const opcode = b0 & 0x0f;
|
|
166
|
+
|
|
167
|
+
const masked = (b1 & 0x80) !== 0;
|
|
168
|
+
let payloadLen = b1 & 0x7f;
|
|
169
|
+
|
|
170
|
+
// MUST be masked (client → server)
|
|
171
|
+
if (!masked) return { error: "unmasked frame", code: 1002 };
|
|
172
|
+
|
|
173
|
+
// opcode validation
|
|
174
|
+
const valid = [0x0, 0x1, 0x2, 0x8, 0x9, 0xA];
|
|
175
|
+
if (!valid.includes(opcode)) {
|
|
176
|
+
return { error: "invalid opcode", code: 1002 };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
let offset = 2;
|
|
180
|
+
|
|
181
|
+
if (payloadLen === 126) {
|
|
182
|
+
if (buf.length < 4) return null;
|
|
183
|
+
payloadLen = buf.readUInt16BE(2);
|
|
184
|
+
offset = 4;
|
|
185
|
+
} else if (payloadLen === 127) {
|
|
186
|
+
if (buf.length < 10) return null;
|
|
187
|
+
const big = buf.readBigUInt64BE(2);
|
|
188
|
+
if (big > BigInt(MAX_PAYLOAD_SIZE)) {
|
|
189
|
+
return { error: "too large", code: 1009 };
|
|
190
|
+
}
|
|
191
|
+
payloadLen = Number(big);
|
|
192
|
+
offset = 10;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (payloadLen > MAX_PAYLOAD_SIZE) {
|
|
196
|
+
return { error: "too large", code: 1009 };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// control frames rules
|
|
200
|
+
if (opcode >= 0x8) {
|
|
201
|
+
if (!fin) return { error: "fragmented control", code: 1002 };
|
|
202
|
+
if (payloadLen > 125) return { error: "control too large", code: 1002 };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const total = offset + 4 + payloadLen;
|
|
206
|
+
if (buf.length < total) return null;
|
|
207
|
+
|
|
208
|
+
const mask = buf.subarray(offset, offset + 4);
|
|
209
|
+
const payload = Buffer.alloc(payloadLen);
|
|
210
|
+
|
|
211
|
+
for (let i = 0; i < payloadLen; i++) {
|
|
212
|
+
payload[i] = buf[offset + 4 + i] ^ mask[i % 4];
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
fin,
|
|
217
|
+
opcode,
|
|
218
|
+
payload,
|
|
219
|
+
totalLength: total,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// -------------------------------------------------------------------------
|
|
224
|
+
// Frame encode
|
|
225
|
+
// -------------------------------------------------------------------------
|
|
226
|
+
_writeFrame(opcode, payload) {
|
|
227
|
+
if (this.readyState !== 1) return;
|
|
228
|
+
|
|
229
|
+
const len = payload.length;
|
|
230
|
+
let header;
|
|
231
|
+
|
|
232
|
+
if (len < 126) {
|
|
233
|
+
header = Buffer.alloc(2);
|
|
234
|
+
header[1] = len;
|
|
235
|
+
} else if (len < 65536) {
|
|
236
|
+
header = Buffer.alloc(4);
|
|
237
|
+
header[1] = 126;
|
|
238
|
+
header.writeUInt16BE(len, 2);
|
|
239
|
+
} else {
|
|
240
|
+
header = Buffer.alloc(10);
|
|
241
|
+
header[1] = 127;
|
|
242
|
+
header.writeBigUInt64BE(BigInt(len), 2);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
header[0] = 0x80 | opcode;
|
|
246
|
+
|
|
247
|
+
const frame = Buffer.concat([header, payload]);
|
|
248
|
+
|
|
249
|
+
if (!this.socket.write(frame)) {
|
|
250
|
+
this.socket.once("drain", () => {});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_fail(code, reason) {
|
|
255
|
+
try {
|
|
256
|
+
const buf = Buffer.alloc(2);
|
|
257
|
+
buf.writeUInt16BE(code, 0);
|
|
258
|
+
this._writeFrame(0x8, buf);
|
|
259
|
+
} catch {}
|
|
260
|
+
this.socket.destroy();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
_handleClose() {
|
|
264
|
+
if (this.readyState === 3) return;
|
|
265
|
+
this.readyState = 3;
|
|
266
|
+
this.emit("close");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ---------------------------------------------------------------------------
|
|
271
|
+
// Server
|
|
272
|
+
// ---------------------------------------------------------------------------
|
|
273
|
+
export class MiniWebSocketServer extends EventEmitter {
|
|
274
|
+
constructor({ port }, cb) {
|
|
275
|
+
super();
|
|
276
|
+
|
|
277
|
+
this.server = createServer((req, res) => {
|
|
278
|
+
res.writeHead(426);
|
|
279
|
+
res.end("Upgrade required");
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
this.server.on("upgrade", (req, socket, head) => {
|
|
283
|
+
// strict handshake validation
|
|
284
|
+
if (
|
|
285
|
+
req.headers["upgrade"]?.toLowerCase() !== "websocket" ||
|
|
286
|
+
!req.headers["connection"]?.toLowerCase().includes("upgrade") ||
|
|
287
|
+
req.headers["sec-websocket-version"] !== "13"
|
|
288
|
+
) {
|
|
289
|
+
socket.destroy();
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const key = req.headers["sec-websocket-key"];
|
|
294
|
+
if (!key) {
|
|
295
|
+
socket.destroy();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const accept = createHash("sha1")
|
|
300
|
+
.update(key + GUID)
|
|
301
|
+
.digest("base64");
|
|
302
|
+
|
|
303
|
+
// subprotocol (used for auth in your daemon)
|
|
304
|
+
const protocol = req.headers["sec-websocket-protocol"];
|
|
305
|
+
|
|
306
|
+
socket.setNoDelay(true);
|
|
307
|
+
socket.setTimeout(0);
|
|
308
|
+
|
|
309
|
+
socket.write(
|
|
310
|
+
"HTTP/1.1 101 Switching Protocols\r\n" +
|
|
311
|
+
"Upgrade: websocket\r\n" +
|
|
312
|
+
"Connection: Upgrade\r\n" +
|
|
313
|
+
`Sec-WebSocket-Accept: ${accept}\r\n` +
|
|
314
|
+
(protocol ? `Sec-WebSocket-Protocol: ${protocol}\r\n` : "") +
|
|
315
|
+
"\r\n"
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
if (head?.length) socket.unshift(head);
|
|
319
|
+
|
|
320
|
+
this.emit("connection", new MiniWebSocket(socket), req);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
this.server.listen(port, "127.0.0.1", cb);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
close(cb) {
|
|
327
|
+
this.server.close(cb);
|
|
328
|
+
}
|
|
329
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@businessmaps/bifrost",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Bridge any browser web app to Claude Code via MCP",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"bifrost": "./bin/bifrost"
|
|
8
|
+
},
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public"
|
|
11
|
+
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"start": "node bin/bifrost",
|
|
14
|
+
"test": "node --test test/*.test.js",
|
|
15
|
+
"release": "npm test && git tag -f v$(node -p \"require('./package.json').version\") && git push origin main --tags --force"
|
|
16
|
+
},
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=18"
|
|
19
|
+
},
|
|
20
|
+
"license": "Apache-2.0",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/Business-Maps/mcp.git"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"bifrost",
|
|
27
|
+
"mcp",
|
|
28
|
+
"browser",
|
|
29
|
+
"bridge",
|
|
30
|
+
"claude",
|
|
31
|
+
"websocket"
|
|
32
|
+
],
|
|
33
|
+
"files": [
|
|
34
|
+
"bin/",
|
|
35
|
+
"lib/",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"README.md"
|
|
38
|
+
]
|
|
39
|
+
}
|