mcp-teams 0.3.61 → 0.3.63

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.
@@ -1,6 +1,8 @@
1
- // Service worker: connects to the local MCP server over WebSocket and runs Teams
2
- // requests inside an open Teams tab, with the session Teams itself uses.
1
+ // Service worker: connects to the local MCP server (through the native host while config.json
2
+ // turns it on, else over WebSocket) and runs Teams requests inside an open Teams tab, with the
3
+ // session Teams itself uses.
3
4
 
5
+ import { NATIVE_MAX_MESSAGE_BYTES, Reassembler } from "./chunks.js";
4
6
  import * as teams from "./teams.js";
5
7
 
6
8
  const VERSION = chrome.runtime.getManifest().version;
@@ -9,7 +11,9 @@ const DEFAULT_PORT = 47393;
9
11
  * What hello declares to the hub (#115), as mcp-newoutlook's extension does (EXTENSION_FEATURES in
10
12
  * its extension/background.js). No features yet: "native" is only for a native host's port.
11
13
  * maxMessageBytes: the largest message it takes, the server's own MAX_MESSAGE_BYTES (Chrome's
12
- * WebSocket sets no lower limit of its own).
14
+ * WebSocket sets no lower limit of its own). It is what the extension receives, on native messaging
15
+ * too (the host's chunks are joined up to it); what it sends there is capped at Chrome's 64 MB
16
+ * (NATIVE_MAX_MESSAGE_BYTES).
13
17
  */
14
18
  const CAPABILITIES = Object.freeze({ features: Object.freeze([]), maxMessageBytes: 256 * 1024 * 1024 });
15
19
  const CONFIRM_TIMEOUT_MS = 5 * 60_000;
@@ -2062,33 +2066,157 @@ export function stopReconnecting() {
2062
2066
  }
2063
2067
 
2064
2068
  /**
2065
- * The pairing token: one saved under Advanced, else the one setup wrote into this
2066
- * folder (pairing.json, only in the installed copy). Null when there is none.
2069
+ * This folder's pairing.json ({ token, nativeHost }), which servers and setup write into the
2070
+ * installed copy; null without one. The pairing token is one saved under Advanced, else its
2071
+ * token. `nativeHost: true` while config.json turns the native host on (#123).
2067
2072
  */
2068
- async function pairingToken(saved) {
2069
- if (saved) return saved;
2073
+ async function pairingFile() {
2070
2074
  try {
2071
2075
  const res = await fetch(chrome.runtime.getURL("pairing.json"), { cache: "no-store" });
2072
- return res.ok ? ((await res.json()).token ?? null) : null;
2076
+ return res.ok ? await res.json() : null;
2073
2077
  } catch {
2074
2078
  return null;
2075
2079
  }
2076
2080
  }
2077
2081
 
2082
+ /** The native-messaging host (#123, ADR 0001), dist/hub.js, which setup registers. */
2083
+ const NATIVE_HOST = "com.mcp_teams.hub";
2084
+ /** WebSocket readyState values, which a native connection uses too. */
2085
+ const OPEN = 1;
2086
+ const CLOSED = 3;
2087
+
2088
+ const formatSize = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`);
2089
+ /** `text`'s UTF-8 size, or its length when even 3 bytes a character stay within `max` (no need to count). */
2090
+ const utf8Bytes = (text, max) => (text.length * 3 <= max ? text.length : new TextEncoder().encode(text).length);
2091
+
2092
+ /**
2093
+ * The answer that goes instead of one too large for the native connection: the hub would drop the
2094
+ * whole connection on it (or Chrome refuse it), and the call would wait for its time limit.
2095
+ * Wording as mcp-newoutlook's dispatch (commit cf8cc72).
2096
+ */
2097
+ const tooLarge = (id, detail) => ({
2098
+ type: "response",
2099
+ id,
2100
+ ok: false,
2101
+ error: `The answer was too large to pass on over the native connection (${detail}). Nothing else was affected. Ask for less at once (fewer messages, a shorter range), or open it in Teams.`,
2102
+ });
2103
+
2104
+ /**
2105
+ * A connection to the native host over chrome.runtime.connectNative, shaped like the WebSocket
2106
+ * connect() uses: readyState, send(text, msg), close(), and onmessage({ data }) and onclose({ code })
2107
+ * (code null). It is open at once. Messages the host split into chunks (over Chrome's 1 MB) are
2108
+ * joined first. Throws when Chrome refuses at once. Ported from mcp-newoutlook
2109
+ * extension/background.js (openNative; commit df54b52).
2110
+ *
2111
+ * A response larger than the host takes (maxMessageBytes: Chrome's 64 MB, or less when the host's
2112
+ * welcome declares less) goes as a short error instead, as does one Chrome refuses to post; that
2113
+ * error is no larger than the host takes either (see fitting).
2114
+ */
2115
+ function openNative() {
2116
+ const port = chrome.runtime.connectNative(NATIVE_HOST);
2117
+ const chunks = new Reassembler();
2118
+ const conn = {
2119
+ transport: "native",
2120
+ readyState: OPEN,
2121
+ maxMessageBytes: NATIVE_MAX_MESSAGE_BYTES,
2122
+ onmessage: null,
2123
+ onclose: null,
2124
+ /** `msg`: the message `text` is, when the caller has it (saves parsing it again). */
2125
+ send(text, msg = JSON.parse(text)) {
2126
+ if (conn.readyState !== OPEN) return;
2127
+ const bytes = utf8Bytes(text, conn.maxMessageBytes);
2128
+ const answer = msg?.type === "response";
2129
+ const over = bytes > conn.maxMessageBytes;
2130
+ if (over) {
2131
+ if (!answer) return;
2132
+ msg = fitting(msg.id, `${formatSize(bytes)}; the limit is ${formatSize(conn.maxMessageBytes)}`);
2133
+ if (!msg) return;
2134
+ }
2135
+ try {
2136
+ port.postMessage(msg);
2137
+ } catch (err) {
2138
+ // Chrome refused it (a disconnected port's onDisconnect follows, and the hub fails the call
2139
+ // then); on an open port, an answer still goes, short, so the call doesn't wait for nothing.
2140
+ if (!answer || over) return;
2141
+ const short = fitting(msg.id, err?.message ?? String(err));
2142
+ try {
2143
+ if (short) port.postMessage(short);
2144
+ } catch {
2145
+ // closed meanwhile
2146
+ }
2147
+ }
2148
+ },
2149
+ close() {
2150
+ if (conn.readyState === CLOSED) return;
2151
+ port.disconnect();
2152
+ closed();
2153
+ },
2154
+ };
2155
+ /**
2156
+ * The error answer for request `id` that fits within what the host takes: the full explanation,
2157
+ * else a bare "too large" (a host that declares a tiny limit); null when not even that fits.
2158
+ */
2159
+ const fitting = (id, detail) => {
2160
+ for (const reply of [tooLarge(id, detail), { type: "response", id, ok: false, error: "too large" }]) {
2161
+ if (utf8Bytes(JSON.stringify(reply), conn.maxMessageBytes) <= conn.maxMessageBytes) return reply;
2162
+ }
2163
+ return null;
2164
+ };
2165
+ // Later, as a WebSocket's close event: the caller may still be setting the connection up.
2166
+ const closed = () => {
2167
+ conn.readyState = CLOSED;
2168
+ chunks.clear();
2169
+ setTimeout(() => conn.onclose?.({ code: null }), 0);
2170
+ };
2171
+ port.onMessage.addListener((msg) => {
2172
+ if (conn.readyState !== OPEN) return;
2173
+ if (msg?.type !== "chunk") return conn.onmessage?.({ data: JSON.stringify(msg) });
2174
+ const text = chunks.add(msg);
2175
+ if (text !== null) conn.onmessage?.({ data: text });
2176
+ });
2177
+ port.onDisconnect.addListener(() => {
2178
+ // Read even when unused: Chrome warns about an unchecked lastError otherwise.
2179
+ void chrome.runtime.lastError;
2180
+ if (conn.readyState !== CLOSED) closed();
2181
+ });
2182
+ return conn;
2183
+ }
2184
+
2185
+ let tcpRefused = false; // a TCP hub said 4403 (use native messaging), until a TCP hub welcomes us
2186
+ let skipNative = false; // native just failed before its welcome: the next connect() uses TCP
2187
+
2188
+ /**
2189
+ * Whether connect() goes to the native host: pairing.json says config.json turns it on, or a TCP
2190
+ * hub refused this extension with 4403 (only the native host does: ADR decision 4, #123 decision
2191
+ * 9). Not right after native failed before its welcome (that connect goes to TCP), and never
2192
+ * without connectNative (no nativeMessaging permission). Off, everything stays on TCP.
2193
+ */
2194
+ function nativeFirst(pairing, canNative) {
2195
+ const skip = skipNative;
2196
+ skipNative = false;
2197
+ return !skip && (pairing?.nativeHost === true || tcpRefused) && canNative;
2198
+ }
2199
+
2078
2200
  /**
2079
2201
  * Connects to the local MCP server. Both sides prove they know the pairing token without
2080
2202
  * sending it (see src/bridge.ts): the extension answers the server's challenge, and acts
2081
2203
  * on requests only after the server answered its own nonce. Any other program that holds
2082
2204
  * the port gets nothing.
2205
+ *
2206
+ * While config.json turns the native host on (#123, see nativeFirst), it connects by native
2207
+ * messaging instead: Chrome starts the host for this extension only, so hello goes at once with
2208
+ * no proof, and the welcome still has to prove the nonce. A native port that closes before its
2209
+ * welcome (no host registered, the host off or failing) falls back to the TCP port at once.
2083
2210
  */
2084
2211
  async function connect() {
2085
2212
  if (!reconnecting || starting || (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING))) return;
2086
2213
  clearTimeout(retryTimer);
2087
2214
  retryTimer = null;
2088
2215
  starting = true;
2089
- let token, port, instance;
2216
+ let token, port, instance, pairing;
2090
2217
  try {
2091
2218
  ({ token, port, instance } = await chrome.storage.local.get(["token", "port", "instance"]));
2219
+ pairing = await pairingFile();
2092
2220
  // Identifies this browser profile to the server across reconnects (Chrome and Edge,
2093
2221
  // or two profiles, can be connected at the same time).
2094
2222
  if (!instance) {
@@ -2101,10 +2229,23 @@ async function connect() {
2101
2229
  // stopReconnecting() may have run while the storage read was waiting.
2102
2230
  if (ws || !reconnecting) return;
2103
2231
  state = "connecting";
2104
- const socket = new WebSocket(`ws://127.0.0.1:${port || DEFAULT_PORT}`);
2232
+ // Read once, here: the socket's handlers below never touch chrome (#99: a test's teardown removes
2233
+ // it while a connection may still be closing).
2234
+ const canNative = typeof chrome.runtime.connectNative === "function";
2235
+ let socket = null;
2236
+ if (nativeFirst(pairing, canNative)) {
2237
+ try {
2238
+ socket = openNative();
2239
+ } catch {
2240
+ // Chrome refused at once: the TCP port.
2241
+ }
2242
+ }
2243
+ const native = socket !== null;
2244
+ socket ??= new WebSocket(`ws://127.0.0.1:${port || DEFAULT_PORT}`);
2105
2245
  ws = socket;
2106
2246
  const nonce = crypto.randomUUID();
2107
- let secret = null;
2247
+ const secret = token || pairing?.token || null;
2248
+ const noPairing = "This copy of the extension has no pairing file. Run `npx mcp-teams setup` and load the extension from the folder it shows.";
2108
2249
  let challenged = false;
2109
2250
  let authed = false;
2110
2251
  let opened = false;
@@ -2132,12 +2273,12 @@ async function connect() {
2132
2273
  if (!authed) {
2133
2274
  if (msg.type === "challenge" && !challenged && typeof msg.nonce === "string") {
2134
2275
  challenged = true;
2135
- secret = await pairingToken(token);
2136
- if (!secret) return refuse("This copy of the extension has no pairing file. Run `npx mcp-teams setup` and load the extension from the folder it shows.");
2276
+ if (!secret) return refuse(noPairing);
2137
2277
  const proof = await teams.pairingProof(secret, "client", msg.nonce);
2138
2278
  socket.send(JSON.stringify({ type: "hello", proof, nonce, version: VERSION, browser: browserName(), instance, capabilities: CAPABILITIES }));
2139
2279
  } else if (msg.type === "welcome" && !checking) {
2140
- const notProven = () => refuse(`The program on port ${port || DEFAULT_PORT} could not prove it is your mcp-teams server, so the extension doesn't answer it.`);
2280
+ const who = native ? "The native host" : `The program on port ${port || DEFAULT_PORT}`;
2281
+ const notProven = () => refuse(`${who} could not prove it is your mcp-teams server, so the extension doesn't answer it.`);
2141
2282
  checking = (async () => {
2142
2283
  if (!secret || msg.proof !== (await teams.pairingProof(secret, "server", nonce))) return notProven();
2143
2284
  if (ws !== socket || socket.readyState !== WebSocket.OPEN) return; // a newer connection's state stays
@@ -2145,6 +2286,10 @@ async function connect() {
2145
2286
  state = "connected";
2146
2287
  lastError = null;
2147
2288
  retryMs = RETRY_MIN_MS;
2289
+ if (!native) tcpRefused = false;
2290
+ // The native host takes no more than it declares, and Chrome passes it no more than 64 MB.
2291
+ const hostMax = Number(msg.capabilities?.maxMessageBytes);
2292
+ if (native && hostMax > 0) socket.maxMessageBytes = Math.min(NATIVE_MAX_MESSAGE_BYTES, hostMax);
2148
2293
  const heartbeatMs = Number(msg.heartbeatMs);
2149
2294
  watchHeartbeat(socket, heartbeatMs > 0 ? Math.max(MIN_HEARTBEAT_TIMEOUT_MS, Math.round(2.25 * heartbeatMs)) : HEARTBEAT_TIMEOUT_MS);
2150
2295
  })().catch(notProven);
@@ -2156,7 +2301,8 @@ async function connect() {
2156
2301
  if (watchdog?.socket === socket) watchHeartbeat(socket, watchdog.ms);
2157
2302
  return;
2158
2303
  }
2159
- await dispatch(msg, (reply) => socket.readyState === WebSocket.OPEN && socket.send(JSON.stringify(reply)), socket);
2304
+ // The reply object goes along for a native connection (a WebSocket ignores it).
2305
+ await dispatch(msg, (reply) => socket.readyState === WebSocket.OPEN && socket.send(JSON.stringify(reply), reply), socket);
2160
2306
  };
2161
2307
  socket.onclose = (ev) => {
2162
2308
  // Nobody can be told the outcome of what came on this connection: withdraw it
@@ -2165,12 +2311,29 @@ async function connect() {
2165
2311
  stopWatchdog(socket);
2166
2312
  if (ws && ws !== socket) return; // replaced by a newer connection (reconnectNow)
2167
2313
  ws = null;
2314
+ if (native && !authed) {
2315
+ // No native host here, or it failed before its welcome: the TCP port, at once (native is
2316
+ // tried again on the next connect).
2317
+ skipNative = true;
2318
+ clearTimeout(retryTimer);
2319
+ retryTimer = null;
2320
+ return void connect();
2321
+ }
2168
2322
  // When a server session ends, another one takes over the port within a second:
2169
2323
  // retry soon, backing off to the alarm's pace.
2170
2324
  clearTimeout(retryTimer);
2171
2325
  retryTimer = reconnecting ? setTimeout(connect, retryMs) : null;
2172
2326
  retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
2173
- if (state === "unauthorized" && !authed && lastError) {
2327
+ if (ev.code === 4403) {
2328
+ // The native host holds the port and takes extensions only by native messaging (#123
2329
+ // decision 9): the retry goes there, backing off as above.
2330
+ tcpRefused = true;
2331
+ state = "disconnected";
2332
+ lastError =
2333
+ canNative
2334
+ ? "The mcp-teams native host holds the port and refuses extensions there; connecting to it by native messaging."
2335
+ : "The mcp-teams native host holds the port and refuses extensions there, and this copy of the extension can't use native messaging (no nativeMessaging permission).";
2336
+ } else if (state === "unauthorized" && !authed && lastError) {
2174
2337
  // refuse() said why.
2175
2338
  } else if (opened && !challenged) {
2176
2339
  state = "unauthorized";
@@ -2185,6 +2348,13 @@ async function connect() {
2185
2348
  socket.onerror = () => {
2186
2349
  lastError = "MCP server not reachable (is your AI client running mcp-teams?)";
2187
2350
  };
2351
+ if (native) {
2352
+ // Chrome vouches for this extension to its native host (allowed_origins): hello goes at once,
2353
+ // without waiting for (or answering) a challenge. A relaying host adds its own proof.
2354
+ challenged = true;
2355
+ if (!secret) refuse(noPairing);
2356
+ else socket.send(JSON.stringify({ type: "hello", nonce, version: VERSION, browser: browserName(), instance, capabilities: CAPABILITIES }));
2357
+ }
2188
2358
  }
2189
2359
 
2190
2360
  /** Requests being run, by id, so they can be withdrawn (a cancel from the server, or their connection closed). */
@@ -0,0 +1,68 @@
1
+ // Joins the slices of a message the native host split (#123, src/native.ts toExtensionFrames):
2
+ // Chrome passes at most 1 MB per message from a host, so the host sends a larger one as
3
+ // {type:"chunk", id, seq, last, data}, `data` being a slice of the message's JSON text and `seq`
4
+ // counting from 0. A set that is incomplete after CHUNK_TTL_MS, arrives out of order or grows
5
+ // past CHUNK_MAX_CHARS is dropped.
6
+ //
7
+ // Ported from mcp-newoutlook extension/chunks.js (Reassembler; commit df54b52). The limit is the
8
+ // largest message this extension takes (its hello's maxMessageBytes).
9
+
10
+ /** Chrome's limit for one message from the extension to its native host (64 MiB). */
11
+ export const NATIVE_MAX_MESSAGE_BYTES = 64 * 1024 * 1024;
12
+
13
+ /** The largest message joined (the JSON text's length). */
14
+ export const CHUNK_MAX_CHARS = 256 * 1024 * 1024;
15
+ /** How long a set may take to arrive completely. */
16
+ export const CHUNK_TTL_MS = 60_000;
17
+
18
+ export class Reassembler {
19
+ /** id -> { parts, next, size, timer, dropped } */
20
+ #sets = new Map();
21
+ #maxChars;
22
+ #ttlMs;
23
+
24
+ constructor({ maxChars = CHUNK_MAX_CHARS, ttlMs = CHUNK_TTL_MS } = {}) {
25
+ this.#maxChars = maxChars;
26
+ this.#ttlMs = ttlMs;
27
+ }
28
+
29
+ /** Adds one chunk; returns the whole message's text when this slice completes it, else null. */
30
+ add(chunk) {
31
+ const { id, seq, last, data } = chunk ?? {};
32
+ if ((typeof id !== "string" && typeof id !== "number") || !Number.isInteger(seq) || seq < 0 || typeof data !== "string") return null;
33
+ let set = this.#sets.get(id);
34
+ if (!set) {
35
+ if (seq !== 0) return null; // the start of this set is missing (or it was dropped and forgotten)
36
+ set = { parts: [], next: 0, size: 0, dropped: false, timer: setTimeout(() => this.#forget(id, set), this.#ttlMs) };
37
+ this.#sets.set(id, set);
38
+ }
39
+ if (set.dropped) {
40
+ // The rest of a dropped set is ignored, until its last slice frees the id.
41
+ if (last) this.#forget(id, set);
42
+ return null;
43
+ }
44
+ if (seq !== set.next || set.size + data.length > this.#maxChars) {
45
+ set.parts = [];
46
+ set.dropped = true;
47
+ if (last) this.#forget(id, set);
48
+ return null;
49
+ }
50
+ set.parts.push(data);
51
+ set.next++;
52
+ set.size += data.length;
53
+ if (!last) return null;
54
+ this.#forget(id, set);
55
+ return set.parts.join("");
56
+ }
57
+
58
+ /** Drops every set (the connection closed). */
59
+ clear() {
60
+ for (const s of this.#sets.values()) clearTimeout(s.timer);
61
+ this.#sets.clear();
62
+ }
63
+
64
+ #forget(id, set) {
65
+ clearTimeout(set.timer);
66
+ if (this.#sets.get(id) === set) this.#sets.delete(id);
67
+ }
68
+ }
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvoz9Wexl4ZqY9YtEyBZsu/Qi5Ft5EjNUNB8b30wgt3AR8TjXI5UumcPQFBIm7ZfvBsjgrh6tBJlygsgFbZ5cB1EiI+WSz/2Wcqwz4eowKMXXPvGuDGrO+2O2zbSpTG19/MwTljI+g0TLfn8Vkoqd8z9MskKk+vCZjjV0Jk8QjVEdHypgM7H8zTuUM06SO12IIZMdeE3IURzf35zbjlfPPkJiDWoo3wB9nxAvLd57xrQhPUB/lGtCJk9mS3SY+/VwOlG5kJ9WS/RCHXcs5Qs7huIlKIatmFz7YiducvTR3DKBbjqbMTyqHzXkmkUmJRqzsYtgtKcz0C0cjFOt6uNdhwIDAQAB",
4
4
  "name": "mcp-teams bridge",
5
- "version": "0.3.61",
5
+ "version": "0.3.63",
6
6
  "description": "Lets AI assistants (via the mcp-teams MCP server) read and search Microsoft Teams chats, channels and meeting transcripts and, with your explicit confirmation, post messages.",
7
7
  "minimum_chrome_version": "116",
8
8
  "icons": {
@@ -20,7 +20,8 @@
20
20
  "scripting",
21
21
  "tabs",
22
22
  "webRequest",
23
- "alarms"
23
+ "alarms",
24
+ "nativeMessaging"
24
25
  ],
25
26
  "host_permissions": [
26
27
  "https://teams.cloud.microsoft/*",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-teams",
3
- "version": "0.3.61",
3
+ "version": "0.3.63",
4
4
  "description": "MCP server that lets AI assistants work with Microsoft Teams (web) through a Chrome/Edge extension bridge",
5
5
  "keywords": ["mcp", "model-context-protocol", "teams", "microsoft-teams", "microsoft-365", "chat", "claude", "chrome-extension"],
6
6
  "repository": {