mcp-newoutlook 0.23.3 → 0.24.0

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/README.md CHANGED
@@ -62,6 +62,7 @@ npx mcp-newoutlook setup
62
62
 
63
63
  - registers the server with the AI apps it finds: Claude Code, Claude Desktop, Cursor, VS Code (Copilot), Windsurf, Gemini CLI and Codex. It shows what it will change and asks first (`--yes` skips the question), only ever adds or updates its own `newoutlook` entry, and keeps a `.mcp-newoutlook.bak` copy of each file it changes. Other MCP clients: register `npx --prefer-online -y mcp-newoutlook@latest` as a stdio server. ChatGPT and claude.ai on the web can't use local servers;
64
64
  - installs the extension in `~/.mcp-newoutlook/extension`;
65
+ - registers the native-messaging host for the Chrome and Edge profiles it finds (see [The native host](#the-native-host));
65
66
  - opens the Extensions page of Chrome and/or Edge, and that folder. The one manual step, in the browser you use Outlook in: turn on *Developer mode* and click *Load unpacked* on the folder;
66
67
  - waits until the extension connects and Outlook answers, then says *Ready*.
67
68
 
@@ -95,7 +96,13 @@ Every AI session starts its own mcp-newoutlook server, and they share the one ex
95
96
 
96
97
  - The first server to start owns the bridge port and the extension connection (`role: "hub"` in `get_version`).
97
98
  - Servers started later connect to the hub with the same pairing token and send their tool calls through it (`role: "peer"`).
98
- - When the hub's session ends, a peer takes over the port within a second. The extension reconnects to it within 30 seconds; calls made in that gap fail with "Browser extension is not connected".
99
+ - When the hub's session ends, it first lets the other sessions' running calls (and open confirmation windows) finish, for up to 5 seconds; calls they make meanwhile go to the next hub. Then a peer takes over the port within a second. The extension reconnects to it within 30 seconds; calls made in that gap fail with "Browser extension is not connected".
100
+
101
+ ### The native host
102
+
103
+ `setup` also registers a native-messaging host (`com.mcp_newoutlook.hub`) for each Chrome or Edge profile folder it finds: a host manifest and a small launcher that starts this Node with `dist/hub.js`. On macOS and Linux both go in the browser's `NativeMessagingHosts` folder; on Windows they go in `%LOCALAPPDATA%\mcp-newoutlook\`, with a registry key under `HKCU\Software\…\NativeMessagingHosts`. Chrome starts the host only for this extension. The hub then lives as long as the browser, not as long as the first AI session, so closing a session doesn't fail the others' calls. `npm run update` rewrites the host files so they point at the current copy and Node. Details: [docs/native-messaging.md](docs/native-messaging.md).
104
+
105
+ The extension tries the native host first. Where it isn't installed, or a policy blocks native messaging, the extension uses the TCP port as described above, and tries native again the next time it reconnects. `get_version` shows which one is in use: `transport: "native"` or `"websocket"` in the extension's status.
99
106
 
100
107
  Connections from web pages are always refused, and peers need the pairing token. While the extension with the fixed id is connected, other copies of it (e.g. an older one loaded from another folder) are turned away.
101
108
 
@@ -123,6 +130,7 @@ Connections from web pages are always refused, and peers need the pairing token.
123
130
  - It relies on Outlook on the web's internal JSON API (`/owa/service.svc`), which Microsoft doesn't document and can change. All request shapes live in `extension/owa.js`.
124
131
  - Without full-text search (see Search syntax), search matches substrings in fields (subject, body, sender, `To`/`Cc` display names).
125
132
  - Emails can't be permanently deleted, only moved to Deleted Items.
133
+ - Teams invitations made through `create_event` have the join link and meeting ID but no passcode: Outlook fetches that from a Teams service this extension doesn't have access to; people join from the link, which carries it.
126
134
  - Outlook doesn't hand out an attached email's original MIME, so its `.eml` is rebuilt from the original headers, body and attachments. It opens normally in mail clients, but isn't byte-identical to the original (e.g. signatures can't be verified).
127
135
  - `download_email` and attached emails in `download_attachments` are limited to 30 MB per email (Outlook's size of the item). A larger one is refused before it is fetched; the error gives its size and a link to open it in Outlook.
128
136
 
package/dist/bridge.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { randomUUID } from "node:crypto";
3
+ import { chmodSync, mkdirSync, unlinkSync } from "node:fs";
4
+ import { createServer as createHttpServer } from "node:http";
5
+ import { connect } from "node:net";
6
+ import { dirname } from "node:path";
3
7
  import { WebSocketServer, WebSocket } from "ws";
4
8
  import { EXTENSION_ORIGIN as TRUSTED_EXTENSION_ORIGIN } from "./extension.js";
5
9
  import { FairQueue } from "./fairqueue.js";
@@ -117,6 +121,20 @@ const PEER_BUFFER_HARD_CAP = 4;
117
121
  * be back (the extension reconnects within about a second) instead of failing at once.
118
122
  */
119
123
  const RECONNECT_GRACE_MS = 3_000;
124
+ /** How long a hub whose session ended keeps serving the calls in flight (#68b). */
125
+ export const DRAIN_MAX_WAIT_MS = 5_000;
126
+ /** How often a server on TCP checks the hub socket for a native host (#68b). */
127
+ const HUB_POLL_MS = 5_000;
128
+ /** True when something accepts connections on a local socket path. */
129
+ function socketAlive(path) {
130
+ return new Promise((resolve) => {
131
+ const s = connect(path);
132
+ const done = (alive) => (s.destroy(), resolve(alive));
133
+ s.setTimeout(1_000, () => done(false));
134
+ s.once("connect", () => done(true));
135
+ s.once("error", () => done(false));
136
+ });
137
+ }
120
138
  export class ExtensionBridge {
121
139
  port;
122
140
  token;
@@ -132,9 +150,13 @@ export class ExtensionBridge {
132
150
  /** Peer only: what the hub said it can do (null: a hub too old to say). */
133
151
  hubCapabilities;
134
152
  wss;
153
+ httpServer; // hub on listenPath: the server under wss
135
154
  sockets = new Map(); // hub: the extensions
136
155
  preferred; // hub: the extension that last answered a call
137
156
  hub; // peer: the hub
157
+ hubIsHost = false; // peer: the hub is the native host, reached on hubSocket
158
+ hostWatch; // a server on TCP: checks hubSocket for a host
159
+ checkingHost = false;
138
160
  peers = new Set();
139
161
  peerLimits = new WeakMap(); // hub: the largest message each peer accepts
140
162
  peerCalls = new WeakMap(); // hub: calls run for each peer, by its id
@@ -159,6 +181,11 @@ export class ExtensionBridge {
159
181
  ownSession = randomUUID();
160
182
  maxMessageBytes;
161
183
  timing;
184
+ listenPath;
185
+ hubSocket;
186
+ socketNeedsToken;
187
+ features;
188
+ onExtensionsChange;
162
189
  /** options: the largest message accepted (a number, as before), or limits and timings for tests. */
163
190
  constructor(port, token, serverVersion, options = {}) {
164
191
  this.port = port;
@@ -174,16 +201,32 @@ export class ExtensionBridge {
174
201
  pickStatusTimeoutMs: o.pickStatusTimeoutMs ?? PICK_STATUS_TIMEOUT_MS,
175
202
  reconnectGraceMs: o.reconnectGraceMs ?? RECONNECT_GRACE_MS,
176
203
  maxPeerBufferedBytes: o.maxPeerBufferedBytes ?? MAX_PEER_BUFFERED_BYTES,
204
+ hubPollMs: o.hubPollMs ?? HUB_POLL_MS,
177
205
  };
206
+ this.listenPath = o.listenPath;
207
+ this.hubSocket = o.listenPath ? undefined : o.hubSocket;
208
+ this.socketNeedsToken = o.socketNeedsToken ?? process.platform === "win32";
209
+ this.features = [...SERVER_FEATURES, ...(o.features ?? []).filter((f) => !SERVER_FEATURES.includes(f))];
210
+ this.onExtensionsChange = o.onExtensionsChange;
178
211
  }
179
212
  /** Becomes the hub, or a peer of the existing hub. Keeps retrying in the background if neither works. */
180
213
  async start() {
181
214
  if (this.closed)
182
215
  return;
216
+ if (this.listenPath) {
217
+ // The native host: the hub on its socket, or nothing (hub.ts then relays to the host there).
218
+ if (await this.listen())
219
+ return this.setRole("hub");
220
+ this.role = "none";
221
+ return;
222
+ }
223
+ // A native host serves the extension: join it (#68b). Otherwise the TCP hub, as before.
224
+ if (this.hubSocket && (await this.join({ path: this.hubSocket })))
225
+ return this.setRole("peer");
183
226
  if (await this.listen())
184
- return this.setRole("hub");
227
+ return (this.setRole("hub"), this.watchHost());
185
228
  if (await this.join())
186
- return this.setRole("peer");
229
+ return (this.setRole("peer"), this.watchHost());
187
230
  this.role = "none";
188
231
  clearTimeout(this.retry);
189
232
  this.retry = setTimeout(() => void this.start(), this.timing.retryMs);
@@ -191,7 +234,15 @@ export class ExtensionBridge {
191
234
  }
192
235
  /** What this server tells extensions and peers it can do. */
193
236
  get capabilities() {
194
- return { maxMessageBytes: this.maxMessageBytes, features: SERVER_FEATURES };
237
+ return { maxMessageBytes: this.maxMessageBytes, features: this.features };
238
+ }
239
+ /**
240
+ * The native host: takes the extension's native-messaging port as an extension connection.
241
+ * Chrome only starts the host for the extension ids in allowed_origins, and hub.ts checks
242
+ * the origin it was given, so it is trusted as our extension.
243
+ */
244
+ attachExtension(conn) {
245
+ this.onConnection(conn, TRUSTED_EXTENSION_ORIGIN, "native");
195
246
  }
196
247
  get connected() {
197
248
  if (this.role === "hub")
@@ -206,6 +257,8 @@ export class ExtensionBridge {
206
257
  }
207
258
  // ------------------------------------------------------------------ hub
208
259
  listen() {
260
+ if (this.listenPath)
261
+ return this.listenOnPath(this.listenPath);
209
262
  return new Promise((resolve) => {
210
263
  const wss = new WebSocketServer({
211
264
  host: "127.0.0.1",
@@ -227,10 +280,84 @@ export class ExtensionBridge {
227
280
  wss.close();
228
281
  resolve(false);
229
282
  });
230
- wss.on("connection", (ws, req) => this.onConnection(ws, req.headers.origin));
283
+ wss.on("connection", (ws, req) => this.onConnection(ws, req.headers.origin, "tcp"));
284
+ });
285
+ }
286
+ /**
287
+ * The native host's hub socket: WebSocket on a local socket. On macOS/Linux the socket is
288
+ * 0600 in a 0700 folder; a socket file left by a host that crashed is replaced. Only local
289
+ * processes connect: any Origin header (a browser page) is refused.
290
+ */
291
+ listenOnPath(path, retried = false) {
292
+ const unix = process.platform !== "win32";
293
+ if (unix) {
294
+ try {
295
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
296
+ chmodSync(dirname(path), 0o700);
297
+ }
298
+ catch (err) {
299
+ this.listenError = err.message;
300
+ return Promise.resolve(false);
301
+ }
302
+ }
303
+ return new Promise((resolve) => {
304
+ const server = createHttpServer((_req, res) => res.writeHead(426).end());
305
+ const wss = new WebSocketServer({
306
+ server,
307
+ maxPayload: this.maxMessageBytes,
308
+ verifyClient: ({ origin }) => !origin,
309
+ });
310
+ let listening = false;
311
+ server.once("listening", () => {
312
+ listening = true;
313
+ try {
314
+ if (unix)
315
+ chmodSync(path, 0o600);
316
+ }
317
+ catch {
318
+ // gone again already; the folder is owner-only either way
319
+ }
320
+ this.wss = wss;
321
+ this.httpServer = server;
322
+ resolve(true);
323
+ });
324
+ wss.on("error", async (err) => {
325
+ if (listening)
326
+ return this.restartHub(`bridge server error: ${err.message}`);
327
+ wss.close();
328
+ server.close();
329
+ if (err.code === "EADDRINUSE" && unix && !retried && !(await socketAlive(path))) {
330
+ // A socket file nobody listens on (a host that crashed): take it over.
331
+ try {
332
+ unlinkSync(path);
333
+ }
334
+ catch {
335
+ // another host was quicker
336
+ }
337
+ return resolve(this.listenOnPath(path, true));
338
+ }
339
+ if (err.code !== "EADDRINUSE")
340
+ this.listenError = err.message;
341
+ resolve(false);
342
+ });
343
+ wss.on("connection", (ws, req) => this.onConnection(ws, req.headers.origin, "socket"));
344
+ server.listen(path);
231
345
  });
232
346
  }
233
- onConnection(ws, origin) {
347
+ /** Closes the listening server (and, on listenPath, the server under it). */
348
+ closeServer() {
349
+ const wss = this.wss;
350
+ const server = this.httpServer;
351
+ this.wss = undefined;
352
+ this.httpServer = undefined;
353
+ return new Promise((r) => (wss ? wss.close(() => r()) : r())).then(() => new Promise((r) => {
354
+ if (!server)
355
+ return r();
356
+ server.closeAllConnections();
357
+ server.close(() => r());
358
+ }));
359
+ }
360
+ onConnection(ws, origin, via) {
234
361
  let authed = false;
235
362
  const authTimer = setTimeout(() => !authed && ws.close(4401, "auth timeout"), 5000);
236
363
  ws.on("message", (raw) => {
@@ -247,15 +374,20 @@ export class ExtensionBridge {
247
374
  if (!msg || typeof msg !== "object")
248
375
  return;
249
376
  if (!authed) {
250
- const trusted = msg.type === "hello" && origin === TRUSTED_EXTENSION_ORIGIN;
251
- if ((!trusted && msg.token !== this.token) || (msg.type !== "hello" && msg.type !== "peer-hello")) {
377
+ // The native port is our extension (Chrome checked); the hub socket is owner-only
378
+ // except on Windows; on TCP, only our extension's origin needs no token.
379
+ const trusted = via === "native" ? msg.type === "hello" : via === "socket" ? !this.socketNeedsToken : msg.type === "hello" && origin === TRUSTED_EXTENSION_ORIGIN;
380
+ const known = via === "native" ? msg.type === "hello" : msg.type === "hello" || msg.type === "peer-hello";
381
+ if ((!trusted && msg.token !== this.token) || !known) {
252
382
  ws.close(4401, "bad token");
253
383
  return;
254
384
  }
255
385
  authed = true;
256
386
  clearTimeout(authTimer);
387
+ // A hello on the hub socket is a second browser's host relaying its extension, which
388
+ // that host checked: ours, on native messaging.
257
389
  if (msg.type === "hello")
258
- this.acceptExtension(ws, msg, origin);
390
+ this.acceptExtension(ws, msg, via === "tcp" ? origin : TRUSTED_EXTENSION_ORIGIN, via === "tcp" ? "websocket" : "native");
259
391
  else
260
392
  this.acceptPeer(ws, msg.version, Number(msg.capabilities?.maxMessageBytes) || MAX_MESSAGE_BYTES);
261
393
  return;
@@ -295,7 +427,7 @@ export class ExtensionBridge {
295
427
  * connected, copies with another id (e.g. an older one loaded from another folder) are
296
428
  * turned away, and connecting ours replaces them.
297
429
  */
298
- acceptExtension(ws, msg, origin) {
430
+ acceptExtension(ws, msg, origin, transport) {
299
431
  const info = {
300
432
  version: String(msg.version ?? "unknown"),
301
433
  browser: msg.browser,
@@ -303,6 +435,7 @@ export class ExtensionBridge {
303
435
  ...(typeof msg.instance === "string" ? { instance: msg.instance } : {}),
304
436
  connection: randomUUID(),
305
437
  features: featuresOf(msg),
438
+ transport,
306
439
  };
307
440
  const ours = origin === TRUSTED_EXTENSION_ORIGIN;
308
441
  const others = [...this.sockets].filter(([s]) => s !== ws);
@@ -331,6 +464,7 @@ export class ExtensionBridge {
331
464
  this.extensions = [...this.sockets.values()];
332
465
  this.extension = (this.preferred && this.sockets.get(this.preferred)) ?? this.extensions.at(-1);
333
466
  this.broadcastState();
467
+ this.onExtensionsChange?.(this.extensions);
334
468
  }
335
469
  /**
336
470
  * The extension a call goes to: the only one, the one that answered last, or else the
@@ -364,7 +498,8 @@ export class ExtensionBridge {
364
498
  }));
365
499
  // A newer server joined: hand the port to it, so its fixes (and what the newer
366
500
  // extension expects) take effect without restarting this AI session.
367
- if (isNewer(peerVersion, this.serverVersion))
501
+ // The native host stays the hub: Chrome connects the extension to it, not to a server.
502
+ if (!this.listenPath && isNewer(peerVersion, this.serverVersion))
368
503
  void this.stepDown(String(peerVersion));
369
504
  }
370
505
  /**
@@ -383,8 +518,7 @@ export class ExtensionBridge {
383
518
  // A confirmation window stays open longer than that: wait for its answer, so the user's
384
519
  // decision isn't lost and the AI doesn't open a second window for the same thing.
385
520
  const until = () => Math.max(end, ...[...this.pending.values()].filter((p) => p.confirm).map((p) => p.deadline));
386
- while ((this.active || this.pending.size || this.turns.waiting) && Date.now() < until() && !this.closed)
387
- await new Promise((r) => setTimeout(r, 25));
521
+ await this.drain(until);
388
522
  if (this.closed || this.role !== "hub")
389
523
  return void (this.steppingDown = false);
390
524
  console.error(`[mcp-newoutlook ${this.serverVersion}] handing the bridge to mcp-newoutlook ${newer}`);
@@ -395,11 +529,51 @@ export class ExtensionBridge {
395
529
  this.restartHub("mcp-newoutlook was updated; try again in a few seconds.", this.timing.retryMs);
396
530
  this.steppingDown = false;
397
531
  }
532
+ /** Hub: calls accepted and not answered yet, or waiting their turn. */
533
+ get inFlight() {
534
+ return !!(this.active || this.pending.size || this.turns.waiting);
535
+ }
536
+ /** Hub: waits until no call is in flight, until() passes, or the bridge is closed. */
537
+ async drain(until) {
538
+ while (this.inFlight && Date.now() < until() && !this.closed)
539
+ await new Promise((r) => setTimeout(r, 25));
540
+ }
541
+ /**
542
+ * Closes the bridge when this server's AI session ends (#68b). A hub with calls in flight
543
+ * (other sessions', or a confirmation window) first stops taking new ones: they get the
544
+ * handover error, so peers send them again through whoever takes over the port. It waits
545
+ * up to maxWaitMs for the running ones, since the AI app may kill the process soon after.
546
+ * A hub with nothing in flight, and a peer, close at once.
547
+ */
548
+ async drainAndClose(maxWaitMs = DRAIN_MAX_WAIT_MS) {
549
+ if (this.closed)
550
+ return;
551
+ if (this.role === "hub" && this.inFlight) {
552
+ this.steppingDown = true;
553
+ const end = Date.now() + maxWaitMs;
554
+ await this.drain(() => end);
555
+ // Everything it accepted was answered: calls still on their way to it were never run,
556
+ // so peers send them again through the new hub (as on a handover) instead of failing.
557
+ if (!this.inFlight && this.role === "hub") {
558
+ const note = JSON.stringify({ type: "handover", version: this.serverVersion });
559
+ for (const peer of this.peers)
560
+ this.sendToPeer(peer, note);
561
+ }
562
+ }
563
+ await this.close();
564
+ }
398
565
  /** Hub: closes the server and every connection, then becomes a hub or peer again. */
399
566
  restartHub(reason, delayMs = 100 + Math.random() * 400) {
567
+ this.stopServing(reason);
568
+ if (this.closed)
569
+ return;
570
+ clearTimeout(this.retry);
571
+ this.retry = setTimeout(() => void this.start(), delayMs);
572
+ this.retry.unref();
573
+ }
574
+ /** Hub: closes the server and every connection (their calls fail with `reason`). */
575
+ stopServing(reason) {
400
576
  this.disruptedAt = Date.now();
401
- const wss = this.wss;
402
- this.wss = undefined;
403
577
  this.role = "none";
404
578
  clearInterval(this.keepAlive);
405
579
  clearInterval(this.peerBeat);
@@ -414,12 +588,8 @@ export class ExtensionBridge {
414
588
  this.preferred = undefined;
415
589
  this.extension = undefined;
416
590
  this.extensions = [];
417
- wss?.close();
418
- if (this.closed)
419
- return;
420
- clearTimeout(this.retry);
421
- this.retry = setTimeout(() => void this.start(), delayMs);
422
- this.retry.unref();
591
+ this.onExtensionsChange?.(this.extensions);
592
+ void this.closeServer();
423
593
  }
424
594
  onExtensionMessage(ws, msg) {
425
595
  if (msg.type === "response" && typeof msg.id === "string")
@@ -585,10 +755,19 @@ export class ExtensionBridge {
585
755
  this.keepAlive.unref();
586
756
  }
587
757
  // ------------------------------------------------------------------ peer
588
- join() {
758
+ /**
759
+ * Joins a hub as a peer: the TCP hub, or the native host on its hub socket (`path`).
760
+ * adopt: decides on the peer-welcome whether to stay (checking for a host); when it says
761
+ * yes, this server first leaves the TCP bridge (see leaveTcp).
762
+ */
763
+ join(target = {}, adopt) {
589
764
  return new Promise((resolve) => {
590
- const ws = new WebSocket(`ws://127.0.0.1:${this.port}`, { maxPayload: this.maxMessageBytes });
765
+ const path = target.path;
766
+ const ws = path
767
+ ? new WebSocket("ws://localhost/", { maxPayload: this.maxMessageBytes, createConnection: () => connect(path) })
768
+ : new WebSocket(`ws://127.0.0.1:${this.port}`, { maxPayload: this.maxMessageBytes });
591
769
  let joined = false;
770
+ let discarded = false;
592
771
  const timer = setTimeout(() => ws.terminate(), this.timing.joinTimeoutMs);
593
772
  // A hub that declares "heartbeat" pings every keepAliveMs. When the pings stop (a hub
594
773
  // suspended or hung), drop it so the reconnect/takeover path runs. Older hubs never ping peers.
@@ -610,10 +789,19 @@ export class ExtensionBridge {
610
789
  }
611
790
  if (!msg || typeof msg !== "object")
612
791
  return;
613
- if (msg.type === "peer-welcome" && !joined) {
792
+ if (msg.type === "peer-welcome" && !joined && !discarded) {
793
+ if (this.closed || (adopt && !adopt(msg))) {
794
+ discarded = true;
795
+ clearTimeout(timer);
796
+ ws.close(1000, "not now");
797
+ return resolve(false);
798
+ }
799
+ if (adopt)
800
+ this.leaveTcp();
614
801
  joined = true;
615
802
  clearTimeout(timer);
616
803
  this.hub = ws;
804
+ this.hubIsHost = !!path;
617
805
  this.hubVersion = String(msg.serverVersion ?? "unknown");
618
806
  this.hubCapabilities = msg.capabilities
619
807
  ? { maxMessageBytes: Number(msg.capabilities.maxMessageBytes) || MAX_MESSAGE_BYTES, features: featuresOf(msg) }
@@ -622,10 +810,13 @@ export class ExtensionBridge {
622
810
  this.extensions = msg.extensions ?? (msg.extension ? [msg.extension] : []);
623
811
  if (this.hubCapabilities?.features.includes("heartbeat"))
624
812
  watch();
813
+ if (adopt)
814
+ this.setRole("peer");
625
815
  resolve(true);
626
816
  }
627
817
  else if (msg.type === "handover") {
628
818
  this.handoverTo = typeof msg.version === "string" ? msg.version : undefined;
819
+ this.disruptedAt = Date.now(); // the hub closes next; calls wait for the new one
629
820
  }
630
821
  else if (msg.type === "ext-state") {
631
822
  this.extension = msg.extension ?? undefined;
@@ -642,17 +833,20 @@ export class ExtensionBridge {
642
833
  ws.on("close", (code) => {
643
834
  clearTimeout(timer);
644
835
  clearTimeout(watchdog);
645
- if (!joined) {
646
- this.listenError =
647
- code === 4401
648
- ? `The mcp-newoutlook server on port ${this.port} rejected this server's token.`
649
- : `Port ${this.port} is in use by another program.`;
836
+ if (!joined || discarded) {
837
+ if (!path && !discarded) {
838
+ this.listenError =
839
+ code === 4401
840
+ ? `The mcp-newoutlook server on port ${this.port} rejected this server's token.`
841
+ : `Port ${this.port} is in use by another program.`;
842
+ }
650
843
  return resolve(false);
651
844
  }
652
845
  if (this.hub !== ws)
653
846
  return;
654
847
  // The hub went away: take over the port or join whoever did.
655
848
  this.hub = undefined;
849
+ this.hubIsHost = false;
656
850
  this.hubVersion = undefined;
657
851
  this.hubCapabilities = undefined;
658
852
  this.extension = undefined;
@@ -674,6 +868,52 @@ export class ExtensionBridge {
674
868
  });
675
869
  });
676
870
  }
871
+ /**
872
+ * A server on TCP (#68b): checks the hub socket every hubPollMs. When a native host serves
873
+ * the extension there and this server's TCP bridge has none, it moves to the host.
874
+ */
875
+ watchHost() {
876
+ if (!this.hubSocket || this.hostWatch)
877
+ return;
878
+ this.hostWatch = setInterval(() => void this.checkHost(), this.timing.hubPollMs);
879
+ this.hostWatch.unref();
880
+ }
881
+ async checkHost() {
882
+ const onTcp = () => !this.closed && !this.hubIsHost && (this.role === "hub" || this.role === "peer") && !this.connected && !this.steppingDown;
883
+ if (this.checkingHost || !this.hubSocket || !onTcp())
884
+ return;
885
+ this.checkingHost = true;
886
+ try {
887
+ await this.join({ path: this.hubSocket }, (welcome) => onTcp() && !!welcome.extension);
888
+ }
889
+ finally {
890
+ this.checkingHost = false;
891
+ }
892
+ }
893
+ /**
894
+ * Leaves the TCP bridge to join the native host, whose extension moved to native messaging.
895
+ * A hub hands its peers over the usual way (a handover note, then a close); they join the
896
+ * host too. Calls waiting here are sent again through the host.
897
+ */
898
+ leaveTcp() {
899
+ if (this.role === "hub") {
900
+ console.error(`[mcp-newoutlook ${this.serverVersion}] the extension moved to the native host; joining it`);
901
+ const note = JSON.stringify({ type: "handover", version: this.serverVersion });
902
+ for (const peer of this.peers)
903
+ this.sendToPeer(peer, note);
904
+ this.stopServing(handoverError);
905
+ }
906
+ else if (this.hub) {
907
+ const old = this.hub;
908
+ this.hub = undefined;
909
+ this.extension = undefined;
910
+ this.extensions = [];
911
+ this.rejectAll(handoverError, old);
912
+ old.close(1000, "moving to the native host");
913
+ }
914
+ this.disruptedAt = Date.now();
915
+ this.role = "none";
916
+ }
677
917
  // ------------------------------------------------------------------ calls
678
918
  /** signal: aborts the call (default: the MCP request's, from callScope); the extension is told to stop. */
679
919
  call(method, params = {}, timeoutMs = 60_000, signal = callScope.getStore()?.signal) {
@@ -695,9 +935,12 @@ export class ExtensionBridge {
695
935
  return this.callOnce(session, method, params, Math.max(1_000, timeoutMs - (Date.now() - started)), signal);
696
936
  }
697
937
  }
698
- /** Waits until a hub other than `via` serves the bridge (or this server serves it again), until deadline. */
938
+ /**
939
+ * Waits until a hub other than `via` serves the bridge, or this server does (again, or as
940
+ * the peer that took over the port), until deadline.
941
+ */
699
942
  async waitForHandover(via, deadline) {
700
- const done = () => this.connected && ((this.role === "peer" && this.hub !== via) || (this.role === "hub" && !this.steppingDown && via === undefined && this.hub === undefined));
943
+ const done = () => this.connected && ((this.role === "peer" && this.hub !== via) || (this.role === "hub" && !this.steppingDown));
701
944
  while (!done() && !this.closed && Date.now() < deadline)
702
945
  await new Promise((r) => setTimeout(r, 20));
703
946
  }
@@ -772,7 +1015,11 @@ export class ExtensionBridge {
772
1015
  });
773
1016
  }
774
1017
  async callNow(session, method, params, timeoutMs, signal) {
775
- // Right after the hub changed or an extension dropped, wait for it to be back.
1018
+ // Right after the hub changed or an extension dropped, wait for it to be back. A peer whose
1019
+ // hub connection is already closing (a handover note came, the close event not yet) counts
1020
+ // as disrupted now: its close handler, which would say so, runs only later.
1021
+ if (this.role === "peer" && this.hub && this.hub.readyState !== WebSocket.OPEN)
1022
+ this.disruptedAt = Date.now();
776
1023
  const graceEnd = Math.min(this.disruptedAt + this.timing.reconnectGraceMs, Date.now() + timeoutMs);
777
1024
  while (!this.connected && !this.closed && Date.now() < graceEnd)
778
1025
  await new Promise((r) => setTimeout(r, 20));
@@ -922,7 +1169,9 @@ export class ExtensionBridge {
922
1169
  }
923
1170
  async close() {
924
1171
  this.closed = true;
1172
+ this.role = "none";
925
1173
  clearTimeout(this.retry);
1174
+ clearInterval(this.hostWatch);
926
1175
  clearInterval(this.keepAlive);
927
1176
  clearInterval(this.peerBeat);
928
1177
  this.rejectAll("mcp-newoutlook is shutting down");
@@ -931,7 +1180,7 @@ export class ExtensionBridge {
931
1180
  s.close();
932
1181
  for (const peer of this.peers)
933
1182
  peer.close();
934
- await new Promise((r) => (this.wss ? this.wss.close(() => r()) : r()));
1183
+ await this.closeServer();
935
1184
  }
936
1185
  }
937
1186
  //# sourceMappingURL=bridge.js.map