mcp-teams 0.3.57 → 0.3.59

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/dist/bridge.js CHANGED
@@ -1,31 +1,20 @@
1
1
  import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { chmodSync, mkdirSync, unlinkSync } from "node:fs";
3
+ import { createServer as createHttpServer } from "node:http";
4
+ import { connect } from "node:net";
5
+ import { dirname } from "node:path";
2
6
  import { WebSocketServer, WebSocket } from "ws";
3
7
  import { EXTENSION_ORIGIN as TRUSTED_EXTENSION_ORIGIN } from "./extension.js";
4
8
  import { FairQueue } from "./fairqueue.js";
5
- /**
6
- * Local WebSocket bridge between MCP server processes and the browser extension.
7
- *
8
- * Several Claude sessions can each run an mcp-teams server, but only one can
9
- * own the port. The first one becomes the hub: the extension connects to it (MV3
10
- * service workers cannot listen), authenticates with the pairing token and answers
11
- * RPC requests. Later servers become peers: they connect to the hub with the same
12
- * token and forward their calls through it. If the hub exits, a peer takes over the
13
- * port and the extension reconnects to it.
14
- *
15
- * Only loopback connections are accepted, and never from a web page: browsers always
16
- * send an Origin header, so connections must come from an extension origin or from
17
- * a local process (no Origin). Both sides prove they know the pairing token without
18
- * sending it: the server opens with a challenge, the client (extension or peer) answers
19
- * with proof(token, "client", challenge) and its own nonce, and the welcome carries
20
- * proof(token, "server", nonce). So neither a program posing as the extension (any
21
- * local process can send any Origin) nor one holding the port while no AI app runs
22
- * gets anything. The extension reads the token from pairing.json, which setup writes
23
- * into its installed folder.
24
- */
25
- /** HMAC-SHA256 of `${role}:${nonce}` with the pairing token, base64url. The extension computes the same (teams.js). */
9
+ import { errorFields, logVersion } from "./hubLog.js";
10
+ /** HMAC-SHA256 of `${role}:${nonce}` with the pairing token, base64url. The extension computes the same (teams.js) for the TCP port. */
26
11
  export function proof(token, role, nonce) {
27
12
  return createHmac("sha256", token).update(`${role}:${nonce}`).digest("base64url");
28
13
  }
14
+ /** The proof role for `side` on a connection of kind `via`: its socket label on the hub socket. */
15
+ function proofRole(side, via) {
16
+ return via === "socket" ? `${side}:socket` : side;
17
+ }
29
18
  function sameProof(a, b) {
30
19
  if (typeof a !== "string")
31
20
  return false;
@@ -37,8 +26,8 @@ const newNonce = () => randomBytes(24).toString("base64url");
37
26
  /**
38
27
  * Protocol features this server supports, sent in welcome, peer-hello and peer-welcome.
39
28
  * - "checksSend": as the hub, it checks the browser it picks for a send (#22).
40
- * Reserved, declared once they ship (ADR 0001): "native" (sent only by a native host) and
41
- * "hostSwitch" (the hub can hand over to a newer build).
29
+ * The native host adds "native" (NativeHostOptions.features, #123). Reserved, declared once it
30
+ * ships (ADR 0001): "hostSwitch" (the hub can hand over to a newer build).
42
31
  */
43
32
  export const SERVER_FEATURES = Object.freeze(["checksSend"]);
44
33
  /** The string features of a message's capabilities; none for a side too old to send them. */
@@ -62,6 +51,8 @@ export const DEFAULT_BRIDGE_OPTIONS = Object.freeze({
62
51
  cancelGraceMs: 2_000,
63
52
  maxPeerBufferedBytes: 64 * 1024 * 1024,
64
53
  maxConcurrentCalls: 4,
54
+ hubPollMs: 5_000,
55
+ tcpRetryMs: 5_000,
65
56
  });
66
57
  /**
67
58
  * Calls that never wait for a turn: the connection's own (status, reload) answer at once, and a
@@ -189,6 +180,7 @@ export const OPEN = WebSocket.OPEN;
189
180
  */
190
181
  export function webSocketTransport({ port, maxMessageBytes }) {
191
182
  return {
183
+ kind: "tcp",
192
184
  listen: (handlers) => new Promise((resolve, reject) => {
193
185
  const wss = new WebSocketServer({
194
186
  host: "127.0.0.1",
@@ -210,11 +202,92 @@ export function webSocketTransport({ port, maxMessageBytes }) {
210
202
  wss.close();
211
203
  reject(err);
212
204
  });
213
- wss.on("connection", (ws, req) => handlers.connection(ws, req.headers.origin));
205
+ wss.on("connection", (ws, req) => handlers.connection(ws, { via: "tcp", origin: req.headers.origin }));
214
206
  }),
215
207
  connect: () => new WebSocket(`ws://127.0.0.1:${port}`, { maxPayload: maxMessageBytes }),
216
208
  };
217
209
  }
210
+ /** True when something accepts connections on a local socket path. */
211
+ function socketAlive(path) {
212
+ return new Promise((resolve) => {
213
+ const s = connect(path);
214
+ const done = (alive) => (s.destroy(), resolve(alive));
215
+ s.setTimeout(1_000, () => done(false));
216
+ s.once("connect", () => done(true));
217
+ s.once("error", () => done(false));
218
+ });
219
+ }
220
+ /**
221
+ * The native host's hub socket (#123): the same WebSocket protocol on a local socket, a Unix socket
222
+ * file or a Windows named pipe. On macOS and Linux the socket is 0600 in a 0700 folder, and a
223
+ * socket file that a crashed host left (nobody listens on it) is replaced. Only local processes
224
+ * connect: any Origin header (a browser page) is refused. Ported from mcp-newoutlook src/bridge.ts
225
+ * listenOnPath, socketAlive and join({ path }) (commit eb9d32f).
226
+ */
227
+ export function socketTransport({ path, maxMessageBytes }) {
228
+ const unix = process.platform !== "win32";
229
+ const listen = (handlers, retried) => {
230
+ if (unix) {
231
+ try {
232
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
233
+ chmodSync(dirname(path), 0o700);
234
+ }
235
+ catch (err) {
236
+ return Promise.reject(err);
237
+ }
238
+ }
239
+ return new Promise((resolve, reject) => {
240
+ const server = createHttpServer((_req, res) => res.writeHead(426).end());
241
+ const wss = new WebSocketServer({
242
+ server,
243
+ maxPayload: maxMessageBytes,
244
+ verifyClient: ({ origin }) => !origin,
245
+ });
246
+ let listening = false;
247
+ server.once("listening", () => {
248
+ listening = true;
249
+ try {
250
+ if (unix)
251
+ chmodSync(path, 0o600);
252
+ }
253
+ catch {
254
+ // gone again already; the folder is owner-only either way
255
+ }
256
+ const closeWss = () => new Promise((r) => wss.close(() => r()));
257
+ const closeServer = () => new Promise((r) => {
258
+ server.closeAllConnections();
259
+ server.close(() => r());
260
+ });
261
+ resolve({ close: () => closeWss().then(closeServer) });
262
+ });
263
+ server.on("error", async (err) => {
264
+ if (listening)
265
+ return handlers.error(err);
266
+ wss.close();
267
+ server.close();
268
+ if (err.code === "EADDRINUSE" && unix && !retried && !(await socketAlive(path))) {
269
+ // A socket file nobody listens on (a host that crashed): take it over.
270
+ try {
271
+ unlinkSync(path);
272
+ }
273
+ catch {
274
+ // another host was quicker
275
+ }
276
+ return listen(handlers, true).then(resolve, reject);
277
+ }
278
+ reject(err);
279
+ });
280
+ wss.on("error", () => { }); // the server's own errors come through `server`
281
+ wss.on("connection", (ws, req) => handlers.connection(ws, { via: "socket", origin: req.headers.origin }));
282
+ server.listen(path);
283
+ });
284
+ };
285
+ return {
286
+ kind: "socket",
287
+ listen: (handlers) => listen(handlers, false),
288
+ connect: () => new WebSocket("ws://localhost/", { maxPayload: maxMessageBytes, createConnection: () => connect(path) }),
289
+ };
290
+ }
218
291
  function describeSocketError(err, limit) {
219
292
  return err.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ? LOST_CALL.tooLarge(Math.round(limit / 1024 / 1024)) : LOST_CALL.socketError(err.message);
220
293
  }
@@ -237,7 +310,14 @@ export class ExtensionBridge {
237
310
  * Its "checksSend" feature, or the bare checksSend: true of hubs before #115.
238
311
  */
239
312
  hubChecksSend = false;
240
- listener; // hub: where extensions and peers connect
313
+ /** Hub: where extensions and peers connect; the native host has its hub socket and its TCP listener (#123). */
314
+ listeners = [];
315
+ tcpListener; // the native host: its TCP listener, for peers only
316
+ tcpRetry; // the native host: its next try for the TCP port
317
+ nudging; // the native host: its connection to an older TCP hub, which hands over to it
318
+ hubOnSocket = false; // peer: the hub is the native host, reached on its hub socket
319
+ hostWatch; // a server on TCP with a hubSocket: checks it for the host
320
+ checkingHost = false;
241
321
  sockets = new Map(); // hub: the extensions
242
322
  preferred; // hub: the extension that last answered a call
243
323
  hub; // peer: the hub
@@ -259,6 +339,7 @@ export class ExtensionBridge {
259
339
  backlogged = new WeakSet(); // hub: peers over maxPeerBufferedBytes at the last tick
260
340
  legacyReloaded = false; // hub: an extension of 0.2.0 or older was told to reload
261
341
  opts;
342
+ native;
262
343
  boundPort; // the port it got when it first listened (port 0 picks a free one); kept for later takeovers
263
344
  /** The 4th argument is the options, or (as before) just the largest message size. */
264
345
  constructor(requestedPort, token, serverVersion, options = {}) {
@@ -266,9 +347,27 @@ export class ExtensionBridge {
266
347
  this.token = token;
267
348
  this.serverVersion = serverVersion;
268
349
  const given = typeof options === "number" ? { maxMessageBytes: options } : options;
350
+ const { hubSocket, hostSocket, socketNeedsProof, features, onExtensionsChange, onEvent, ...timings } = given;
269
351
  // A key given as undefined keeps its default (spreading it would overwrite the default).
270
- const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));
352
+ const defined = Object.fromEntries(Object.entries(timings).filter(([, v]) => v !== undefined));
271
353
  this.opts = { ...DEFAULT_BRIDGE_OPTIONS, ...defined };
354
+ this.native = { hubSocket: hostSocket ? undefined : hubSocket, hostSocket, socketNeedsProof, features, onExtensionsChange, onEvent };
355
+ }
356
+ /** The native host (#123): the hub on its hub socket, never a peer. */
357
+ get isHost() {
358
+ return !!this.native.hostSocket;
359
+ }
360
+ /** Peer only: true when the hub is the native host, reached on its hub socket; false for another session's TCP hub. */
361
+ get hubIsHost() {
362
+ return this.role === "peer" && this.hubOnSocket;
363
+ }
364
+ /**
365
+ * The native host: takes the extension's native-messaging port as an extension connection.
366
+ * Chrome only starts the host for the extension ids in its manifest's allowed_origins, and
367
+ * dist/hub.js checks the origin it was given, so it is trusted as our extension (no proof).
368
+ */
369
+ attachExtension(conn) {
370
+ this.onConnection(conn, { via: "native", origin: TRUSTED_EXTENSION_ORIGIN });
272
371
  }
273
372
  /**
274
373
  * The bridge's port: the one it was given, or with port 0 the free one it got when it first
@@ -282,7 +381,8 @@ export class ExtensionBridge {
282
381
  }
283
382
  /** What this server tells extensions, peers and the hub it can do (#115). */
284
383
  get capabilities() {
285
- return { features: [...SERVER_FEATURES], maxMessageBytes: this.maxMessageBytes };
384
+ const extra = (this.native.features ?? []).filter((f) => !SERVER_FEATURES.includes(f));
385
+ return { features: [...SERVER_FEATURES, ...extra], maxMessageBytes: this.maxMessageBytes };
286
386
  }
287
387
  /** Read-only, for tests: calls waiting for an answer, and (hub) peers' calls being run. */
288
388
  get inFlight() {
@@ -307,10 +407,24 @@ export class ExtensionBridge {
307
407
  async start() {
308
408
  if (this.closed)
309
409
  return;
310
- if (await this.listen())
311
- return this.setRole("hub");
312
- if (await this.join())
410
+ const socket = this.socketTransport;
411
+ if (this.isHost) {
412
+ // The native host: the hub on its socket, or nothing (dist/hub.js then relays to the host there).
413
+ if (await this.listen(socket)) {
414
+ this.setRole("hub");
415
+ this.native.onEvent?.("host", { socket: "listening" });
416
+ return void this.holdTcp();
417
+ }
418
+ this.role = "none";
419
+ return;
420
+ }
421
+ // The native host serves the extension: join it (#123). Otherwise TCP, as before.
422
+ if (socket && (await this.join(socket)))
313
423
  return this.setRole("peer");
424
+ if (await this.listen(this.tcpTransport))
425
+ return (this.setRole("hub"), this.watchHost());
426
+ if (await this.join(this.tcpTransport))
427
+ return (this.setRole("peer"), this.watchHost());
314
428
  this.role = "none";
315
429
  clearTimeout(this.retry);
316
430
  this.retry = setTimeout(() => void this.start(), this.opts.retryMs);
@@ -328,27 +442,127 @@ export class ExtensionBridge {
328
442
  this.listenError = undefined;
329
443
  }
330
444
  // ------------------------------------------------------------------ hub
331
- /** How it listens and joins: the WebSocket on its port, the only transport so far (#123). */
332
- get transport() {
445
+ /** The WebSocket on its port. */
446
+ get tcpTransport() {
333
447
  return webSocketTransport({ port: this.port, maxMessageBytes: this.maxMessageBytes });
334
448
  }
335
- listen() {
336
- return this.transport
337
- .listen({
338
- connection: (conn, origin) => this.onConnection(conn, origin),
339
- error: (err) => this.restartHub(LOST_CALL.serverError(err.message)),
340
- })
341
- .then((listener) => {
342
- this.listener = listener;
343
- this.boundPort = listener.port ?? this.boundPort;
344
- return true;
345
- }, (err) => {
449
+ /** The native host's hub socket (#123): where the host listens, or where a server looks for it. */
450
+ get socketTransport() {
451
+ const path = this.native.hostSocket ?? this.native.hubSocket;
452
+ return path ? socketTransport({ path, maxMessageBytes: this.maxMessageBytes }) : undefined;
453
+ }
454
+ /** Peers on the hub socket must prove the token only where the socket isn't owner-only (a Windows pipe). */
455
+ get socketNeedsProof() {
456
+ return this.native.socketNeedsProof ?? process.platform === "win32";
457
+ }
458
+ /** Listens on `transport` as the hub; false when the address is taken (or failed: listenError). */
459
+ listen(transport) {
460
+ return this.listenOn(transport, (err) => this.restartHub(LOST_CALL.serverError(err.message))).then((listener) => !!listener, (err) => {
346
461
  if (err.code !== "EADDRINUSE")
347
462
  this.listenError = err.message;
348
463
  return false;
349
464
  });
350
465
  }
351
- onConnection(ws, origin) {
466
+ async listenOn(transport, onError) {
467
+ const listener = await transport.listen({
468
+ connection: (conn, from) => this.onConnection(conn, from),
469
+ error: onError,
470
+ });
471
+ this.listeners.push(listener);
472
+ if (transport.kind === "tcp")
473
+ this.boundPort = listener.port ?? this.boundPort;
474
+ return listener;
475
+ }
476
+ /**
477
+ * The native host: listens on the TCP port too, for peers only (ADR decision 4). While another
478
+ * server holds the port it tries again every tcpRetryMs (#123 decision 7). A TCP hub older than
479
+ * this host is joined as a newer peer, so its stepDown hands the port over (decision 8); one as
480
+ * new or newer moves to the host itself once the host has the extension (watchHost).
481
+ */
482
+ async holdTcp() {
483
+ clearTimeout(this.tcpRetry);
484
+ if (this.closed || this.role !== "hub" || this.tcpListener)
485
+ return;
486
+ let again = this.opts.tcpRetryMs;
487
+ try {
488
+ const listener = await this.listenOn(this.tcpTransport, (err) => {
489
+ // The TCP listener failed: the host stays the hub on its socket and listens again later.
490
+ const { name, code } = errorFields(err);
491
+ this.native.onEvent?.("tcp", { error: name, code });
492
+ this.listeners = this.listeners.filter((l) => l !== listener);
493
+ if (this.tcpListener === listener)
494
+ this.tcpListener = undefined;
495
+ void listener.close();
496
+ this.scheduleTcp(this.opts.tcpRetryMs);
497
+ });
498
+ if (this.closed || this.role !== "hub")
499
+ return void this.closeListener(listener);
500
+ this.tcpListener = listener;
501
+ this.native.onEvent?.("tcp", { port: listener.port });
502
+ return;
503
+ }
504
+ catch (err) {
505
+ if (err.code === "EADDRINUSE" && (await this.nudgeTcpHub()))
506
+ again = 20;
507
+ }
508
+ this.scheduleTcp(again);
509
+ }
510
+ scheduleTcp(ms) {
511
+ if (this.closed || this.role !== "hub")
512
+ return;
513
+ clearTimeout(this.tcpRetry);
514
+ this.tcpRetry = setTimeout(() => void this.holdTcp(), ms);
515
+ this.tcpRetry.unref();
516
+ }
517
+ closeListener(listener) {
518
+ this.listeners = this.listeners.filter((l) => l !== listener);
519
+ return listener.close();
520
+ }
521
+ /**
522
+ * The native host: joins the TCP hub on the port as a peer of its own version. A hub older than
523
+ * that hands over to it (its existing stepDown(), #123 decision 8); this waits until that hub has
524
+ * closed and resolves true, so the port is tried again at once. Any other answer (a hub as new or
525
+ * newer, another program, no answer) resolves false: try again later.
526
+ */
527
+ nudgeTcpHub() {
528
+ return new Promise((resolve) => {
529
+ const ws = this.tcpTransport.connect();
530
+ this.nudging = ws;
531
+ const nonce = newNonce();
532
+ let challenged = false;
533
+ let older = false;
534
+ const timer = setTimeout(() => ws.terminate(), this.opts.joinTimeoutMs);
535
+ ws.on("message", (raw) => {
536
+ let msg;
537
+ try {
538
+ msg = JSON.parse(raw.toString());
539
+ }
540
+ catch {
541
+ return;
542
+ }
543
+ if (msg?.type === "challenge" && !challenged && typeof msg.nonce === "string") {
544
+ challenged = true;
545
+ ws.send(JSON.stringify({ type: "peer-hello", proof: proof(this.token, "client", msg.nonce), nonce, version: this.serverVersion, capabilities: this.capabilities }));
546
+ }
547
+ else if (msg?.type === "peer-welcome" && !older) {
548
+ clearTimeout(timer);
549
+ if (!challenged || !sameProof(msg.proof, proof(this.token, "server", nonce)) || !isNewer(this.serverVersion, msg.serverVersion))
550
+ return void ws.close(1000, "not now");
551
+ // It hands over once its own calls are done; until then this stays its (idle) peer.
552
+ older = true;
553
+ this.native.onEvent?.("tcp", { handover: logVersion(msg.serverVersion) });
554
+ }
555
+ });
556
+ ws.on("error", () => { });
557
+ ws.on("close", () => {
558
+ clearTimeout(timer);
559
+ if (this.nudging === ws)
560
+ this.nudging = undefined;
561
+ resolve(older);
562
+ });
563
+ });
564
+ }
565
+ onConnection(ws, { via, origin }) {
352
566
  let authed = false;
353
567
  const authTimer = setTimeout(() => !authed && ws.close(4401, "auth timeout"), this.opts.authTimeoutMs);
354
568
  const challenge = newNonce();
@@ -366,21 +580,34 @@ export class ExtensionBridge {
366
580
  if (!authed) {
367
581
  if (msg.type !== "hello" && msg.type !== "peer-hello")
368
582
  return void ws.close(4401, "bad token");
583
+ // The native host takes extensions only on native messaging (or relayed on its socket): on
584
+ // its TCP port it serves peers only (ADR decision 4, #123 decision 9).
585
+ if (via === "tcp" && this.isHost && msg.type === "hello") {
586
+ this.native.onEvent?.("refused", { reason: "extension on the TCP port" });
587
+ return void ws.close(4403, "extensions connect to the native host by native messaging");
588
+ }
589
+ if (via === "native" && msg.type !== "hello")
590
+ return void ws.close(4401, "bad token");
369
591
  // Clients up to 0.2.0 send the token itself (peers, or an extension paired by hand).
370
- const proven = sameProof(msg.proof, proof(this.token, "client", challenge)) || (typeof msg.token === "string" && msg.token === this.token);
371
- if (!proven) {
592
+ // Only on TCP: the bare token, and a proof without the socket label (see ProofRole).
593
+ const proven = sameProof(msg.proof, proof(this.token, proofRole("client", via), challenge)) || (via === "tcp" && typeof msg.token === "string" && msg.token === this.token);
594
+ // The native port is our extension (Chrome checked it); the hub socket is owner-only except on Windows.
595
+ const trusted = via === "native" || (via === "socket" && !this.socketNeedsProof);
596
+ if (!proven && !trusted) {
372
597
  // Our extension up to 0.2.0 says hello with neither; it is only told to reload.
373
- if (msg.type === "hello" && origin === TRUSTED_EXTENSION_ORIGIN && msg.token == null && msg.proof == null)
598
+ if (via === "tcp" && msg.type === "hello" && origin === TRUSTED_EXTENSION_ORIGIN && msg.token == null && msg.proof == null)
374
599
  return this.reloadLegacy(ws);
375
600
  return void ws.close(4401, "bad token");
376
601
  }
377
602
  authed = true;
378
603
  clearTimeout(authTimer);
379
- const welcome = typeof msg.nonce === "string" ? { proof: proof(this.token, "server", msg.nonce) } : {};
604
+ const welcome = typeof msg.nonce === "string" ? { proof: proof(this.token, proofRole("server", via), msg.nonce) } : {};
605
+ // A hello on the hub socket is another browser's host relaying its extension, which that
606
+ // host checked: ours, on native messaging.
380
607
  if (msg.type === "hello")
381
- this.acceptExtension(ws, msg, welcome, origin);
608
+ this.acceptExtension(ws, msg, welcome, via === "tcp" ? origin : TRUSTED_EXTENSION_ORIGIN);
382
609
  else
383
- this.acceptPeer(ws, msg.version, welcome);
610
+ this.acceptPeer(ws, msg.version, welcome, via);
384
611
  return;
385
612
  }
386
613
  if (this.sockets.has(ws))
@@ -468,6 +695,7 @@ export class ExtensionBridge {
468
695
  this.extensions = [...this.sockets.values()];
469
696
  this.extension = (this.preferred && this.sockets.get(this.preferred)) ?? this.extensions.at(-1);
470
697
  this.broadcastState();
698
+ this.native.onExtensionsChange?.(this.extensions);
471
699
  }
472
700
  /**
473
701
  * The extension a call goes to: the only one, the one that answered last, or else the
@@ -517,8 +745,10 @@ export class ExtensionBridge {
517
745
  }
518
746
  setTimeout(() => ws.close(4426, "extension update required"), 1_000).unref();
519
747
  }
520
- acceptPeer(ws, peerVersion, welcome) {
748
+ acceptPeer(ws, peerVersion, welcome, via) {
521
749
  this.peers.add(ws);
750
+ this.native.onEvent?.("peer", { version: logVersion(peerVersion), via });
751
+ ws.on("close", () => this.native.onEvent?.("peer-left", { via }));
522
752
  // heartbeatMs: this hub pings the peer that often, so the peer can tell when it stops.
523
753
  ws.send(JSON.stringify({
524
754
  type: "peer-welcome",
@@ -534,7 +764,8 @@ export class ExtensionBridge {
534
764
  this.startPeerBeat(ws);
535
765
  // A newer server joined: hand the port to it, so its fixes (and what the newer
536
766
  // extension expects) take effect without restarting this AI session.
537
- if (isNewer(peerVersion, this.serverVersion))
767
+ // The native host stays the hub: Chrome connects the extension to it, not to a server.
768
+ if (!this.isHost && isNewer(peerVersion, this.serverVersion))
538
769
  void this.stepDown(String(peerVersion));
539
770
  }
540
771
  /**
@@ -558,8 +789,19 @@ export class ExtensionBridge {
558
789
  }
559
790
  /** Hub: closes the server and every connection, then becomes a hub or peer again. */
560
791
  restartHub(reason, delayMs = 100 + Math.random() * 400) {
561
- const listener = this.listener;
562
- this.listener = undefined;
792
+ this.stopServing(reason);
793
+ if (this.closed)
794
+ return;
795
+ clearTimeout(this.retry);
796
+ this.retry = setTimeout(() => void this.start(), delayMs);
797
+ this.retry.unref();
798
+ }
799
+ /** Hub: closes its listeners and every connection; their calls fail with `reason`. */
800
+ stopServing(reason) {
801
+ const listeners = this.listeners;
802
+ this.listeners = [];
803
+ this.tcpListener = undefined;
804
+ clearTimeout(this.tcpRetry);
563
805
  this.role = "none";
564
806
  clearInterval(this.keepAlive);
565
807
  this.stopPeerBeat();
@@ -574,12 +816,9 @@ export class ExtensionBridge {
574
816
  this.preferred = undefined;
575
817
  this.extension = undefined;
576
818
  this.extensions = [];
577
- void listener?.close();
578
- if (this.closed)
579
- return;
580
- clearTimeout(this.retry);
581
- this.retry = setTimeout(() => void this.start(), delayMs);
582
- this.retry.unref();
819
+ this.native.onExtensionsChange?.(this.extensions);
820
+ for (const l of listeners)
821
+ void l.close();
583
822
  }
584
823
  onExtensionMessage(ws, msg) {
585
824
  if (typeof msg.id !== "string")
@@ -745,9 +984,17 @@ export class ExtensionBridge {
745
984
  this.peerBeat = undefined;
746
985
  }
747
986
  // ------------------------------------------------------------------ peer
748
- join() {
987
+ /**
988
+ * Joins the hub on `transport` as a peer: the TCP hub, or the native host on its hub socket.
989
+ * adopt (a server on TCP checking for the host): decides on the peer-welcome whether to stay; when
990
+ * it says yes, this server first leaves the TCP bridge (leaveTcp). Ported from mcp-newoutlook
991
+ * src/bridge.ts join(target, adopt) (commit eb9d32f).
992
+ */
993
+ join(transport, adopt) {
749
994
  return new Promise((resolve) => {
750
- const ws = this.transport.connect();
995
+ const ws = transport.connect();
996
+ const onSocket = transport.kind === "socket";
997
+ let discarded = false;
751
998
  let joined = false;
752
999
  let challenged = false;
753
1000
  let forged = false;
@@ -791,17 +1038,28 @@ export class ExtensionBridge {
791
1038
  return;
792
1039
  if (msg.type === "challenge" && !challenged && typeof msg.nonce === "string") {
793
1040
  challenged = true;
794
- ws.send(JSON.stringify({ type: "peer-hello", proof: proof(this.token, "client", msg.nonce), nonce, version: this.serverVersion, capabilities: this.capabilities }));
1041
+ ws.send(JSON.stringify({ type: "peer-hello", proof: proof(this.token, proofRole("client", transport.kind), msg.nonce), nonce, version: this.serverVersion, capabilities: this.capabilities }));
795
1042
  }
796
- else if (msg.type === "peer-welcome" && !joined) {
1043
+ else if (msg.type === "peer-welcome" && !joined && !discarded) {
797
1044
  // Only the real hub can answer our nonce; never forward calls to anything else.
798
- if (!challenged || !sameProof(msg.proof, proof(this.token, "server", nonce))) {
1045
+ if (!challenged || !sameProof(msg.proof, proof(this.token, proofRole("server", transport.kind), nonce))) {
799
1046
  forged = true;
800
1047
  return void ws.terminate();
801
1048
  }
1049
+ if (adopt && (this.closed || !adopt(msg))) {
1050
+ discarded = true;
1051
+ clearTimeout(timer);
1052
+ ws.close(1000, "not now");
1053
+ return resolve(false);
1054
+ }
1055
+ if (adopt)
1056
+ this.leaveTcp();
802
1057
  joined = true;
803
1058
  clearTimeout(timer);
804
1059
  this.hub = ws;
1060
+ this.hubOnSocket = onSocket;
1061
+ if (adopt)
1062
+ this.setRole("peer");
805
1063
  this.hubVersion = String(msg.serverVersion ?? "unknown");
806
1064
  this.hubCapabilities = capabilitiesOf(msg);
807
1065
  this.hubChecksSend = this.hubCapabilities.features.includes("checksSend") || msg.checksSend === true;
@@ -830,7 +1088,15 @@ export class ExtensionBridge {
830
1088
  ws.on("close", (code) => {
831
1089
  clearTimeout(timer);
832
1090
  clearTimeout(watchdog);
1091
+ if (discarded)
1092
+ return;
833
1093
  if (!joined) {
1094
+ if (onSocket) {
1095
+ // No native host there (or not ours): the TCP logic runs next. Only a refused proof is worth saying.
1096
+ if (code === 4401)
1097
+ this.listenError = "The mcp-teams native host on the hub socket rejected this server's token (run `npx mcp-teams setup` again).";
1098
+ return resolve(false);
1099
+ }
834
1100
  this.listenError =
835
1101
  code === 4401
836
1102
  ? `The mcp-teams server on port ${this.port} rejected this server's token.`
@@ -843,6 +1109,7 @@ export class ExtensionBridge {
843
1109
  return;
844
1110
  // The hub went away: take over the port or join whoever did.
845
1111
  this.hub = undefined;
1112
+ this.hubOnSocket = false;
846
1113
  this.hubVersion = undefined;
847
1114
  this.hubCapabilities = undefined;
848
1115
  this.hubChecksSend = false;
@@ -858,6 +1125,52 @@ export class ExtensionBridge {
858
1125
  });
859
1126
  });
860
1127
  }
1128
+ /**
1129
+ * A server on TCP whose config enables the native host (#123 decision 7): checks the hub socket
1130
+ * every hubPollMs. When the host serves the extension there and this server's TCP bridge has none,
1131
+ * it moves to the host. Ported from mcp-newoutlook src/bridge.ts watchHost (commit eb9d32f).
1132
+ */
1133
+ watchHost() {
1134
+ if (!this.native.hubSocket || this.hostWatch)
1135
+ return;
1136
+ this.hostWatch = setInterval(() => void this.checkHost(), this.opts.hubPollMs);
1137
+ this.hostWatch.unref();
1138
+ }
1139
+ async checkHost() {
1140
+ const socket = this.socketTransport;
1141
+ const onTcp = () => !this.closed && !this.hubOnSocket && (this.role === "hub" || this.role === "peer") && !this.connected && !this.steppingDown && !this.draining;
1142
+ if (this.checkingHost || !socket || !onTcp())
1143
+ return;
1144
+ this.checkingHost = true;
1145
+ try {
1146
+ await this.join(socket, (welcome) => onTcp() && !!welcome.extension);
1147
+ }
1148
+ finally {
1149
+ this.checkingHost = false;
1150
+ }
1151
+ }
1152
+ /**
1153
+ * Leaves the TCP bridge to join the native host, which has the extension. As the hub it closes
1154
+ * the port and its peers, which join the host too (or, servers that don't look for it, the host's
1155
+ * TCP listener once it has the port). Nothing reached an extension here (this server had none),
1156
+ * so whatever waits fails with "try again". Ported from mcp-newoutlook src/bridge.ts leaveTcp
1157
+ * (commit eb9d32f), without its handover note, which Teams' peers don't know.
1158
+ */
1159
+ leaveTcp() {
1160
+ if (this.role === "hub") {
1161
+ console.error(`[mcp-teams ${this.serverVersion}] the extension is on the native host; joining it`);
1162
+ this.stopServing(LOST_CALL.hubRestarted);
1163
+ }
1164
+ else if (this.hub) {
1165
+ const old = this.hub;
1166
+ this.hub = undefined;
1167
+ this.extension = undefined;
1168
+ this.extensions = [];
1169
+ this.rejectAll(LOST_CALL.hubRestarted);
1170
+ old.close(1000, "moving to the native host");
1171
+ }
1172
+ this.role = "none";
1173
+ }
861
1174
  // ------------------------------------------------------------------ calls
862
1175
  /**
863
1176
  * Calls the extension. Aborting `signal` withdraws the call (see withdraw). `deadline` (ms since
@@ -1141,6 +1454,9 @@ export class ExtensionBridge {
1141
1454
  async close() {
1142
1455
  this.closed = true;
1143
1456
  clearTimeout(this.retry);
1457
+ clearTimeout(this.tcpRetry);
1458
+ clearInterval(this.hostWatch);
1459
+ this.nudging?.terminate();
1144
1460
  clearInterval(this.keepAlive);
1145
1461
  this.stopPeerBeat();
1146
1462
  this.dropTurns();
@@ -1150,7 +1466,10 @@ export class ExtensionBridge {
1150
1466
  s.close();
1151
1467
  for (const peer of this.peers)
1152
1468
  peer.close();
1153
- await this.listener?.close();
1469
+ const listeners = this.listeners;
1470
+ this.listeners = [];
1471
+ this.tcpListener = undefined;
1472
+ await Promise.all(listeners.map((l) => l.close()));
1154
1473
  }
1155
1474
  }
1156
1475
  //# sourceMappingURL=bridge.js.map