@mosadd/mcp 3.0.0-alpha.55 → 3.0.0-alpha.56

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +5 -11
  2. package/LICENSE +21 -0
  3. package/README.md +151 -150
  4. package/dist/bin/mcp.js +1 -1
  5. package/dist/{chunk-IWUGKLDX.js → chunk-T3KDVUAT.js} +14 -10
  6. package/dist/index.js +1 -1
  7. package/package.json +10 -10
  8. package/src/__tests__/blob-upload.test.ts +93 -93
  9. package/src/__tests__/channel-e2ee.test.ts +62 -62
  10. package/src/__tests__/flota-jawnie.test.ts +2 -2
  11. package/src/__tests__/golden-path.test.ts +139 -139
  12. package/src/__tests__/integration.test.ts +209 -182
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  14. package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
  15. package/src/__tests__/mirc-invite.test.ts +112 -112
  16. package/src/__tests__/mtalk.test.ts +122 -122
  17. package/src/__tests__/presence.test.ts +199 -199
  18. package/src/__tests__/server.test.ts +71 -71
  19. package/src/__tests__/tool-count-consistency.test.ts +255 -199
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -145
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -288
  24. package/src/crypto/mdm-session.ts +842 -842
  25. package/src/index.ts +19 -19
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +162 -162
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +202 -202
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/server.ts +195 -195
  32. package/src/tools/actions.ts +166 -166
  33. package/src/tools/attachments.ts +276 -276
  34. package/src/tools/capabilities.ts +70 -70
  35. package/src/tools/channel-payload.ts +2 -2
  36. package/src/tools/embed.ts +110 -110
  37. package/src/tools/index.ts +181 -181
  38. package/src/tools/knowledge.ts +344 -344
  39. package/src/tools/mail-aliases.ts +25 -25
  40. package/src/tools/mail-provenance.ts +137 -137
  41. package/src/tools/mail.ts +403 -403
  42. package/src/tools/mdm-as-agent.ts +138 -126
  43. package/src/tools/mdm.ts +3 -3
  44. package/src/tools/mirc-edge.ts +196 -196
  45. package/src/tools/mirc-members.ts +287 -287
  46. package/src/tools/mirc-messages.ts +1 -1
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom.ts +221 -221
  49. package/src/tools/mtalk.ts +131 -131
  50. package/src/tools/presence.ts +442 -442
  51. package/src/tools/voice-format.ts +28 -28
  52. package/src/types.ts +121 -121
  53. package/src/voice/floor.ts +132 -132
package/src/bin/login.ts CHANGED
@@ -1,138 +1,138 @@
1
- /**
2
- * `mosadd login` / `logout` / `whoami` — session helper.
3
- *
4
- * Removes the "copy a JWT from mosadd.com DevTools" hack: signs in with
5
- * Supabase email+password (BYOK project URL + anon key) and stores the session
6
- * at ~/.mosadd/session.json, which the MCP server reads automatically.
7
- *
8
- * Credentials resolution (first found wins): CLI flags → env → interactive
9
- * prompt. URL/anon also fall back to a previously saved session.
10
- */
11
-
12
- import { createInterface } from "node:readline";
13
- import { createClient } from "@supabase/supabase-js";
14
- import { loadSession, saveSession, clearSession, sessionPath, isSessionExpired } from "../config.js";
15
-
16
- function parseFlags(args: string[]): Record<string, string> {
17
- const out: Record<string, string> = {};
18
- for (let i = 0; i < args.length; i += 1) {
19
- const a = args[i];
20
- if (a.startsWith("--")) {
21
- const key = a.slice(2);
22
- const val = args[i + 1] && !args[i + 1].startsWith("--") ? args[(i += 1)] : "true";
23
- out[key] = val;
24
- }
25
- }
26
- return out;
27
- }
28
-
29
- function prompt(question: string, hidden = false): Promise<string> {
30
- return new Promise((resolve) => {
31
- const rl = createInterface({ input: process.stdin, output: process.stdout });
32
- if (hidden) {
33
- // Mute echoed characters for password entry.
34
- const ro = rl as unknown as { _writeToOutput: (s: string) => void; output?: NodeJS.WriteStream };
35
- let first = true;
36
- ro._writeToOutput = (s: string) => {
37
- if (first) {
38
- process.stdout.write(question);
39
- first = false;
40
- } else if (s.includes("\n")) {
41
- process.stdout.write("\n");
42
- }
43
- };
44
- }
45
- rl.question(hidden ? "" : question, (answer) => {
46
- rl.close();
47
- resolve(answer.trim());
48
- });
49
- });
50
- }
51
-
52
- async function login(args: string[]): Promise<void> {
53
- const flags = parseFlags(args);
54
- const prev = loadSession();
55
-
56
- // Canonical env is MOSADD_*; legacy M0SSAD_* names stay honored (deprecated).
57
- const url =
58
- flags.url ||
59
- process.env.MOSADD_SUPABASE_URL ||
60
- process.env.M0SSAD_SUPABASE_URL ||
61
- prev?.url ||
62
- (await prompt("Supabase URL: "));
63
- const anonKey =
64
- flags.anon ||
65
- process.env.MOSADD_SUPABASE_ANON_KEY ||
66
- process.env.M0SSAD_SUPABASE_ANON_KEY ||
67
- prev?.anonKey ||
68
- (await prompt("Supabase anon key: "));
69
- const email =
70
- flags.email || process.env.MOSADD_EMAIL || process.env.M0SSAD_EMAIL || (await prompt("Email: "));
71
- const password =
72
- flags.password ||
73
- process.env.MOSADD_PASSWORD ||
74
- process.env.M0SSAD_PASSWORD ||
75
- (await prompt("Password: ", true));
76
-
77
- if (!url || !anonKey || !email || !password) {
78
- console.error("\nmosadd login: need Supabase URL, anon key, email and password.");
79
- process.exit(1);
80
- }
81
-
82
- const client = createClient(url, anonKey, {
83
- auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
84
- });
85
- const { data, error } = await client.auth.signInWithPassword({ email, password });
86
- if (error || !data.session) {
87
- console.error(`\nmosadd login failed: ${error?.message ?? "no session returned"}`);
88
- process.exit(1);
89
- }
90
-
91
- saveSession({
92
- url,
93
- anonKey,
94
- accessToken: data.session.access_token,
95
- refreshToken: data.session.refresh_token,
96
- expiresAt: data.session.expires_at,
97
- email: data.user?.email ?? email,
98
- });
99
-
100
- const when = data.session.expires_at
101
- ? new Date(data.session.expires_at * 1000).toISOString()
102
- : "unknown";
103
- console.log(`\n✓ Signed in as ${data.user?.email ?? email}`);
104
- console.log(` Session saved to ${sessionPath()} (token expires ${when}).`);
105
- console.log(` The mosadd MCP server will now use it automatically — no env vars needed.`);
106
- }
107
-
108
- function whoami(): void {
109
- const s = loadSession();
110
- if (!s) {
111
- console.log("Not logged in. Run `mosadd login`.");
112
- process.exit(1);
113
- }
114
- const expired = isSessionExpired(s);
115
- console.log(`Logged in as ${s.email ?? "(unknown)"} @ ${s.url}`);
116
- console.log(`Token: ${expired ? "EXPIRED — run `mosadd login` again" : "valid"}`);
117
- }
118
-
119
- function logout(): void {
120
- console.log(clearSession() ? "✓ Logged out (session cleared)." : "No session to clear.");
121
- }
122
-
123
- export async function runAuthCommand(cmd: string, args: string[]): Promise<void> {
124
- switch (cmd) {
125
- case "login":
126
- await login(args);
127
- break;
128
- case "whoami":
129
- whoami();
130
- break;
131
- case "logout":
132
- logout();
133
- break;
134
- default:
135
- console.error(`Unknown command: ${cmd}`);
136
- process.exit(1);
137
- }
138
- }
1
+ /**
2
+ * `mosadd login` / `logout` / `whoami` — session helper.
3
+ *
4
+ * Removes the "copy a JWT from mosadd.com DevTools" hack: signs in with
5
+ * Supabase email+password (BYOK project URL + anon key) and stores the session
6
+ * at ~/.mosadd/session.json, which the MCP server reads automatically.
7
+ *
8
+ * Credentials resolution (first found wins): CLI flags → env → interactive
9
+ * prompt. URL/anon also fall back to a previously saved session.
10
+ */
11
+
12
+ import { createInterface } from "node:readline";
13
+ import { createClient } from "@supabase/supabase-js";
14
+ import { loadSession, saveSession, clearSession, sessionPath, isSessionExpired } from "../config.js";
15
+
16
+ function parseFlags(args: string[]): Record<string, string> {
17
+ const out: Record<string, string> = {};
18
+ for (let i = 0; i < args.length; i += 1) {
19
+ const a = args[i];
20
+ if (a.startsWith("--")) {
21
+ const key = a.slice(2);
22
+ const val = args[i + 1] && !args[i + 1].startsWith("--") ? args[(i += 1)] : "true";
23
+ out[key] = val;
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+
29
+ function prompt(question: string, hidden = false): Promise<string> {
30
+ return new Promise((resolve) => {
31
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
32
+ if (hidden) {
33
+ // Mute echoed characters for password entry.
34
+ const ro = rl as unknown as { _writeToOutput: (s: string) => void; output?: NodeJS.WriteStream };
35
+ let first = true;
36
+ ro._writeToOutput = (s: string) => {
37
+ if (first) {
38
+ process.stdout.write(question);
39
+ first = false;
40
+ } else if (s.includes("\n")) {
41
+ process.stdout.write("\n");
42
+ }
43
+ };
44
+ }
45
+ rl.question(hidden ? "" : question, (answer) => {
46
+ rl.close();
47
+ resolve(answer.trim());
48
+ });
49
+ });
50
+ }
51
+
52
+ async function login(args: string[]): Promise<void> {
53
+ const flags = parseFlags(args);
54
+ const prev = loadSession();
55
+
56
+ // Canonical env is MOSADD_*; legacy M0SSAD_* names stay honored (deprecated).
57
+ const url =
58
+ flags.url ||
59
+ process.env.MOSADD_SUPABASE_URL ||
60
+ process.env.M0SSAD_SUPABASE_URL ||
61
+ prev?.url ||
62
+ (await prompt("Supabase URL: "));
63
+ const anonKey =
64
+ flags.anon ||
65
+ process.env.MOSADD_SUPABASE_ANON_KEY ||
66
+ process.env.M0SSAD_SUPABASE_ANON_KEY ||
67
+ prev?.anonKey ||
68
+ (await prompt("Supabase anon key: "));
69
+ const email =
70
+ flags.email || process.env.MOSADD_EMAIL || process.env.M0SSAD_EMAIL || (await prompt("Email: "));
71
+ const password =
72
+ flags.password ||
73
+ process.env.MOSADD_PASSWORD ||
74
+ process.env.M0SSAD_PASSWORD ||
75
+ (await prompt("Password: ", true));
76
+
77
+ if (!url || !anonKey || !email || !password) {
78
+ console.error("\nmosadd login: need Supabase URL, anon key, email and password.");
79
+ process.exit(1);
80
+ }
81
+
82
+ const client = createClient(url, anonKey, {
83
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
84
+ });
85
+ const { data, error } = await client.auth.signInWithPassword({ email, password });
86
+ if (error || !data.session) {
87
+ console.error(`\nmosadd login failed: ${error?.message ?? "no session returned"}`);
88
+ process.exit(1);
89
+ }
90
+
91
+ saveSession({
92
+ url,
93
+ anonKey,
94
+ accessToken: data.session.access_token,
95
+ refreshToken: data.session.refresh_token,
96
+ expiresAt: data.session.expires_at,
97
+ email: data.user?.email ?? email,
98
+ });
99
+
100
+ const when = data.session.expires_at
101
+ ? new Date(data.session.expires_at * 1000).toISOString()
102
+ : "unknown";
103
+ console.log(`\n✓ Signed in as ${data.user?.email ?? email}`);
104
+ console.log(` Session saved to ${sessionPath()} (token expires ${when}).`);
105
+ console.log(` The mosadd MCP server will now use it automatically — no env vars needed.`);
106
+ }
107
+
108
+ function whoami(): void {
109
+ const s = loadSession();
110
+ if (!s) {
111
+ console.log("Not logged in. Run `mosadd login`.");
112
+ process.exit(1);
113
+ }
114
+ const expired = isSessionExpired(s);
115
+ console.log(`Logged in as ${s.email ?? "(unknown)"} @ ${s.url}`);
116
+ console.log(`Token: ${expired ? "EXPIRED — run `mosadd login` again" : "valid"}`);
117
+ }
118
+
119
+ function logout(): void {
120
+ console.log(clearSession() ? "✓ Logged out (session cleared)." : "No session to clear.");
121
+ }
122
+
123
+ export async function runAuthCommand(cmd: string, args: string[]): Promise<void> {
124
+ switch (cmd) {
125
+ case "login":
126
+ await login(args);
127
+ break;
128
+ case "whoami":
129
+ whoami();
130
+ break;
131
+ case "logout":
132
+ logout();
133
+ break;
134
+ default:
135
+ console.error(`Unknown command: ${cmd}`);
136
+ process.exit(1);
137
+ }
138
+ }
package/src/bin/mcp.ts CHANGED
@@ -1,145 +1,145 @@
1
- #!/usr/bin/env node
2
- /**
3
- * `mosadd-mcp` (also runnable as `npx @mosadd/mcp`)
4
- *
5
- * Starts a mosadd MCP server over stdio. The standard transport for local
6
- * MCP clients (Claude Code, Cursor, Cline, Windsurf, Goose, ...).
7
- *
8
- * For HTTP/SSE transport (hosted mcp.mosadd.com), see packages/mcp-gateway
9
- * in the proprietary repo.
10
- */
11
-
12
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
- import { createClient } from "@supabase/supabase-js";
14
- import { createMosaddServer } from "../server.js";
15
- import { loadSession, saveSession, isSessionExpired } from "../config.js";
16
-
17
- const DEFAULT_EXCHANGE =
18
- "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";
19
-
20
- /**
21
- * Hosted-hub path: when MOSADD_API_KEY is set, exchange it for a short-lived
22
- * session (URL + anon key + access token) so the tools act as the key's owner.
23
- * Removes the DevTools-JWT wall — paste one stable key, done. Falls through
24
- * silently if the key is unset or the exchange is unreachable (so BYOK/self-host
25
- * keep working).
26
- */
27
- async function bootstrapFromApiKey(): Promise<void> {
28
- const apiKey = process.env.MOSADD_API_KEY;
29
- if (!apiKey || process.env.MOSADD_USER_JWT) return;
30
- const endpoint = process.env.MOSADD_HUB_URL
31
- ? `${process.env.MOSADD_HUB_URL.replace(/\/$/, "")}/hub-key-exchange`
32
- : DEFAULT_EXCHANGE;
33
- try {
34
- const res = await fetch(endpoint, {
35
- method: "POST",
36
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
37
- body: "{}",
38
- });
39
- if (!res.ok) {
40
- process.stderr.write(
41
- JSON.stringify({ level: "warn", msg: "mosadd hub key exchange failed", status: res.status }) + "\n",
42
- );
43
- return;
44
- }
45
- const d = (await res.json()) as { url?: string; anon_key?: string; access_token?: string };
46
- if (d.url) process.env.MOSADD_SUPABASE_URL = d.url;
47
- if (d.anon_key) process.env.MOSADD_SUPABASE_ANON_KEY = d.anon_key;
48
- if (d.access_token) process.env.MOSADD_USER_JWT = d.access_token;
49
- } catch (err) {
50
- process.stderr.write(
51
- JSON.stringify({ level: "warn", msg: "mosadd hub unreachable", error: String(err) }) + "\n",
52
- );
53
- }
54
- }
55
-
56
- /**
57
- * `mosadd login` path: refresh the saved session at boot so a stored token that
58
- * expired since the last launch (Supabase access tokens last ~1h) is renewed
59
- * silently from its refresh token — instead of failing the first tool call with
60
- * "session expired, run `mosadd login` again". This makes a single `mosadd login`
61
- * durable across restarts (the founder's "set once, forget" expectation). No-op
62
- * when an explicit env JWT or hub key already resolved a session, when there is no
63
- * saved session, or when the saved token is still valid.
64
- */
65
- async function bootstrapFromSavedSession(): Promise<void> {
66
- if (process.env.MOSADD_USER_JWT) return;
67
- const session = loadSession();
68
- if (!session?.refreshToken) return;
69
- // Still-valid token → the provider uses it as-is; don't churn the refresh token.
70
- if (!isSessionExpired(session)) return;
71
- try {
72
- const client = createClient(session.url, session.anonKey, {
73
- auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
74
- });
75
- const { data, error } = await client.auth.refreshSession({ refresh_token: session.refreshToken });
76
- if (error || !data.session) {
77
- process.stderr.write(
78
- JSON.stringify({ level: "warn", msg: "mosadd session refresh failed — run `mosadd login`", error: error?.message }) + "\n",
79
- );
80
- return;
81
- }
82
- saveSession({
83
- url: session.url,
84
- anonKey: session.anonKey,
85
- accessToken: data.session.access_token,
86
- refreshToken: data.session.refresh_token ?? session.refreshToken,
87
- expiresAt: data.session.expires_at,
88
- email: data.user?.email ?? session.email,
89
- });
90
- } catch (err) {
91
- process.stderr.write(
92
- JSON.stringify({ level: "warn", msg: "mosadd session refresh error — run `mosadd login`", error: String(err) }) + "\n",
93
- );
94
- }
95
- }
96
-
97
- async function main(): Promise<void> {
98
- // Auth subcommands: `mosadd login | logout | whoami`. Everything else starts the server.
99
- const sub = process.argv[2];
100
- if (sub === "login" || sub === "logout" || sub === "whoami") {
101
- const { runAuthCommand } = await import("./login.js");
102
- await runAuthCommand(sub, process.argv.slice(3));
103
- return;
104
- }
105
-
106
- // Hosted: trade MOSADD_API_KEY for a live session before the server reads env.
107
- await bootstrapFromApiKey();
108
- // `mosadd login`: renew a saved session whose access token expired since last launch.
109
- await bootstrapFromSavedSession();
110
-
111
- const server = createMosaddServer({
112
- apiKey: process.env.MOSADD_API_KEY,
113
- hubUrl: process.env.MOSADD_HUB_URL,
114
- mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
115
- logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
116
- // stdio is single-tenant: the session lives in env (set by bootstrapFromApiKey
117
- // above), so auto-publish this identity's prekeys on boot → mDM is reachable.
118
- autoPublishKeys: true,
119
- });
120
-
121
- const transport = new StdioServerTransport();
122
- await server.connect(transport);
123
-
124
- // The server now runs until stdin closes.
125
- process.stderr.write(
126
- JSON.stringify({
127
- level: "info",
128
- msg: "mosadd MCP server ready",
129
- version: "3.0.0-alpha.0",
130
- ts: new Date().toISOString(),
131
- }) + "\n",
132
- );
133
- }
134
-
135
- main().catch((err) => {
136
- process.stderr.write(
137
- JSON.stringify({
138
- level: "error",
139
- msg: "mosadd MCP server failed to start",
140
- error: err instanceof Error ? err.message : String(err),
141
- stack: err instanceof Error ? err.stack : undefined,
142
- }) + "\n",
143
- );
144
- process.exit(1);
145
- });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `mosadd-mcp` (also runnable as `npx @mosadd/mcp`)
4
+ *
5
+ * Starts a mosadd MCP server over stdio. The standard transport for local
6
+ * MCP clients (Claude Code, Cursor, Cline, Windsurf, Goose, ...).
7
+ *
8
+ * For HTTP/SSE transport (hosted mcp.mosadd.com), see packages/mcp-gateway
9
+ * in the proprietary repo.
10
+ */
11
+
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { createClient } from "@supabase/supabase-js";
14
+ import { createMosaddServer } from "../server.js";
15
+ import { loadSession, saveSession, isSessionExpired } from "../config.js";
16
+
17
+ const DEFAULT_EXCHANGE =
18
+ "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";
19
+
20
+ /**
21
+ * Hosted-hub path: when MOSADD_API_KEY is set, exchange it for a short-lived
22
+ * session (URL + anon key + access token) so the tools act as the key's owner.
23
+ * Removes the DevTools-JWT wall — paste one stable key, done. Falls through
24
+ * silently if the key is unset or the exchange is unreachable (so BYOK/self-host
25
+ * keep working).
26
+ */
27
+ async function bootstrapFromApiKey(): Promise<void> {
28
+ const apiKey = process.env.MOSADD_API_KEY;
29
+ if (!apiKey || process.env.MOSADD_USER_JWT) return;
30
+ const endpoint = process.env.MOSADD_HUB_URL
31
+ ? `${process.env.MOSADD_HUB_URL.replace(/\/$/, "")}/hub-key-exchange`
32
+ : DEFAULT_EXCHANGE;
33
+ try {
34
+ const res = await fetch(endpoint, {
35
+ method: "POST",
36
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
37
+ body: "{}",
38
+ });
39
+ if (!res.ok) {
40
+ process.stderr.write(
41
+ JSON.stringify({ level: "warn", msg: "mosadd hub key exchange failed", status: res.status }) + "\n",
42
+ );
43
+ return;
44
+ }
45
+ const d = (await res.json()) as { url?: string; anon_key?: string; access_token?: string };
46
+ if (d.url) process.env.MOSADD_SUPABASE_URL = d.url;
47
+ if (d.anon_key) process.env.MOSADD_SUPABASE_ANON_KEY = d.anon_key;
48
+ if (d.access_token) process.env.MOSADD_USER_JWT = d.access_token;
49
+ } catch (err) {
50
+ process.stderr.write(
51
+ JSON.stringify({ level: "warn", msg: "mosadd hub unreachable", error: String(err) }) + "\n",
52
+ );
53
+ }
54
+ }
55
+
56
+ /**
57
+ * `mosadd login` path: refresh the saved session at boot so a stored token that
58
+ * expired since the last launch (Supabase access tokens last ~1h) is renewed
59
+ * silently from its refresh token — instead of failing the first tool call with
60
+ * "session expired, run `mosadd login` again". This makes a single `mosadd login`
61
+ * durable across restarts (the founder's "set once, forget" expectation). No-op
62
+ * when an explicit env JWT or hub key already resolved a session, when there is no
63
+ * saved session, or when the saved token is still valid.
64
+ */
65
+ async function bootstrapFromSavedSession(): Promise<void> {
66
+ if (process.env.MOSADD_USER_JWT) return;
67
+ const session = loadSession();
68
+ if (!session?.refreshToken) return;
69
+ // Still-valid token → the provider uses it as-is; don't churn the refresh token.
70
+ if (!isSessionExpired(session)) return;
71
+ try {
72
+ const client = createClient(session.url, session.anonKey, {
73
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
74
+ });
75
+ const { data, error } = await client.auth.refreshSession({ refresh_token: session.refreshToken });
76
+ if (error || !data.session) {
77
+ process.stderr.write(
78
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh failed — run `mosadd login`", error: error?.message }) + "\n",
79
+ );
80
+ return;
81
+ }
82
+ saveSession({
83
+ url: session.url,
84
+ anonKey: session.anonKey,
85
+ accessToken: data.session.access_token,
86
+ refreshToken: data.session.refresh_token ?? session.refreshToken,
87
+ expiresAt: data.session.expires_at,
88
+ email: data.user?.email ?? session.email,
89
+ });
90
+ } catch (err) {
91
+ process.stderr.write(
92
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh error — run `mosadd login`", error: String(err) }) + "\n",
93
+ );
94
+ }
95
+ }
96
+
97
+ async function main(): Promise<void> {
98
+ // Auth subcommands: `mosadd login | logout | whoami`. Everything else starts the server.
99
+ const sub = process.argv[2];
100
+ if (sub === "login" || sub === "logout" || sub === "whoami") {
101
+ const { runAuthCommand } = await import("./login.js");
102
+ await runAuthCommand(sub, process.argv.slice(3));
103
+ return;
104
+ }
105
+
106
+ // Hosted: trade MOSADD_API_KEY for a live session before the server reads env.
107
+ await bootstrapFromApiKey();
108
+ // `mosadd login`: renew a saved session whose access token expired since last launch.
109
+ await bootstrapFromSavedSession();
110
+
111
+ const server = createMosaddServer({
112
+ apiKey: process.env.MOSADD_API_KEY,
113
+ hubUrl: process.env.MOSADD_HUB_URL,
114
+ mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
115
+ logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
116
+ // stdio is single-tenant: the session lives in env (set by bootstrapFromApiKey
117
+ // above), so auto-publish this identity's prekeys on boot → mDM is reachable.
118
+ autoPublishKeys: true,
119
+ });
120
+
121
+ const transport = new StdioServerTransport();
122
+ await server.connect(transport);
123
+
124
+ // The server now runs until stdin closes.
125
+ process.stderr.write(
126
+ JSON.stringify({
127
+ level: "info",
128
+ msg: "mosadd MCP server ready",
129
+ version: "3.0.0-alpha.0",
130
+ ts: new Date().toISOString(),
131
+ }) + "\n",
132
+ );
133
+ }
134
+
135
+ main().catch((err) => {
136
+ process.stderr.write(
137
+ JSON.stringify({
138
+ level: "error",
139
+ msg: "mosadd MCP server failed to start",
140
+ error: err instanceof Error ? err.message : String(err),
141
+ stack: err instanceof Error ? err.stack : undefined,
142
+ }) + "\n",
143
+ );
144
+ process.exit(1);
145
+ });