Repository navigation
Expand file tree
/
Copy pathroom-server.js
More file actions
5856 lines (5527 loc) · 387 KB
/
Copy pathroom-server.js
File metadata and controls
5856 lines (5527 loc) · 387 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Exec Room: a local web room backed by real headless Claude Code agents.
// Runs `claude -p --agent` on the owner's Claude plan instead of calling the API with a key,
// so Coen keeps his tools and memory across messages via --resume. When Coen consults a peer
// through the Agent tool, that peer's work is streamed into their own card.
// Chats and a job log are kept as append-only NDJSON under data/.
import express from 'express';
import { execFile, execFileSync, spawn } from 'child_process';
import crypto from 'crypto';
import dns from 'dns';
import fs from 'fs';
import http from 'http';
import https from 'https';
import { Marked } from 'marked';
import net from 'net';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import zlib from 'zlib';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Load configuration: what the whole install needs (the Notion databases and token, connectors to hide).
// Everything else is set per room, in the room.
function loadConfig() {
const configPath = process.env.ROOM_CONFIG_FILE || path.join(__dirname, 'room.config.json');
if (!fs.existsSync(configPath)) {
// New install: use minimal defaults
return {
notionDatabases: {},
notionChannels: ['X', 'LinkedIn', 'Substack Note', 'Substack Post', 'Instagram', 'Blog'],
};
}
try {
return JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (err) {
console.error(`Failed to load room.config.json: ${err.message}`);
process.exit(1);
}
}
const CONFIG = loadConfig();
const PORT = Number(process.env.PORT || 4179);
const HOST = '127.0.0.1';
const ALLOWED_HOSTS = new Set([`localhost:${PORT}`, `127.0.0.1:${PORT}`]);
const ALLOWED_ORIGINS = new Set([...ALLOWED_HOSTS].map((h) => `http://${h}`));
const DATA_DIR = process.env.ROOM_DATA_DIR || path.join(__dirname, 'data');
const ROOMS_DIR = path.join(DATA_DIR, 'rooms');
const INDEX_FILE = path.join(ROOMS_DIR, 'index.json');
const SPACES_FILE = path.join(DATA_DIR, 'workspaces.json');
const JOBS_FILE = path.join(DATA_DIR, 'jobs.ndjson');
const RECS_FILE = path.join(DATA_DIR, 'recommendations.json');
const DRAFTS_DIR = path.join(__dirname, 'drafts');
// Draft names as the execs are told to write them; no leading dot, no path separators.
const DRAFT_NAME = /^[\w-][\w.-]*\.md$/;
const DRAFT_MAX_BYTES = 512 * 1024;
// Files the owner attaches to one message. They live in the temp folder, outside the repo and every room's folders,
// where no run can read without a rule (checked live on 2026-10-07 with the room's flags), so only the run they
// were sent to gets one. One folder per job, deleted when that job ends. Per port, so a second room on this Mac
// (a sandbox, the suite) only clears its own leftovers at start-up.
const ATTACH_PREFIX = 'exec-room-attachments-';
const ATTACH_DIR = path.join(os.tmpdir(), `${ATTACH_PREFIX}${PORT}`);
const ATTACH_MAX_FILES = 3;
const ATTACH_MAX_BYTES = 5 * 1024 * 1024;
// What the Read tool can open: text, PDFs and images. The value is how the file's first bytes are checked.
const ATTACH_TYPES = { txt: 'text', md: 'text', csv: 'text', pdf: 'pdf', png: 'png', jpg: 'jpeg', jpeg: 'jpeg', gif: 'gif', webp: 'webp' };
const ATTACH_JOB_DIR = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
// Saving a file into a room's save folder (the save_file proposal). The server does it once the owner approves; agents
// never get a download tool or write access outside drafts/. Two sources: a web link, or one of the agents' drafts.
// Web files are kept to documents, data and images: nothing that runs. A file the server saves gets no macOS
// "downloaded from the internet" flag, so a program saved this way would open without that warning.
const SAVE_MAX_FOLDERS = 10;
const SAVE_MAX_BYTES = 25 * 1024 * 1024;
const SAVE_TIMEOUT_MS = Number(process.env.ROOM_SAVE_TIMEOUT_MS) || 60000;
const SAVE_MAX_REDIRECTS = 5;
// What a web file may be, by extension. The value is how its content is checked (saveLooksLike).
const SAVE_WEB_TYPES = { pdf: 'pdf', png: 'png', jpg: 'jpeg', jpeg: 'jpeg', gif: 'gif', webp: 'webp', txt: 'text', md: 'text', csv: 'text', json: 'json', docx: 'docx', xlsx: 'xlsx', pptx: 'pptx' };
// A draft is saved as it is (.md) or as a Word file the server builds itself (docxFromMarkdown), on any system.
const DRAFT_FORMATS = ['md', 'docx'];
// For the suite only: one plain-http host:port on this computer that downloads may use (a real room refuses this
// computer and the home network). Said at start-up whenever it is set.
const SAVE_TEST_HOST = process.env.ROOM_TEST_SAVE_HOST || '';
const STDERR_CAP = 8 * 1024;
// Never passed on to a run: an API key or token (pay-as-you-go billing), another endpoint, or another provider
// (Bedrock, Vertex, Foundry). Each of them takes a run off the owner's Claude plan without anything showing it.
const AUTH_ENV = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'ROOM_ANTHROPIC_API_KEY'];
// Room agents get what the room gives them (their own description, the room's note and brief, the message) and
// nothing else. Without these two switches Claude Code also hands every run, and every agent consulted inside it,
// the CLAUDE.md files of this folder, of the folders above it and of any folder an agent works in (this repo's
// notes for contributors, the owner's personal file, whatever other tools write into such files), plus the memory
// index Claude Code keeps for the folder. It works like a .gitignore for the room: the files stay where they are,
// and the runs the room starts don't load them. An agent can still open such a file itself where it may read. Both
// names come from the Claude Code program (seen in 2.1.289), not from its documentation, so contextCheck() tries
// them every time the room starts.
// The owner can turn this around with `"agentsGetClaudeFiles": true` in room.config.json: then no switch is set,
// agents are given those files as any Claude Code session would be, and there is nothing to check.
const OWN_CONTEXT_ONLY = CONFIG.agentsGetClaudeFiles !== true;
const OWN_CONTEXT_ENV = OWN_CONTEXT_ONLY ? { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {};
// What the room starts gets a short, fixed environment, not the server's own: a program inherits every variable of
// the one that starts it, and the server's environment holds whatever the shell it was started from had (tokens of
// other tools included). Tried on 2026-10-13 with Claude Code 2.1.289 and gh on macOS: both find their login with
// these alone. BASE_ENV is what any program needs to run and reach the network.
const BASE_ENV = ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TERM', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ',
'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'no_proxy', 'all_proxy',
'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR',
// Linux: where programs keep their settings and reach the login keyring.
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_STATE_HOME', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS'];
// A plan login kept somewhere other than the default: a token, or a config folder of its own. Never on a key.
const PLAN_ENV = ['CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CONFIG_DIR'];
const GH_ENV = ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GH_HOST', 'GH_CONFIG_DIR'];
// For a setup that needs more (a version manager's own variables, say): names in ROOM_PASS_ENV, separated by commas,
// are passed on as well. Never one of AUTH_ENV. ROOM_TEST_* is the test suite's own and goes to its stand-ins.
const PASS_ENV = (process.env.ROOM_PASS_ENV || '').split(',').map((n) => n.trim()).filter((n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n) && !AUTH_ENV.includes(n));
function passedOn(names) {
const env = {};
for (const name of [...names, ...PASS_ENV, ...Object.keys(process.env).filter((n) => n.startsWith('ROOM_TEST_'))]) {
if (process.env[name] !== undefined) env[name] = process.env[name];
}
return env;
}
// The environment of everything the room starts with `claude`: a job's run, and the start-up check.
function runEnv() {
const env = { ...passedOn(KEY_MODE ? BASE_ENV : [...BASE_ENV, ...PLAN_ENV]), ...OWN_CONTEXT_ENV };
// No API key, other endpoint or other provider reaches a run from the server's environment (none of them is on
// the list above, and they are removed from the server's own environment at start): the CLI uses the logged-in
// Claude plan, never pay-as-you-go credits, unless the room was started on a key.
for (const name of AUTH_ENV) delete env[name];
if (KEY_MODE) {
fs.mkdirSync(KEY_CONFIG_DIR, { recursive: true, mode: 0o700 });
env.ANTHROPIC_API_KEY = API_KEY;
env.CLAUDE_CONFIG_DIR = KEY_CONFIG_DIR;
}
return env;
}
// How runs are paid for: the owner's Claude plan (the default), or an Anthropic API key, which is
// pay-as-you-go. Chosen when the room starts (ROOM_AUTH=api-key, `npm run room:key`) and fixed until it stops, so
// the two never run side by side. Never guessed from a key that happens to be in the environment.
function stopStart(message) {
console.error(message);
process.exit(1);
}
const AUTH = process.env.ROOM_AUTH || 'subscription';
if (!['subscription', 'api-key'].includes(AUTH)) stopStart(`ROOM_AUTH must be "subscription" (the Claude plan, the default) or "api-key", not "${AUTH}".`);
const KEY_MODE = AUTH === 'api-key';
// The key is read once at start-up, from ROOM_ANTHROPIC_API_KEY or from 1Password (ROOM_ANTHROPIC_API_KEY_REF, an
// op:// reference), and kept in memory only: it goes to the `claude` runs and nowhere else (not to data/, the job
// log, the page or an error text).
function readApiKey() {
if (process.env.ROOM_ANTHROPIC_API_KEY) return process.env.ROOM_ANTHROPIC_API_KEY.trim();
if (!process.env.ROOM_ANTHROPIC_API_KEY_REF) return '';
try {
return execFileSync('op', ['read', process.env.ROOM_ANTHROPIC_API_KEY_REF], { encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch {
return '';
}
}
const API_KEY = KEY_MODE ? readApiKey() : '';
if (KEY_MODE && !API_KEY) stopStart('ROOM_AUTH is "api-key" but no key was found. Set ROOM_ANTHROPIC_API_KEY, or ROOM_ANTHROPIC_API_KEY_REF to its 1Password reference (op://…), or start the room on the Claude plan with `npm run room`.');
// From here on the key, and everything else that decides how a run is paid, is out of the server's own environment:
// what the server starts besides `claude` (gh, and op for the Notion token) inherits that environment and has no
// use for any of it. runEnv() puts the key into the environment of a `claude` run and nowhere else.
for (const name of AUTH_ENV) delete process.env[name];
const scrub = (text) => (API_KEY ? String(text).split(API_KEY).join('[API key removed]') : text);
// The same through everything an event holds. No way for the key into a run's context is known (no tool reads the
// environment); this is the second line: if it ever got there, it would not leave in a reply, a tool's details, a
// proposal or the transcript. It is an exact match, so a key that is encoded or split on purpose passes, and what
// an agent sends to the web (a search, a fetched address) has left before the room sees it.
const scrubDeep = (v) => (!API_KEY ? v
: typeof v === 'string' ? scrub(v)
: Array.isArray(v) ? v.map(scrubDeep)
: v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrubDeep(x)])) : v);
// A text cut to `cap` characters with the key taken out. Cutting first could leave half a key at the end, which
// no longer matches; so a key that starts before the cut is kept whole until it has been replaced.
function cutScrubbed(raw, cap) {
if (!API_KEY) return raw.slice(0, cap);
let end = cap;
for (let i = raw.indexOf(API_KEY); i !== -1 && i < cap; i = raw.indexOf(API_KEY, i + 1)) end = Math.max(end, i + API_KEY.length);
return scrub(raw.slice(0, end));
}
const fileHasKey = (file) => {
if (!API_KEY) return false;
try { return fs.readFileSync(file, 'utf8').includes(API_KEY); } catch { return false; }
};
// With a Claude plan login around, the CLI uses that login and not the key (checked on 2026-10-10: an invalid key
// still got an answer). So key-mode runs get a config folder of their own, where no plan login exists: only then is
// the key what pays, and a wrong key fails. It sits in data/, which no agent can read. The claude.ai connectors
// (Notion, Microsoft 365) come with the plan login, so they don't exist in this mode.
const KEY_CONFIG_DIR = path.join(DATA_DIR, 'claude-key');
// Spend caps, key mode only. One run: the CLI's own --max-budget-usd, checked after each turn, so a run can pass it
// by one turn. One day (this Mac's date): summed from the job log, checked before any run starts, also the ones
// the room starts itself (a nudge, a chain's next step).
function capOf(name, fallback) {
const raw = process.env[name];
if (raw == null || raw === '') return fallback;
if (!(Number(raw) > 0)) stopStart(`${name} must be a number above 0, not "${raw}".`);
return Number(raw);
}
const RUN_CAP_USD = KEY_MODE ? capOf('ROOM_RUN_CAP_USD', 2) : null;
const DAY_CAP_USD = KEY_MODE ? capOf('ROOM_DAY_CAP_USD', 10) : null;
const dayOf = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
let keySpend = null; // { day, usd }: what key-mode runs cost today
// Job lines from before this (no `auth`) were paid by the plan, so they don't count.
function keySpentToday() {
const day = dayOf(new Date());
if (keySpend && keySpend.day === day) return keySpend.usd;
keySpend = { day, usd: 0 };
let lines = [];
try { lines = fs.readFileSync(JOBS_FILE, 'utf8').split('\n'); } catch { /* no job log yet */ }
for (const line of lines) {
let j;
try { j = JSON.parse(line); } catch { continue; }
if (j && j.kind === 'job' && j.auth === 'api-key' && j.endedAt && dayOf(new Date(j.endedAt)) === day) keySpend.usd += Number(j.costUsd) || 0;
}
return keySpend.usd;
}
// A failed run's reason (Claude's own words, or stderr) is kept in the job log, cut to this length.
const ERROR_LOG_MAX = 500;
const STOP_GRACE_MS = 5000;
// Who decides in this room: recorded as `actor` on every decision and named in the credit line on what an approved
// proposal creates. Nothing else uses it. "ownerName" in room.config.json sets it (one line, up to 60 characters);
// without one it is "the owner". It is a label, not a login.
const OWNER_NAME = (typeof CONFIG.ownerName === 'string' && CONFIG.ownerName.replace(/\s+/g, ' ').trim().slice(0, 60)) || 'the owner';
const AGENT = 'chief-operating-officer';
// What agents may use is set per room by the owner (Room settings → "What this room can use"), not in code:
// the folders they can read, web search, the exact sites they can open, Notion and Microsoft 365 mail (both read-only). Writing is
// always drafts/ only. The server turns a room's access into the run's --tools/--allowedTools (permissionsFor),
// and anything not allowed is refused, as headless runs don't ask. Peers inherit the session's rules.
// Every room starts with nothing beyond drafts/, the default room included; the owner adds what a room needs.
const minimalAccess = () => ({ files: [], webSearch: false, sites: [], notion: false, m365: false, mcp: {} });
const MAX_FOLDERS = 10;
const MAX_SITES = 30;
// Execs may write, but only drafts: file-writing tools are available, approved solely under drafts/.
const DRAFT_TOOLS = ['Write', 'Edit'];
const DRAFT_RULES = ['Write(drafts/**)', 'Edit(drafts/**)'];
// Every tool a run or an agent inside it may be given. None of them can run a command or read a program's
// environment, and that is what keeps the API key, and any other secret a run is started with, out of an agent's
// reach. It used to follow from how permissionsFor happens to be written; onlySafeTools makes it a rule: a run whose
// tool list holds anything else is not started.
const SAFE_TOOLS = new Set(['Read', 'Grep', 'Glob', 'WebSearch', 'WebFetch', 'Agent', 'ToolSearch', ...DRAFT_TOOLS]);
function onlySafeTools(tools, whose, more = null) {
const off = tools.filter((t) => !SAFE_TOOLS.has(t) && !(more && more.has(t)));
if (off.length) throw new Error(`The room refused to start ${whose}: its tool list holds ${off.join(', ')}, which no room agent may have.`);
return tools;
}
// Folders of the system itself, never a room folder and never readable by a run. On Linux /proc shows the
// environment of running programs (the run's own included, with the API key in key mode); macOS has no /proc, so
// there this only refuses /dev.
const SYSTEM_DIRS = ['/proc', '/sys', '/dev'];
// Notion is read-only for agents: a write to a database can set off whatever automation the owner has on it (publishing, for example).
const NOTION = 'mcp__claude_ai_Notion__';
const NOTION_READ = ['notion-search', 'notion-fetch', 'notion-query-data-sources'].map((t) => NOTION + t);
// Microsoft 365 mail (issue #46), per room: search Outlook mail through the owner's claude.ai connector, nothing else.
// Search returns metadata only (sender, subject, date, a preview). read_resource (full bodies) is left out on purpose:
// it opens any Microsoft Graph resource by URI, including the whole OneDrive (drive:///users/me), calendar and Teams. Off: the whole connector is blocked (as when it was in HIDDEN). On: only M365_READ is allowed, so any
// other tool of the connector is refused, as headless runs don't ask.
const M365_SERVER = 'mcp__claude_ai_Microsoft_365';
const M365 = M365_SERVER + '__';
const M365_READ = ['outlook_email_search'].map((t) => M365 + t);
// The only connector tools any agent may be given by name: reading Notion and searching mail.
const CONNECTOR_READ = new Set([...NOTION_READ, ...M365_READ]);
// Blocked by name when mail is on: every other tool of the connector, so none of them is even in the agents' view.
// The names are the connector's real ones, as a sandbox run listed them on 2026-09-28 (45 visible, plus the non-mail
// search tools that were already blocked). The real guard is still that only M365_READ is allowed: a tool the
// connector adds later is refused too, but shows up in the agents' context until it's added here.
const M365_BLOCKED = [
// account, people directory, and reading any Graph resource by URI (mail bodies, OneDrive, calendar, Teams)
'get_granted_scopes', 'get_me', 'search_people', 'read_resource',
// Outlook mail: everything except search (drafts, send, forward, reply, trash, labels, filters, vacation)
'outlook_create_draft', 'outlook_update_draft', 'outlook_delete_draft', 'outlook_send_draft', 'outlook_send_mail',
'outlook_forward_mail', 'outlook_create_reply_draft', 'outlook_create_reply_all_draft', 'outlook_trash_thread',
'outlook_untrash_thread', 'outlook_batch_delete_messages', 'outlook_modify_labels', 'outlook_modify_thread_labels',
'outlook_batch_modify_labels', 'outlook_create_label', 'outlook_update_label', 'outlook_delete_label',
'outlook_create_filter', 'outlook_delete_filter', 'outlook_set_vacation',
// Outlook calendar
'outlook_calendar_search', 'outlook_create_event', 'outlook_update_event', 'outlook_delete_event',
'outlook_respond_to_event', 'outlook_find_available_time', 'find_meeting_availability',
// SharePoint / OneDrive
'sharepoint_search', 'sharepoint_folder_search', 'sharepoint_copy_item', 'sharepoint_create_folder',
'sharepoint_delete_item', 'sharepoint_move_item', 'sharepoint_rename_item', 'sharepoint_update_file',
'sharepoint_upload_file',
// Teams
'chat_message_search', 'teams_create_chat', 'teams_list_channel_messages', 'teams_list_channels', 'teams_list_chats',
'teams_list_teams', 'teams_reply_channel_message', 'teams_send_channel_message', 'teams_send_chat_message',
].map((t) => M365 + t);
// Hidden from the agents to keep context small: claude.ai connectors the room has no use for. Safety doesn't rely
// on this list: user settings (with their allow-rules) aren't loaded, so anything not allowed above is denied.
// The built-in names are common connectors; owners add their own in room.config.json ("hiddenConnectors"), by the
// name in the connector's tool names (mcp__claude_ai_<name>__<tool>). An entry that isn't such a name is skipped
// with a warning, and so are Notion and Microsoft 365: the room's own switches need those connectors.
const CONNECTOR_NAME = /^[A-Za-z0-9_-]{1,64}$/;
const HIDDEN_CONNECTORS = ['Claude_Docs', 'Gmail', 'Slack', 'Google_Drive', 'Google_Calendar'];
const ROOM_CONNECTORS = ['Notion', 'Microsoft_365'];
const configuredHidden = (Array.isArray(CONFIG.hiddenConnectors) ? CONFIG.hiddenConnectors : []).filter((n) => {
const reason = typeof n !== 'string' || !CONNECTOR_NAME.test(n) ? 'not a connector name (letters, digits, _ and - only)'
: ROOM_CONNECTORS.some((r) => n === r || n.startsWith(`${r}__`)) ? 'the Notion and Microsoft 365 connectors are switched per room, not hidden here'
: null;
if (reason) console.warn(`room.config.json: skipped "hiddenConnectors" entry ${String(JSON.stringify(n)).slice(0, 80)}: ${reason}.`);
return !reason;
});
const HIDDEN = [
...[...new Set([...HIDDEN_CONNECTORS, ...configuredHidden])].map((n) => `mcp__claude_ai_${n}`),
...['ai-search', 'check-mcp-next-steps', 'convert-page-to-skill', 'create-attachment', 'create-comment',
'create-database', 'create-file-upload', 'create-folder', 'create-pages', 'create-view', 'download-attachment',
'download-skill', 'duplicate-page', 'get-async-task', 'get-comments', 'get-session-status', 'get-teams',
'get-tool-access', 'get-users', 'list-favorite-pages', 'list-private-pages', 'list-recent-pages',
'list-session-events', 'list-shared-pages', 'move-pages', 'query-meeting-notes', 'query-multiple-data-sources',
'query-sessions', 'read-session-event', 'search-agents', 'search-sessions', 'search-skills',
'send-message-to-session', 'show-advanced-analysis-next-steps', 'spawn-session', 'stop-session',
'update-data-source', 'update-folder', 'update-page', 'update-view', 'upload-skill', 'wait-session',
// Added by Notion since this list was written; seen in a run's tool list on 2026-10-13.
'get-enabled-skills', 'get-file-download-urls', 'get-self', 'memory-search', 'restore-pages', 'update-enabled-skills',
].map((t) => NOTION + 'notion-' + t),
];
// ---- The Exec Room's own MCP servers: servers set up once for the whole Exec Room, next to the
// claude.ai connectors, so agents keep them on an API key and can use services a Claude plan doesn't offer.
// Agents only read: each server has the tools agents may use (ticked in room.config.json), every other tool of it is
// blocked, and a server with a tool on that list known to write is not started at all (agents can't write
// themselves; writing goes through an approved proposal). Each room switches a server on or off (off by default),
// and the Exec Room settings page can pause one everywhere. For now only servers at a web address with a token in a
// header; a program on this Mac comes later, and only by hand in room.config.json, never from the page.
const MCP_CATALOG_FILE = process.env.ROOM_MCP_CATALOG || path.join(__dirname, 'mcp-catalog.json');
const MCP_ID = /^[a-z][a-z0-9-]{0,39}$/;
const MCP_TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
const MCP_ENV_NAME = /^[A-Z_][A-Z0-9_]{0,63}$/;
const MCP_MAX = 20;
const MCP_STATE_FILE = path.join(DATA_DIR, 'mcp-servers.json');
// A run's server list, with the tokens, is a file in data/ (which no run can read), never part of the command line:
// that shows in the process list. One per job, removed when the job ends.
const MCP_RUNS_DIR = path.join(DATA_DIR, 'mcp-runs');
const MCP_CHECK_TIMEOUT_MS = 20000;
// The marker a room-built agent's "mcp" tool group carries: it may use the tools of the servers its room has on.
const MCP_GROUP = 'mcp-servers';
function loadMcpCatalog() {
try {
return JSON.parse(fs.readFileSync(MCP_CATALOG_FILE, 'utf8'));
} catch (err) {
if (err.code !== 'ENOENT') console.warn(`The MCP catalog (${MCP_CATALOG_FILE}) couldn't be read: ${err.message}. Only servers added by hand can start.`);
return {};
}
}
const MCP_CATALOG = loadMcpCatalog();
// A server's address: https, or http on this computer only. No user, password or query in it: a token belongs in a
// header, as an address ends up in the vendor's logs.
function mcpAddress(value) {
let url;
try { url = new URL(String(value)); } catch { return null; }
const local = url.hostname === '127.0.0.1' || url.hostname === 'localhost';
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return null;
if (url.username || url.password || url.search || url.hash) return null;
return url.toString();
}
// One server from its entry, with the reason when it can't start. Entries come from "mcpServers" in room.config.json
// (source 'config', set up by hand) and from the Exec Room settings page (source 'page', saved in data/mcp-servers.json).
// Every entry is listed on the settings page, also the ones that are refused, so a mistake shows there. A page entry
// may sign in with "Connect" instead of naming a token ("via": "connect"), and a custom one may have no tools ticked
// yet: it then works but gives agents nothing until the owner ticks some.
function mcpServerFromEntry(id, e, source = 'config') {
const s = { id, name: String(id).slice(0, 40), by: '', description: '', origin: 'hand', source, via: 'token', url: null, tokenFrom: '', tools: [],
catalogId: null, catalogTools: null, claudeAi: null, check: null, note: '', explain: null, status: 'checking', problem: '', offered: null, readHint: [], token: null };
const refuse = (why) => { s.status = 'refused'; s.problem = why; return s; };
if (!MCP_ID.test(id)) return refuse('its name must start with a letter and hold only lowercase letters, digits and -');
if (!e || typeof e !== 'object' || Array.isArray(e)) return refuse('its entry must be an object');
if (source === 'page' && e.via === 'connect') s.via = 'connect';
let tools;
if (e.catalog != null) {
const cat = typeof e.catalog === 'string' && Object.hasOwn(MCP_CATALOG, e.catalog) ? MCP_CATALOG[e.catalog] : null;
if (!cat) return refuse(`"${String(e.catalog).slice(0, 40)}" isn't in the catalog`);
const where = s.via === 'connect' ? cat.connect : cat.token;
Object.assign(s, { origin: 'catalog', catalogId: e.catalog, name: cat.name, by: cat.by || '', description: cat.description || '', url: mcpAddress(where && where.url),
catalogTools: cat.tools || {}, claudeAi: cat.claudeAi || null, check: cat.check || null,
// What agents are told about the service besides its tools' names (Resend: email is written by anyone).
note: typeof cat.agentNote === 'string' ? cat.agentNote.trim().slice(0, 300) : '', explain: mcpExplain(cat.explain) });
if (!s.url) return refuse(`the catalog entry has no web address for ${s.via === 'connect' ? 'Connect' : 'a token'}`);
if (e.readOnlyTools != null) return refuse('a catalog entry lists its tools as "tools"; "readOnlyTools" is for servers added by hand');
// Set up on the page: every tool the catalog marks as reading, unless the owner ticked fewer.
tools = e.tools == null && source === 'page' ? Object.keys(s.catalogTools).filter((t) => s.catalogTools[t] === 'reads') : e.tools;
} else {
if (e.command != null || e.args != null) return refuse('a program on this computer isn\'t supported yet: only servers at a web address');
s.url = mcpAddress(e.url);
if (typeof e.name === 'string' && e.name.trim()) s.name = e.name.trim().slice(0, 40);
if (!s.url) return refuse('it needs a web address (https://…, or http:// on this computer) without a token or other details in it');
if (e.tools != null) return refuse('a server added by hand lists its tools as "readOnlyTools": you mark each one as only reading');
tools = e.readOnlyTools == null && source === 'page' ? [] : e.readOnlyTools;
}
const noneYet = source === 'page' && Array.isArray(tools) && !tools.length;
if (!Array.isArray(tools) || (!tools.length && !noneYet) || tools.some((t) => typeof t !== 'string' || !MCP_TOOL_NAME.test(t))) {
return refuse(`it needs the tools agents may use, as a list of tool names under "${s.origin === 'catalog' ? 'tools' : 'readOnlyTools'}"`);
}
s.tools = [...new Set(tools)];
if (s.catalogTools) {
const unknown = s.tools.find((t) => !Object.hasOwn(s.catalogTools, t));
if (unknown) return refuse(`"${unknown}" isn't one of ${s.name}'s tools in the catalog`);
const writes = s.tools.find((t) => s.catalogTools[t] !== 'reads');
if (writes) return refuse(`"${writes}" writes, and agents can't write themselves (writing goes through your approval): take it off the list`);
}
if (s.via === 'connect') s.tokenFrom = 'Connect';
else if (typeof e.tokenRef === 'string' && MCP_OP_REF.test(e.tokenRef)) s.tokenFrom = e.tokenRef;
else if (source === 'config' && typeof e.tokenEnv === 'string' && MCP_ENV_NAME.test(e.tokenEnv) && !AUTH_ENV.includes(e.tokenEnv)) s.tokenFrom = `$${e.tokenEnv}`;
else return refuse('it needs where its token lives: "tokenRef" (a 1Password op:// reference) or "tokenEnv" (the name of a variable that holds it)');
return s;
}
// What a catalog service does, in plain words, for the settings pages: what agents can do themselves, what the Exec
// Room does after you approve a card (left out when there's nothing to approve), what never happens, and one line for
// the switch in a room's Can use, and what the Exec Room itself uses after approval (where to, with which access). A
// server added by hand has none of these: its card says what was ticked, and that the Exec Room never writes through it.
function mcpExplain(x) {
if (!x || typeof x !== 'object' || Array.isArray(x)) return null;
const text = (v) => (typeof v === 'string' && v.trim() ? v.replace(/\s+/g, ' ').trim().slice(0, 300) : null);
const out = { agentsCan: text(x.agentsCan), approved: text(x.approved), never: text(x.never), roomLine: text(x.roomLine), roomUses: text(x.roomUses) };
return Object.values(out).some(Boolean) ? out : null;
}
// A 1Password reference: op://vault/item/field, nothing else (it is passed to `op read` as one argument).
const MCP_OP_REF = /^op:\/\/[^\s/]+(\/[^\s/]+){1,3}$/;
function mcpServersFromConfig() {
const raw = CONFIG.mcpServers;
const servers = {};
if (raw == null) return servers;
if (typeof raw !== 'object' || Array.isArray(raw)) {
console.warn('room.config.json: "mcpServers" must be an object with one entry per server; no MCP server is started.');
return servers;
}
for (const [id, e] of Object.entries(raw).slice(0, MCP_MAX)) servers[id] = mcpServerFromEntry(id, e, 'config');
return servers;
}
// Read once at start-up, like the Notion token: from 1Password or from a variable, which is then taken out of the
// server's own environment so nothing the server starts inherits it. Kept in memory only.
function readMcpToken(s) {
if (s.tokenFrom.startsWith('$')) {
const name = s.tokenFrom.slice(1);
const value = (process.env[name] || '').trim();
delete process.env[name];
return value;
}
try {
return execFileSync('op', ['read', s.tokenFrom], { encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch {
return '';
}
}
// The same, while the Exec Room runs (a server set up on the page): 1Password may wait for the owner's approval, and
// the room keeps answering meanwhile.
function readMcpTokenLater(ref) {
return new Promise((resolve) => {
execFile('op', ['read', ref], { encoding: 'utf8', timeout: 120000 }, (err, out) => resolve(err ? '' : String(out).trim()));
});
}
const MCP_SERVERS = mcpServersFromConfig();
// The servers set up on the settings page, and which servers are paused, live in data/mcp-servers.json. A file from
// before the page could add servers holds only "paused". An entry with the id of one in room.config.json is left out:
// the config, which is the owner's own, wins.
let mcpSaved = {};
const mcpPaused = new Set();
try {
const state = JSON.parse(fs.readFileSync(MCP_STATE_FILE, 'utf8'));
if (state && state.servers && typeof state.servers === 'object' && !Array.isArray(state.servers)) mcpSaved = state.servers;
for (const [id, e] of Object.entries(mcpSaved).slice(0, MCP_MAX)) {
if (Object.hasOwn(MCP_SERVERS, id)) { console.warn(`MCP server "${id}" set up on the settings page is left out: room.config.json has a server by that name.`); continue; }
MCP_SERVERS[id] = mcpServerFromEntry(id, e, 'page');
}
if (Array.isArray(state.paused)) for (const id of state.paused) if (typeof id === 'string' && Object.hasOwn(MCP_SERVERS, id)) mcpPaused.add(id);
} catch { /* no file yet: nothing set up on the page, nothing paused */ }
function saveMcpState() {
const tmp = `${MCP_STATE_FILE}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ paused: [...mcpPaused], servers: mcpSaved }, null, 1));
fs.renameSync(tmp, MCP_STATE_FILE);
}
// "Connect" sign-ins: what the service gave the Exec Room when the owner signed in, kept in data/mcp-signins.json
// (mode 600; no run can read data/). The renewal key changes at every renewal, so the file is rewritten each time.
const MCP_SIGNINS_FILE = path.join(DATA_DIR, 'mcp-signins.json');
let mcpSignins = {};
try { mcpSignins = JSON.parse(fs.readFileSync(MCP_SIGNINS_FILE, 'utf8')) || {}; } catch { /* none yet */ }
function saveMcpSignins() {
const tmp = `${MCP_SIGNINS_FILE}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(mcpSignins), { mode: 0o600 });
fs.renameSync(tmp, MCP_SIGNINS_FILE);
fs.chmodSync(MCP_SIGNINS_FILE, 0o600);
}
// Each source is read once (one 1Password prompt, and a variable is gone after its first read), also when two servers
// share it. A Connect server's token is the one from its sign-in, renewed before the check when it is about to run out.
const mcpTokens = new Map();
for (const s of Object.values(MCP_SERVERS)) {
if (s.status === 'refused') continue;
if (s.via === 'connect') {
const sign = mcpSignins[s.id];
s.token = sign && sign.accessToken || null;
if (!sign) { s.status = 'signin-expired'; s.problem = 'there is no sign-in for it any more'; }
continue;
}
if (!mcpTokens.has(s.tokenFrom)) mcpTokens.set(s.tokenFrom, readMcpToken(s));
s.token = mcpTokens.get(s.tokenFrom);
if (!s.token) { s.status = 'no-token'; s.problem = `no token found at ${s.tokenFrom}`; }
}
// A server agents can use now: checked and found working, with tools ticked, and not paused.
const mcpUsable = (s) => s.status === 'ready' && s.tools.length > 0 && !mcpPaused.has(s.id) && mcpTokenFresh(s);
const mcpToolName = (s, tool) => `mcp__${s.id}__${tool}`;
const ownMcpTool = (t) => Object.values(MCP_SERVERS).some((s) => t.startsWith(`mcp__${s.id}__`));
const mcpScrub = (s, text) => (s.token ? String(text).split(s.token).join('[token removed]') : String(text));
// One request to a server the way a run's Claude Code would make it (streamable HTTP, token in a header). Replies
// may be plain JSON or an event stream. A 401 or 403 means the token wasn't accepted.
async function mcpPost(s, session, body) {
const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${s.token}` };
if (session.id) headers['mcp-session-id'] = session.id;
const res = await fetch(s.url, { method: 'POST', headers, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(session.timeoutMs || MCP_CHECK_TIMEOUT_MS) });
session.id = res.headers.get('mcp-session-id') || session.id;
const text = await res.text();
if (res.status === 401 || res.status === 403) throw Object.assign(new Error(`the server answered ${res.status}`), { token: true });
if (body.id == null) return null;
if (!res.ok) throw new Error(`the server answered ${res.status}`);
const msg = (res.headers.get('content-type') || '').includes('text/event-stream')
? text.split('\n').filter((l) => l.startsWith('data:')).map((l) => { try { return JSON.parse(l.slice(5)); } catch { return null; } }).find((m) => m && m.id === body.id)
: JSON.parse(text);
if (!msg) throw new Error('the server sent no answer');
if (msg.error) throw new Error(`the server said: ${String(msg.error.message).slice(0, 160)}`);
return msg.result;
}
// At start-up: does the server answer, which tools does it offer, and is the token accepted? A server's tool list
// alone doesn't tell (some list their tools for any token), so a catalog entry names one harmless read call that
// does. What that call returns is not kept.
async function checkMcpServer(s) {
const session = { id: null };
let next = 1;
const request = (method, params) => mcpPost(s, session, { jsonrpc: '2.0', id: next++, method, params });
try {
await request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'exec-room', version: '1.0.0' } });
await mcpPost(s, session, { jsonrpc: '2.0', method: 'notifications/initialized' });
const offered = [];
const readHint = [];
let cursor;
for (let page = 0; page < 5; page++) {
const list = await request('tools/list', cursor ? { cursor } : {});
for (const t of Array.isArray(list && list.tools) ? list.tools : []) {
if (!t || typeof t.name !== 'string' || !MCP_TOOL_NAME.test(t.name)) continue;
offered.push(t.name);
// The server's own word that a tool only reads: shown next to it on the page, never trusted on its own.
if (t.annotations && t.annotations.readOnlyHint === true) readHint.push(t.name);
}
cursor = list && list.nextCursor;
if (!cursor) break;
}
s.offered = [...new Set(offered)].slice(0, 300);
s.readHint = [...new Set(readHint)].filter((t) => s.offered.includes(t));
const check = s.check && s.offered.includes(s.check.tool) ? s.check : null;
if (check) {
const result = await request('tools/call', { name: check.tool, arguments: check.arguments || {} });
if (result && result.isError) {
const said = (result.content || []).filter((c) => c && c.type === 'text').map((c) => c.text).join(' ');
throw Object.assign(new Error(`its test call was refused: ${said.slice(0, 160)}`), { token: true });
}
}
const missing = s.tools.filter((t) => !s.offered.includes(t));
s.status = 'ready';
s.problem = missing.length ? `the server doesn't offer ${missing.join(', ')}` : '';
} catch (err) {
s.status = err.token ? 'token-invalid' : 'unreachable';
s.problem = mcpScrub(s, err.name === 'TimeoutError' ? `no answer within ${MCP_CHECK_TIMEOUT_MS / 1000} seconds` : err.message);
}
}
// What the page and the terminal say about a server.
function mcpStatusText(s) {
if (s.status === 'ready') {
if (!mcpTokenFresh(s)) return 'Renewing the sign-in · trying every minute';
if (!s.tools.length) return 'Connected · choose its tools';
const ready = s.tools.filter((t) => s.offered.includes(t)).length;
return mcpPaused.has(s.id) ? 'Paused · off in every room' : `Connected · ${ready} ${ready === 1 ? 'tool' : 'tools'} ready`;
}
return { checking: 'Checking…', refused: 'Not started', 'no-token': 'No token', 'token-invalid': 'Token not accepted', unreachable: "Can't reach the server",
'signin-expired': 'Sign in again' }[s.status] || s.status;
}
// Runs started after this check get the servers that passed it. Said in the terminal, and on the settings page.
function checkMcpServers() {
const all = Object.values(MCP_SERVERS);
for (const s of all) if (['refused', 'no-token', 'signin-expired'].includes(s.status)) console.warn(`MCP server "${s.id}" not started: ${s.problem}.`);
return Promise.all(all.filter((s) => s.status === 'checking').map(async (s) => {
if (s.via === 'connect') await mcpRenew(s, MCP_RENEW_BEFORE_MS);
if (s.status === 'checking') await checkMcpServer(s);
const line = `MCP server "${s.id}" (${s.name}): ${mcpStatusText(s)}${s.problem ? ` (${s.problem})` : ''}.`;
if (s.status === 'ready') console.log(line); else console.warn(line);
}));
}
// The run's server list: only the servers this run gets, with their tokens. Returns the file, or null for none.
function writeMcpRunConfig(jobId, servers) {
if (!servers.length) return null;
fs.mkdirSync(MCP_RUNS_DIR, { recursive: true, mode: 0o700 });
const file = path.join(MCP_RUNS_DIR, `${jobId}.json`);
const config = { mcpServers: Object.fromEntries(servers.map((s) => [s.id, { type: 'http', url: s.url, headers: { Authorization: `Bearer ${s.token}` } }])) };
fs.writeFileSync(file, JSON.stringify(config), { mode: 0o600 });
return file;
}
// A run's file from before a restart holds tokens that may since have changed: cleared at every start.
try { for (const f of fs.readdirSync(MCP_RUNS_DIR)) fs.rmSync(path.join(MCP_RUNS_DIR, f), { force: true }); } catch { /* none yet */ }
// ---- "Connect": signing in with a service instead of making a token by hand (OAuth for MCP). The Exec Room finds
// where the server signs in (its 401 names the details), registers itself there, and gives the page a sign-in link
// with a one-time state and PKCE. The service sends the owner's browser back to this Mac with a code, which the server
// swaps for a token and a renewal key. Tokens run out (some after an hour), so a timer renews each one
// ten minutes before; a server whose renewal is refused says "Sign in again", and no run gets a token that ran out.
const MCP_REDIRECT = `http://127.0.0.1:${PORT}/api/mcp/callback`;
const MCP_RENEW_BEFORE_MS = 10 * 60 * 1000;
const MCP_RENEW_EVERY_MS = Number(process.env.ROOM_TEST_MCP_RENEW_MS) || 60 * 1000;
// After a token ran out, renewing goes on this long while it fails for a passing reason (no network after the
// computer wakes, too many requests): the renewal key usually outlives the token by far. A refusal ends it at once.
const MCP_RENEW_GRACE_MS = 24 * 60 * 60 * 1000;
const MCP_SIGNIN_WAIT_MS = 10 * 60 * 1000;
const mcpPending = new Map(); // one-time state → the sign-in it belongs to
const isLocalHost = (host) => host === '127.0.0.1' || host === 'localhost' || host === '[::1]';
// An address the sign-in steps may call or open. It comes from the server's answers, so it must be https, and not an
// address on this Mac or another bare IP address (a server could otherwise point the Exec Room at something local).
// A server on this Mac itself (a test server) may use http on this Mac.
function mcpAuthAddress(value, local) {
let url;
try { url = new URL(String(value)); } catch { return null; }
if (url.username || url.password || url.hash) return null;
if (local) return isLocalHost(url.hostname) && (url.protocol === 'http:' || url.protocol === 'https:') ? url.toString() : null;
if (url.protocol !== 'https:' || isLocalHost(url.hostname) || /^[\d.]+$/.test(url.hostname) || url.hostname.startsWith('[')) return null;
return url.toString();
}
// Whether a resource a server names is that server: the same origin, with a path the server's path starts with.
function mcpSameResource(resource, serverUrl) {
let r;
try { r = new URL(String(resource)); } catch { return false; }
const s = new URL(serverUrl);
const path = (p) => p.replace(/\/+$/, '');
return r.origin === s.origin && !r.search && !r.hash
&& (path(r.pathname) === '' || path(s.pathname) === path(r.pathname) || path(s.pathname).startsWith(`${path(r.pathname)}/`));
}
async function mcpJson(url, init = {}) {
const res = await fetch(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(MCP_CHECK_TIMEOUT_MS) });
const text = await res.text();
let body = null;
try { body = JSON.parse(text); } catch { /* not JSON */ }
return { res, body };
}
// Where and how a server signs in, and the Exec Room registered there. Throws a sentence for the page.
async function mcpDiscover(serverUrl) {
const local = isLocalHost(new URL(serverUrl).hostname);
const probe = await fetch(serverUrl, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(MCP_CHECK_TIMEOUT_MS),
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'exec-room', version: '1.0.0' } } }) });
await probe.text().catch(() => '');
if (probe.status !== 401) {
throw new Error(probe.ok ? 'the server answers without signing in, so there is nothing to connect: add it with a token from 1Password instead' : `the server answered ${probe.status}`);
}
const u = new URL(serverUrl);
const named = /resource_metadata="([^"]+)"/.exec(probe.headers.get('www-authenticate') || '');
const tail = u.pathname === '/' ? '' : u.pathname.replace(/\/$/, '');
let prm = null;
for (const c of [named && named[1], `${u.origin}/.well-known/oauth-protected-resource${tail}`, `${u.origin}/.well-known/oauth-protected-resource`]) {
const a = c && mcpAuthAddress(c, local);
if (!a) continue;
const { res, body } = await mcpJson(a).catch(() => ({}));
if (res && res.ok && body && Array.isArray(body.authorization_servers) && body.authorization_servers.length) { prm = body; break; }
}
if (!prm) throw new Error("the server doesn't say where to sign in, so Connect can't be used: add it with a token from 1Password instead");
// The sign-in is for the resource the server names, and the token then goes to this server. A server naming another
// service's address (to get a sign-in with Notion, say, and receive that token) is refused (RFC 9728, section 3.3).
if (prm.resource !== undefined && !mcpSameResource(prm.resource, serverUrl)) {
throw new Error("the server says its sign-in is for another address, so Connect can't be used with it");
}
const asBase = mcpAuthAddress(prm.authorization_servers[0], local);
if (!asBase) throw new Error('the server names a sign-in service at an address the Exec Room refuses (not https, or on this computer)');
const asu = new URL(asBase);
const p = asu.pathname.replace(/\/$/, '');
let as = null;
for (const c of [`${asu.origin}/.well-known/oauth-authorization-server${p}`, `${asu.origin}/.well-known/openid-configuration${p}`, ...(p ? [`${asu.origin}${p}/.well-known/openid-configuration`] : [])]) {
const { res, body } = await mcpJson(c).catch(() => ({}));
if (res && res.ok && body && body.authorization_endpoint && body.token_endpoint) { as = body; break; }
}
if (!as) throw new Error("its sign-in service doesn't describe itself, so Connect can't be used: add it with a token from 1Password instead");
const authorize = mcpAuthAddress(as.authorization_endpoint, local);
const tokenEndpoint = mcpAuthAddress(as.token_endpoint, local);
const register = as.registration_endpoint && mcpAuthAddress(as.registration_endpoint, local);
if (!authorize || !tokenEndpoint) throw new Error('its sign-in service names an address the Exec Room refuses (not https, or on this computer)');
if (!register) throw new Error("its sign-in service doesn't let the Exec Room register itself, so Connect can't be used yet: add it with a token from 1Password instead");
if (Array.isArray(as.code_challenge_methods_supported) && !as.code_challenge_methods_supported.includes('S256')) {
throw new Error("its sign-in service doesn't support the safe way of signing in (PKCE with S256)");
}
const { res, body } = await mcpJson(register, { method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ client_name: 'Exec Room', redirect_uris: [MCP_REDIRECT], grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'], token_endpoint_auth_method: 'none' }) });
if (!body || typeof body.client_id !== 'string') throw new Error(`its sign-in service refused to register the Exec Room (it answered ${res.status})`);
return { local, authorize, tokenEndpoint, clientId: body.client_id, resource: typeof prm.resource === 'string' ? prm.resource : serverUrl,
scopes: Array.isArray(prm.scopes_supported) ? prm.scopes_supported.filter((x) => typeof x === 'string') : [] };
}
// The sign-in link for a server to set up (or to sign in to again). Its entry is saved only once the sign-in worked.
async function mcpStartConnect(id, entry, serverUrl, scope) {
const d = await mcpDiscover(serverUrl);
const b64url = (buf) => buf.toString('base64url');
const verifier = b64url(crypto.randomBytes(32));
const state = b64url(crypto.randomBytes(24));
for (const [st, p] of mcpPending) if (p.id === id || p.expires < Date.now()) mcpPending.delete(st); // one sign-in per server at a time
mcpPending.set(state, { id, entry, verifier, expires: Date.now() + MCP_SIGNIN_WAIT_MS, ...d });
const url = new URL(d.authorize);
const params = { response_type: 'code', client_id: d.clientId, redirect_uri: MCP_REDIRECT, state, resource: d.resource,
code_challenge: b64url(crypto.createHash('sha256').update(verifier).digest()), code_challenge_method: 'S256' };
const scopes = scope || d.scopes.join(' ');
if (scopes) params.scope = scopes;
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
return url.toString();
}
async function mcpTokenRequest(sign, params) {
const { res, body } = await mcpJson(sign.tokenEndpoint, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
body: new URLSearchParams({ client_id: sign.clientId, resource: sign.resource, ...params }) });
if (body && typeof body.access_token === 'string' && body.access_token) return body;
// A 4xx is a refusal (the sign-in is gone), except "too many requests" and a timeout: those pass, so renewing tries again.
const refused = res.status >= 400 && res.status < 500 && res.status !== 429 && res.status !== 408;
throw Object.assign(new Error(`its sign-in service answered ${res.status}${body && body.error ? ` (${String(body.error).slice(0, 60)})` : ''}`), { refused });
}
function mcpKeepSignin(id, sign, t, previous) {
mcpSignins[id] = { clientId: sign.clientId, tokenEndpoint: sign.tokenEndpoint, resource: sign.resource, local: Boolean(sign.local),
accessToken: t.access_token, refreshToken: t.refresh_token || (previous && previous.refreshToken) || null,
expiresAt: Date.now() + (Number(t.expires_in) > 0 ? Number(t.expires_in) : 3600) * 1000 };
saveMcpSignins();
return mcpSignins[id];
}
// The browser's return from the service. Refused unless it carries a state this Exec Room handed out in the last ten
// minutes, and each state works once. Returns what the return page says.
async function mcpFinishConnect(state, code, error) {
for (const [st, p] of mcpPending) if (p.expires < Date.now()) mcpPending.delete(st);
const p = typeof state === 'string' ? mcpPending.get(state) : null;
if (!p) return { ok: false, refused: true, message: "This sign-in wasn't started by the Exec Room, or it took longer than 10 minutes. Nothing was changed." };
mcpPending.delete(state);
const name = p.entry.catalog ? MCP_CATALOG[p.entry.catalog].name : p.entry.name;
if (error || typeof code !== 'string' || !code) return { ok: false, message: `The sign-in with ${name} was not completed${error ? ` (${String(error).slice(0, 60)})` : ''}. Nothing was changed.` };
let t;
try {
t = await mcpTokenRequest(p, { grant_type: 'authorization_code', code, redirect_uri: MCP_REDIRECT, code_verifier: p.verifier });
} catch (err) {
return { ok: false, message: `${name} didn't accept the sign-in: ${err.message}. Nothing was changed.` };
}
const sign = mcpKeepSignin(p.id, p, t, null);
mcpSaved[p.id] = p.entry;
saveMcpState();
const s = mcpServerFromEntry(p.id, p.entry, 'page');
s.token = sign.accessToken;
MCP_SERVERS[p.id] = s;
if (s.status === 'checking') await checkMcpServer(s);
console.log(`MCP server "${s.id}" (${s.name}) signed in on the settings page: ${mcpStatusText(s)}${s.problem ? ` (${s.problem})` : ''}.`);
fs.appendFileSync(JOBS_FILE, JSON.stringify({ kind: 'mcp', change: 'signed in', server: s.id, at: new Date().toISOString() }) + '\n');
return { ok: true, message: `Signed in with ${s.name}: ${mcpStatusText(s)}. You can close this tab and go back to the Exec Room.` };
}
// Each renewal goes into the job log with its time (never a token or key), so that when a service stops accepting a
// sign-in it shows when, next to what else happened then. A failure that isn't a refusal (no network after the Mac
// wakes, say) is tried again every minute and logged once per run of failures.
function mcpRenewLog(s, change, extra = {}) {
try {
fs.appendFileSync(JOBS_FILE, JSON.stringify({ kind: 'mcp', change, server: s.id, ...extra, at: new Date().toISOString() }) + '\n');
} catch { /* the renewal itself stands; only its line is missing */ }
}
// Renews a Connect server's token when it runs out within `before`. Only one renewal per server at a time: the renewal
// key works once.
function mcpRenew(s, before) {
if (s.renewing) return s.renewing;
const sign = mcpSignins[s.id];
if (!sign) { s.status = 'signin-expired'; s.problem = 'there is no sign-in for it any more'; return Promise.resolve(); }
if (sign.expiresAt - Date.now() > before) return Promise.resolve();
// At start-up the check says how it went; later, the renewal says it itself.
const quiet = s.status === 'checking';
s.renewing = (async () => {
try {
if (!sign.refreshToken) throw Object.assign(new Error('the service gave no way to renew the sign-in'), { refused: true });
const t = await mcpTokenRequest(sign, { grant_type: 'refresh_token', refresh_token: sign.refreshToken });
const kept = mcpKeepSignin(s.id, sign, t, sign);
s.token = kept.accessToken;
s.renewFailing = false;
mcpRenewLog(s, 'renewed', { until: new Date(kept.expiresAt).toISOString() });
} catch (err) {
const reason = mcpScrub(s, err.message);
if (err.refused || Date.now() - sign.expiresAt > MCP_RENEW_GRACE_MS) {
s.status = 'signin-expired';
s.since = new Date().toISOString();
s.problem = `the sign-in ran out and couldn't be renewed: ${reason}`;
mcpRenewLog(s, 'renewal refused', { reason: reason.slice(0, 200) });
if (!quiet) console.warn(`${s.since} MCP server "${s.id}" (${s.name}): Sign in again (${s.problem}).`);
} else if (!s.renewFailing) {
s.renewFailing = true;
mcpRenewLog(s, 'renewal failed, trying again every minute', { reason: reason.slice(0, 200) });
}
} finally {
s.renewing = null;
}
})();
return s.renewing;
}
setInterval(() => {
for (const s of Object.values(MCP_SERVERS)) if (s.via === 'connect' && s.status === 'ready') mcpRenew(s, MCP_RENEW_BEFORE_MS);
}, MCP_RENEW_EVERY_MS).unref();
// A Connect server whose token has run out (its renewal failed or hasn't come yet) is given to no run.
const mcpTokenFresh = (s) => s.via !== 'connect' || (mcpSignins[s.id] && mcpSignins[s.id].expiresAt > Date.now());
// One tool call by the Exec Room's own server (saving an approved proposal), never by an agent. Returns the text the
// tool answered; a tool's refusal becomes an error in its own words.
async function mcpCallTool(s, name, args, timeoutMs = 60000) {
if (s.via === 'connect') await mcpRenew(s, MCP_RENEW_BEFORE_MS);
const session = { id: null, timeoutMs };
let next = 1;
const request = (method, params) => mcpPost(s, session, { jsonrpc: '2.0', id: next++, method, params });
try {
await request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'exec-room', version: '1.0.0' } });
await mcpPost(s, session, { jsonrpc: '2.0', method: 'notifications/initialized' });
const result = await request('tools/call', { name, arguments: args });
const text = (result && Array.isArray(result.content) ? result.content : []).filter((c) => c && c.type === 'text').map((c) => c.text).join('\n');
if (result && result.isError) throw new Error(`${s.name} said: ${text.slice(0, 300) || 'the call failed'}`);
return text;
} catch (err) {
throw new Error(mcpScrub(s, err.name === 'TimeoutError' ? `${s.name} gave no answer within ${timeoutMs / 1000} seconds` : err.message));
}
}
// ---- Sending a draft from a Resend inbox: the one thing the Exec Room sends itself. Agents only read the
// inboxes; a draft goes out only through an approved send_draft card, sent by the Exec Room's own Resend sign-in.
// Coen names the draft, never its text: the server reads the draft from Resend's REST API (the Connect sign-in works
// there too, checked live on 2026-11-21) when the card is made, the card shows what Resend has, and at approval the
// server reads it again and sends only when nothing changed. Sending uses the card's id as Resend's idempotency key,
// so one card sends one email at most. Approving is possible on the page only: Slack shows the card without Approve.
const RESEND_API = process.env.ROOM_RESEND_API || 'https://api.resend.com';
const RESEND_ID = /^[A-Za-z0-9._@+-]{1,200}$/;
const RESEND_TEXT_MAX = 20000;
const RESEND_CATALOG = 'resend';
// The cards that read Resend before they are shown: sending a draft, and writing one.
const RESEND_ACTIONS = ['send_draft', 'write_draft'];
const resendFor = (space) => (space ? roomMcp(accessOf(space)).find((s) => s.catalogId === RESEND_CATALOG) || null : null);
const resendPath = (...parts) => parts.map((p) => `/${encodeURIComponent(p)}`).join('');
async function resendRequest(s, method, p, { idempotencyKey, json = {} } = {}) {
if (s.via === 'connect') await mcpRenew(s, MCP_RENEW_BEFORE_MS);
const headers = { authorization: `Bearer ${s.token}`, accept: 'application/json' };
if (method === 'POST') headers['content-type'] = 'application/json';
if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
let res;
try {
res = await fetch(`${RESEND_API}${p}`, { method, headers, ...(method === 'POST' && { body: JSON.stringify(json) }), redirect: 'error', signal: AbortSignal.timeout(30000) });
} catch (err) {
throw new Error(mcpScrub(s, err.name === 'TimeoutError' ? 'Resend gave no answer within 30 seconds' : `Resend couldn't be reached (${err.message})`));
}
const text = await res.text();
let body = null;
try { body = JSON.parse(text); } catch { /* not JSON: said below by status */ }
if (!res.ok) throw new Error(mcpScrub(s, `Resend answered ${res.status}${body && body.message ? ` (${String(body.message).slice(0, 200)})` : ''}`));
return body;
}
// "Ada <ada@example.org>" and "ada@example.org" alike become ada@example.org.
const bareAddress = (a) => { const m = /<([^<>\s]+@[^<>\s]+)>\s*$/.exec(a); return (m ? m[1] : a).trim().toLowerCase(); };
const addressList = (v) => (Array.isArray(v) ? v : typeof v === 'string' && v ? [v] : []).filter((a) => typeof a === 'string').map(bareAddress);
// What a mail app shows of an HTML-only draft, near enough to read before approving.
function htmlText(html) {
return String(html).replace(/<(script|style)[\s\S]*?<\/\1>/gi, '').replace(/<br\s*\/?>/gi, '\n').replace(/<\/(p|div|li|h[1-6]|tr)>/gi, '\n')
.replace(/<[^>]+>/g, '').replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&')
.replace(/\n{3,}/g, '\n\n').trim();
}
// The draft as Resend has it now: what the card shows, and a fingerprint of everything that would be sent.
async function readDraft(s, inbox, draft) {
const d = await resendRequest(s, 'GET', `/inboxes${resendPath(inbox)}/drafts${resendPath(draft)}`);
if (!d || d.object !== 'inbox_draft') throw new Error("Resend didn't return a draft for that id");
if (d.email_id) throw new Error('that draft has already been sent');
if (Array.isArray(d.attachments) && d.attachments.length) throw new Error("the draft has attachments, which the Exec Room can't show you: send it from Resend instead");
const html = typeof d.html === 'string' && d.html.trim() ? d.html : null;
const plain = typeof d.text === 'string' && d.text.trim() ? d.text : null;
// Mail apps show the HTML version when there is one, so that is what the card shows.
const shown = html ? htmlText(html) : plain || '';
if (!shown.trim()) throw new Error('the draft has no text');
if (shown.length > RESEND_TEXT_MAX) throw new Error(`the draft is longer than ${RESEND_TEXT_MAX} characters, more than a card shows: send it from Resend instead`);
const snap = {
kind: d.thread_id ? 'reply' : 'standalone', threadId: d.thread_id || null,
to: addressList(d.to), cc: addressList(d.cc), bcc: addressList(d.bcc),
subject: typeof d.subject === 'string' ? d.subject.replace(/\s+/g, ' ').trim() : '', text: shown, html: Boolean(html),
};
snap.fingerprint = crypto.createHash('sha256').update(JSON.stringify([snap.to, snap.cc, snap.bcc, snap.subject, html, plain, d.thread_id, d.reply_to_email_id])).digest('hex');
return snap;
}
// Who a draft may go to: a reply only to people already in its thread, a new email only to the room's recipient
// list. Returns the subject a reply goes out with when its own is empty (the thread's, with "Re:").
async function checkDraftRecipients(s, inbox, snap, allowed, replyTo = null) {
const all = [...snap.to, ...snap.cc, ...snap.bcc];
if (!all.length) throw new Error('the draft has no recipients');
if (snap.kind === 'standalone') {
const off = all.filter((a) => !recipientAllowed(a, allowed));
if (off.length) throw new Error(`${off.join(', ')} ${off.length > 1 ? "aren't" : "isn't"} on this room's recipient list, and a new email may only go there`);
return snap.subject;
}
const emails = [];
let after = null;
for (let page = 0; page < 5; page++) {
const r = await resendRequest(s, 'GET', `/inboxes${resendPath(inbox)}/threads${resendPath(snap.threadId)}/emails?limit=100${after ? `&after=${encodeURIComponent(after)}` : ''}`);
const data = Array.isArray(r && r.data) ? r.data : [];
emails.push(...data);
if (!(r && r.has_more) || !data.length) break;
after = data[data.length - 1].id;
}
if (replyTo && !emails.some((e) => e.id === replyTo)) throw new Error("the email it answers isn't in that thread");
const people = new Set(emails.flatMap((e) => [...addressList(e.from), ...addressList(e.to), ...addressList(e.cc)]));
const off = all.filter((a) => !people.has(a));
if (off.length) throw new Error(`${off.join(', ')} ${off.length > 1 ? "aren't" : "isn't"} in that thread, and a reply may only go to people already in it`);
if (snap.subject) return snap.subject;
const first = emails.find((e) => typeof e.subject === 'string' && e.subject.trim());
const base = first ? first.subject.replace(/\s+/g, ' ').trim() : '';
return /^re:/i.test(base) ? base : base ? `Re: ${base}` : '(the thread\'s subject)';
}
// A send_draft card's content, read when the card is made. Throws a sentence for the chat.
async function prepareSendDraft(rec, space) {
const s = resendFor(space);
if (!s) throw new Error("Resend isn't on and connected in this room");
const inbox = await resendRequest(s, 'GET', `/inboxes${resendPath(rec.inbox)}`);
if (!inbox || typeof inbox.id !== 'string') throw new Error(`Resend has no inbox "${rec.inbox}"`);
const snap = await readDraft(s, inbox.id, rec.draft);
const subject = await checkDraftRecipients(s, inbox.id, snap, targetsOf(space).allowedRecipients);
return { ...rec, inbox: inbox.id, from: [inbox.from_name, inbox.email_address].filter((x) => typeof x === 'string' && x).join(' · '),
kind: snap.kind, to: snap.to, cc: snap.cc, bcc: snap.bcc, subject, text: snap.text, html: snap.html, fingerprint: snap.fingerprint };
}
// ---- Writing a draft into a Resend inbox (write_draft): Coen writes a reply or a new email, and approving only
// saves it as a draft in that inbox. Nothing is sent: sending is a send_draft card of its own. The same recipient
// rule applies as for sending, checked when the card is made and again at approval.
const writtenDraft = (rec) => ({ kind: rec.threadId ? 'reply' : 'standalone', threadId: rec.threadId || null, to: rec.to, cc: rec.cc || [], bcc: [], subject: rec.subject || '' });
// A write_draft card's sender and, for a reply, the thread's subject. Throws a sentence for the chat.
async function prepareWriteDraft(rec, space) {
const s = resendFor(space);
if (!s) throw new Error("Resend isn't on and connected in this room");
const inbox = await resendRequest(s, 'GET', `/inboxes${resendPath(rec.inbox)}`);
if (!inbox || typeof inbox.id !== 'string') throw new Error(`Resend has no inbox "${rec.inbox}"`);
const shownSubject = await checkDraftRecipients(s, inbox.id, writtenDraft({ ...rec }), targetsOf(space).allowedRecipients, rec.replyTo);
return { ...rec, inbox: inbox.id, from: [inbox.from_name, inbox.email_address].filter((x) => typeof x === 'string' && x).join(' · '),
kind: rec.threadId ? 'reply' : 'standalone', shownSubject };
}
// Saves an approved write_draft card as a draft. Resend keeps one unsent reply draft per email: asking for a second
// returns the one that is there, unchanged. So the draft is read back, and anything but Coen's text is a failure.
async function createDraft(rec, space) {
const s = resendFor(space);
if (!s) throw new Error("Resend is no longer on and connected in this room, so nothing was saved");
await checkDraftRecipients(s, rec.inbox, writtenDraft(rec), targetsOf(space).allowedRecipients, rec.replyTo);
const made = await resendRequest(s, 'POST', `/inboxes${resendPath(rec.inbox)}/drafts`, { idempotencyKey: rec.recId, json: {
to: rec.to, ...(rec.cc.length && { cc: rec.cc }), ...(rec.subject && { subject: rec.subject }), text: rec.body,
...(rec.threadId && { thread_id: rec.threadId, reply_to_email_id: rec.replyTo }),
} });
if (!made || typeof made.id !== 'string') throw new Error("Resend didn't say which draft it saved");
const d = await resendRequest(s, 'GET', `/inboxes${resendPath(rec.inbox)}/drafts${resendPath(made.id)}`);
const same = d && d.text === rec.body && JSON.stringify(addressList(d.to)) === JSON.stringify(rec.to) && (d.subject || '') === (rec.subject || '');
if (!same) throw new Error('that email already has an unsent reply draft in the inbox (the inbox agent\'s, most likely), and Resend keeps one per email: it was left as it is, and nothing was saved. Send or delete that draft in Resend first, or ask Coen to propose sending it');
return made.id;
}
// ---- Notion through "Connect". Notion's hosted server is a catalog service like the others,
// but no room switches it on by itself: it follows each room's "Notion (read-only)" switch. Once Notion is connected,
// agents read it through this connection on the plan and on a key alike, and on the plan the claude.ai Notion
// connector (the same server with the same tools) is blocked, so there is one way in, under the Exec Room's rules.
// Not connected: the claude.ai connector on the plan, links on a key. The Exec Room's own server saves approved
// proposals through it; a Notion token made by hand (notionTokenRef) is used only while the sign-in doesn't work.
const NOTION_CATALOG = 'notion';
const notionConn = () => Object.values(MCP_SERVERS).find((s) => s.catalogId === NOTION_CATALOG && s.via === 'connect') || null;
// Agents read through it when it works, has its tools ticked and isn't paused. Connected but not usable (paused, or
// "Sign in again"), agents read no Notion at all: pausing it stops reading on the plan too.
const notionReader = () => { const s = notionConn(); return s && mcpUsable(s) ? s : null; };
// Saving goes through it whenever the sign-in works. Pausing it stops the agents' reading, not saving what the owner approves.
const notionWriter = () => { const s = notionConn(); return s && s.status === 'ready' && mcpTokenFresh(s) ? s : null; };
const notionSaving = () => Boolean(notionWriter() || NOTION_TOKEN);
// The lists above name tools, and a connector gains tools without telling anyone. A tool the room doesn't know can't
// be called (only the read tools a room allows can; a run has nobody to ask), but agents see it and try it. So the
// room learns: every run reports the tools it was given when it starts, and a Notion or Microsoft 365 tool that is
// neither allowed nor blocked yet is written to data/connector-tools.json and blocked from the next run on.
const NOTION_SERVER = 'mcp__claude_ai_Notion';
const CONNECTOR_TOOL = /^mcp__claude_ai_(Notion|Microsoft_365)__[A-Za-z0-9_-]{1,80}$/;
const CONNECTOR_TOOLS_FILE = path.join(DATA_DIR, 'connector-tools.json');