@mosadd/mcp 3.0.0-alpha.0 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,9 +23,9 @@ claude mcp add mosadd npx -- -y @mosadd/mcp
23
23
  "command": "npx",
24
24
  "args": ["-y", "@mosadd/mcp"],
25
25
  "env": {
26
- "M0SSAD_SUPABASE_URL": "https://<your-project>.supabase.co",
27
- "M0SSAD_SUPABASE_ANON_KEY": "<anon key>",
28
- "M0SSAD_USER_JWT": "<your session JWT>"
26
+ "MOSADD_SUPABASE_URL": "https://<your-project>.supabase.co",
27
+ "MOSADD_SUPABASE_ANON_KEY": "<anon key>",
28
+ "MOSADD_USER_JWT": "<your session JWT>"
29
29
  }
30
30
  }
31
31
  }
@@ -35,16 +35,16 @@ claude mcp add mosadd npx -- -y @mosadd/mcp
35
35
  ### Standalone
36
36
 
37
37
  ```bash
38
- M0SSAD_SUPABASE_URL=... M0SSAD_SUPABASE_ANON_KEY=... M0SSAD_USER_JWT=... npx @mosadd/mcp
38
+ MOSADD_SUPABASE_URL=... MOSADD_SUPABASE_ANON_KEY=... MOSADD_USER_JWT=... npx @mosadd/mcp
39
39
  ```
40
40
 
41
41
  ## BYOK — get your env values
42
42
 
43
43
  While the hosted gateway is in development, the alpha runs in **local BYOK mode** — you supply your own Supabase credentials to talk to your own m0ssad-3 backend.
44
44
 
45
- - `M0SSAD_SUPABASE_URL` — your Supabase project URL (e.g. `https://abc.supabase.co`)
46
- - `M0SSAD_SUPABASE_ANON_KEY` — the public anon key from project settings
47
- - `M0SSAD_USER_JWT` — a Supabase session token for your mosadd user. Get it from the browser:
45
+ - `MOSADD_SUPABASE_URL` — your Supabase project URL (e.g. `https://abc.supabase.co`)
46
+ - `MOSADD_SUPABASE_ANON_KEY` — the public anon key from project settings
47
+ - `MOSADD_USER_JWT` — a Supabase session token for your mosadd user. Get it from the browser:
48
48
  1. Sign in to mosadd.com
49
49
  2. Open DevTools → Application → Local Storage → `sb-<ref>-auth-token`
50
50
  3. Copy the `access_token` field
@@ -84,7 +84,7 @@ Agent (Claude / Cursor / ...)
84
84
  @mosadd/mcp server (this package)
85
85
  │
86
86
  │ supabase.functions.invoke('message-send', ...)
87
- │ + Authorization: Bearer <M0SSAD_USER_JWT>
87
+ │ + Authorization: Bearer <MOSADD_USER_JWT>
88
88
  ▼
89
89
  m0ssad-3 Edge Function
90
90
  │
@@ -103,9 +103,9 @@ For PTT / CALL / ROOM (real-time media), the architecture separates **control pl
103
103
 
104
104
  | Env | Description | Required |
105
105
  |---|---|---|
106
- | `M0SSAD_SUPABASE_URL` | Supabase project URL | yes |
107
- | `M0SSAD_SUPABASE_ANON_KEY` | Supabase anon key | yes |
108
- | `M0SSAD_USER_JWT` | User session token | yes (for tools that touch user data) |
106
+ | `MOSADD_SUPABASE_URL` | Supabase project URL | yes |
107
+ | `MOSADD_SUPABASE_ANON_KEY` | Supabase anon key | yes |
108
+ | `MOSADD_USER_JWT` | User session token | yes (for tools that touch user data) |
109
109
  | `MOSADD_API_KEY` | Hub API key (Phase 2 hosted mode) | no |
110
110
  | `MOSADD_HUB_URL` | Override hub url | no |
111
111
  | `MOSADD_MODE` | `local` / `cloud` / `self-host` | no (auto-detected) |
@@ -0,0 +1,13 @@
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
+ declare function runAuthCommand(cmd: string, args: string[]): Promise<void>;
12
+
13
+ export { runAuthCommand };
@@ -0,0 +1,110 @@
1
+ import {
2
+ clearSession,
3
+ isSessionExpired,
4
+ loadSession,
5
+ saveSession,
6
+ sessionPath
7
+ } from "../chunk-Z7WR52GE.js";
8
+
9
+ // src/bin/login.ts
10
+ import { createInterface } from "readline";
11
+ import { createClient } from "@supabase/supabase-js";
12
+ function parseFlags(args) {
13
+ const out = {};
14
+ for (let i = 0; i < args.length; i += 1) {
15
+ const a = args[i];
16
+ if (a.startsWith("--")) {
17
+ const key = a.slice(2);
18
+ const val = args[i + 1] && !args[i + 1].startsWith("--") ? args[i += 1] : "true";
19
+ out[key] = val;
20
+ }
21
+ }
22
+ return out;
23
+ }
24
+ function prompt(question, hidden = false) {
25
+ return new Promise((resolve) => {
26
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
27
+ if (hidden) {
28
+ const ro = rl;
29
+ let first = true;
30
+ ro._writeToOutput = (s) => {
31
+ if (first) {
32
+ process.stdout.write(question);
33
+ first = false;
34
+ } else if (s.includes("\n")) {
35
+ process.stdout.write("\n");
36
+ }
37
+ };
38
+ }
39
+ rl.question(hidden ? "" : question, (answer) => {
40
+ rl.close();
41
+ resolve(answer.trim());
42
+ });
43
+ });
44
+ }
45
+ async function login(args) {
46
+ const flags = parseFlags(args);
47
+ const prev = loadSession();
48
+ const url = flags.url || process.env.MOSADD_SUPABASE_URL || process.env.M0SSAD_SUPABASE_URL || prev?.url || await prompt("Supabase URL: ");
49
+ const anonKey = flags.anon || process.env.MOSADD_SUPABASE_ANON_KEY || process.env.M0SSAD_SUPABASE_ANON_KEY || prev?.anonKey || await prompt("Supabase anon key: ");
50
+ const email = flags.email || process.env.MOSADD_EMAIL || process.env.M0SSAD_EMAIL || await prompt("Email: ");
51
+ const password = flags.password || process.env.MOSADD_PASSWORD || process.env.M0SSAD_PASSWORD || await prompt("Password: ", true);
52
+ if (!url || !anonKey || !email || !password) {
53
+ console.error("\nmosadd login: need Supabase URL, anon key, email and password.");
54
+ process.exit(1);
55
+ }
56
+ const client = createClient(url, anonKey, {
57
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }
58
+ });
59
+ const { data, error } = await client.auth.signInWithPassword({ email, password });
60
+ if (error || !data.session) {
61
+ console.error(`
62
+ mosadd login failed: ${error?.message ?? "no session returned"}`);
63
+ process.exit(1);
64
+ }
65
+ saveSession({
66
+ url,
67
+ anonKey,
68
+ accessToken: data.session.access_token,
69
+ refreshToken: data.session.refresh_token,
70
+ expiresAt: data.session.expires_at,
71
+ email: data.user?.email ?? email
72
+ });
73
+ const when = data.session.expires_at ? new Date(data.session.expires_at * 1e3).toISOString() : "unknown";
74
+ console.log(`
75
+ \u2713 Signed in as ${data.user?.email ?? email}`);
76
+ console.log(` Session saved to ${sessionPath()} (token expires ${when}).`);
77
+ console.log(` The mosadd MCP server will now use it automatically \u2014 no env vars needed.`);
78
+ }
79
+ function whoami() {
80
+ const s = loadSession();
81
+ if (!s) {
82
+ console.log("Not logged in. Run `mosadd login`.");
83
+ process.exit(1);
84
+ }
85
+ const expired = isSessionExpired(s);
86
+ console.log(`Logged in as ${s.email ?? "(unknown)"} @ ${s.url}`);
87
+ console.log(`Token: ${expired ? "EXPIRED \u2014 run `mosadd login` again" : "valid"}`);
88
+ }
89
+ function logout() {
90
+ console.log(clearSession() ? "\u2713 Logged out (session cleared)." : "No session to clear.");
91
+ }
92
+ async function runAuthCommand(cmd, args) {
93
+ switch (cmd) {
94
+ case "login":
95
+ await login(args);
96
+ break;
97
+ case "whoami":
98
+ whoami();
99
+ break;
100
+ case "logout":
101
+ logout();
102
+ break;
103
+ default:
104
+ console.error(`Unknown command: ${cmd}`);
105
+ process.exit(1);
106
+ }
107
+ }
108
+ export {
109
+ runAuthCommand
110
+ };
package/dist/bin/mcp.js CHANGED
@@ -1,11 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createMosaddServer
4
- } from "../chunk-25L536JZ.js";
4
+ } from "../chunk-HD5RLE5K.js";
5
+ import "../chunk-Z7WR52GE.js";
5
6
 
6
7
  // src/bin/mcp.ts
7
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
9
  async function main() {
10
+ const sub = process.argv[2];
11
+ if (sub === "login" || sub === "logout" || sub === "whoami") {
12
+ const { runAuthCommand } = await import("./login.js");
13
+ await runAuthCommand(sub, process.argv.slice(3));
14
+ return;
15
+ }
9
16
  const server = createMosaddServer({
10
17
  apiKey: process.env.MOSADD_API_KEY,
11
18
  hubUrl: process.env.MOSADD_HUB_URL,
@@ -1,3 +1,8 @@
1
+ import {
2
+ isSessionExpired,
3
+ loadSession
4
+ } from "./chunk-Z7WR52GE.js";
5
+
1
6
  // src/tools/mdm.ts
2
7
  import { z } from "zod";
3
8
 
@@ -6,19 +11,25 @@ import { createClient } from "@supabase/supabase-js";
6
11
  var MissingSupabaseEnvError = class extends Error {
7
12
  constructor(missing) {
8
13
  super(
9
- `Missing Supabase env vars: ${missing.join(", ")}. Set M0SSAD_SUPABASE_URL, M0SSAD_SUPABASE_ANON_KEY, and (for authenticated calls) M0SSAD_USER_JWT.`
14
+ `Missing Supabase credentials: ${missing.join(", ")}. Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`
10
15
  );
11
16
  this.name = "MissingSupabaseEnvError";
12
17
  }
13
18
  };
14
19
  function readSupabaseEnv() {
15
- const url = process.env.M0SSAD_SUPABASE_URL;
16
- const anonKey = process.env.M0SSAD_SUPABASE_ANON_KEY;
17
- const userJwt = process.env.M0SSAD_USER_JWT;
20
+ const env = (canonical, legacy) => process.env[canonical] ?? process.env[legacy];
21
+ const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
22
+ const session = loadSession();
23
+ const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
24
+ const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
25
+ const userJwt = userJwtEnv ?? session?.accessToken;
18
26
  const missing = [];
19
- if (!url) missing.push("M0SSAD_SUPABASE_URL");
20
- if (!anonKey) missing.push("M0SSAD_SUPABASE_ANON_KEY");
27
+ if (!url) missing.push("MOSADD_SUPABASE_URL");
28
+ if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
21
29
  if (missing.length) throw new MissingSupabaseEnvError(missing);
30
+ if (!userJwtEnv && session && isSessionExpired(session)) {
31
+ throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
32
+ }
22
33
  return { url, anonKey, userJwt };
23
34
  }
24
35
  function getSupabase(env = readSupabaseEnv()) {
@@ -295,7 +306,7 @@ async function resolveSelfIdentityId() {
295
306
  const { data: u, error: ue } = await sb.auth.getUser();
296
307
  if (ue || !u?.user) {
297
308
  throw new Error(
298
- "Unable to resolve current user. Ensure M0SSAD_USER_JWT is set to a valid Supabase session token."
309
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
299
310
  );
300
311
  }
301
312
  const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
@@ -1042,7 +1053,7 @@ var SupabaseDmProvider = class {
1042
1053
  const { data: u, error: ue } = await sb.auth.getUser();
1043
1054
  if (ue || !u?.user) {
1044
1055
  throw new Error(
1045
- "Unable to resolve current user. Ensure M0SSAD_USER_JWT is set to a valid Supabase session token."
1056
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1046
1057
  );
1047
1058
  }
1048
1059
  const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
@@ -0,0 +1,45 @@
1
+ // src/config.ts
2
+ import { homedir } from "os";
3
+ import { join } from "path";
4
+ import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from "fs";
5
+ function configDir() {
6
+ return join(homedir(), ".mosadd");
7
+ }
8
+ function sessionPath() {
9
+ return join(configDir(), "session.json");
10
+ }
11
+ function loadSession() {
12
+ try {
13
+ const raw = readFileSync(sessionPath(), "utf8");
14
+ const s = JSON.parse(raw);
15
+ if (s && typeof s.url === "string" && typeof s.anonKey === "string") return s;
16
+ return null;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+ function saveSession(session) {
22
+ mkdirSync(configDir(), { recursive: true });
23
+ writeFileSync(sessionPath(), JSON.stringify(session, null, 2), "utf8");
24
+ try {
25
+ chmodSync(sessionPath(), 384);
26
+ } catch {
27
+ }
28
+ }
29
+ function clearSession() {
30
+ if (!existsSync(sessionPath())) return false;
31
+ rmSync(sessionPath());
32
+ return true;
33
+ }
34
+ function isSessionExpired(session) {
35
+ if (!session.expiresAt) return false;
36
+ return Date.now() / 1e3 >= session.expiresAt - 30;
37
+ }
38
+
39
+ export {
40
+ sessionPath,
41
+ loadSession,
42
+ saveSession,
43
+ clearSession,
44
+ isSessionExpired
45
+ };
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@ import {
2
2
  allTools,
3
3
  createMosaddServer,
4
4
  defaultProviders
5
- } from "./chunk-25L536JZ.js";
5
+ } from "./chunk-HD5RLE5K.js";
6
+ import "./chunk-Z7WR52GE.js";
6
7
  export {
7
8
  allTools,
8
9
  createMosaddServer,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.0",
3
+ "version": "3.0.0-alpha.2",
4
4
  "description": "Model Context Protocol server for mosadd. Exposes m* OS modules (mDM, mTALK, mAIL, mCALL, mIRC, mIRL, mROOM, and bridges) as MCP tools to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
5
  "homepage": "https://github.com/Hei33enberg/mosadd-os/tree/main/packages/mcp",
6
6
  "repository": {
@@ -20,7 +20,8 @@
20
20
  }
21
21
  },
22
22
  "bin": {
23
- "mosadd-mcp": "./dist/bin/mcp.js"
23
+ "mosadd-mcp": "./dist/bin/mcp.js",
24
+ "mosadd": "./dist/bin/mcp.js"
24
25
  },
25
26
  "files": [
26
27
  "dist",
@@ -35,8 +36,8 @@
35
36
  "@modelcontextprotocol/sdk": "^1.0.4",
36
37
  "@supabase/supabase-js": "^2.48.0",
37
38
  "zod": "^4.3.6",
38
- "@mosadd/crypto": "3.0.0-alpha.0",
39
39
  "@mosadd/providers": "3.0.0-alpha.0",
40
+ "@mosadd/crypto": "3.0.0-alpha.0",
40
41
  "@mosadd/protocol": "3.0.0-alpha.0"
41
42
  },
42
43
  "devDependencies": {
@@ -57,7 +58,7 @@
57
58
  "messaging"
58
59
  ],
59
60
  "scripts": {
60
- "build": "tsup src/index.ts src/bin/mcp.ts --format esm --dts --clean --shims",
61
+ "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
61
62
  "dev": "tsx src/bin/mcp.ts",
62
63
  "test": "vitest run",
63
64
  "typecheck": "tsc -p tsconfig.json --noEmit",
@@ -158,7 +158,7 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
158
158
  clientInfo: { name: "vitest", version: "1.0" },
159
159
  });
160
160
 
161
- // mDM_send needs M0SSAD_SUPABASE_URL etc. — in test env we don't have them,
161
+ // mDM_send needs MOSADD_SUPABASE_URL etc. — in test env we don't have them,
162
162
  // so the handler will throw MissingSupabaseEnvError. The MCP layer must wrap
163
163
  // that in a normal `isError: true` content block, not a JSON-RPC error
164
164
  // (that would crash the agent loop).
@@ -0,0 +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
+ }
package/src/bin/mcp.ts CHANGED
@@ -13,6 +13,14 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
13
13
  import { createMosaddServer } from "../server.js";
14
14
 
15
15
  async function main(): Promise<void> {
16
+ // Auth subcommands: `mosadd login | logout | whoami`. Everything else starts the server.
17
+ const sub = process.argv[2];
18
+ if (sub === "login" || sub === "logout" || sub === "whoami") {
19
+ const { runAuthCommand } = await import("./login.js");
20
+ await runAuthCommand(sub, process.argv.slice(3));
21
+ return;
22
+ }
23
+
16
24
  const server = createMosaddServer({
17
25
  apiKey: process.env.MOSADD_API_KEY,
18
26
  hubUrl: process.env.MOSADD_HUB_URL,
package/src/config.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Local session config for the mosadd CLI (`mosadd login`).
3
+ *
4
+ * Stores the authenticated session at `~/.mosadd/session.json` so the MCP
5
+ * server can pick up credentials without the user pasting an expiring JWT
6
+ * from mosadd.com DevTools into env vars. Env vars still take precedence.
7
+ *
8
+ * The file holds a Supabase session (BYOK): the project URL + anon key (both
9
+ * public, RLS-gated) and the user's access/refresh tokens.
10
+ */
11
+
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from "node:fs";
15
+
16
+ export interface MosaddSession {
17
+ url: string;
18
+ anonKey: string;
19
+ accessToken: string;
20
+ refreshToken?: string;
21
+ /** Unix seconds when the access token expires. */
22
+ expiresAt?: number;
23
+ email?: string;
24
+ }
25
+
26
+ export function configDir(): string {
27
+ return join(homedir(), ".mosadd");
28
+ }
29
+
30
+ export function sessionPath(): string {
31
+ return join(configDir(), "session.json");
32
+ }
33
+
34
+ export function loadSession(): MosaddSession | null {
35
+ try {
36
+ const raw = readFileSync(sessionPath(), "utf8");
37
+ const s = JSON.parse(raw) as MosaddSession;
38
+ if (s && typeof s.url === "string" && typeof s.anonKey === "string") return s;
39
+ return null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ export function saveSession(session: MosaddSession): void {
46
+ mkdirSync(configDir(), { recursive: true });
47
+ writeFileSync(sessionPath(), JSON.stringify(session, null, 2), "utf8");
48
+ // Best-effort tighten perms (no-op on platforms that ignore it).
49
+ try {
50
+ chmodSync(sessionPath(), 0o600);
51
+ } catch {
52
+ /* ignore */
53
+ }
54
+ }
55
+
56
+ export function clearSession(): boolean {
57
+ if (!existsSync(sessionPath())) return false;
58
+ rmSync(sessionPath());
59
+ return true;
60
+ }
61
+
62
+ /** True if the stored token is past (or within 30s of) its expiry. */
63
+ export function isSessionExpired(session: MosaddSession): boolean {
64
+ if (!session.expiresAt) return false;
65
+ return Date.now() / 1000 >= session.expiresAt - 30;
66
+ }
@@ -3,26 +3,26 @@
3
3
  *
4
4
  * Optional. The MCP server runs entirely as user-supplied stdio — most
5
5
  * operators won't want their tool errors phoning home. We expose an opt-in
6
- * env var (M0SSAD_SENTRY_DSN) so power users / hub-operators can attach.
6
+ * env var (MOSADD_SENTRY_DSN) so power users / hub-operators can attach.
7
7
  *
8
8
  * Setup (one-time, hub operators):
9
9
  * 1. Create a project in https://papugai.sentry.io named "mosadd-mcp"
10
10
  * with platform = Node.
11
- * 2. Export M0SSAD_SENTRY_DSN before running the server.
11
+ * 2. Export MOSADD_SENTRY_DSN before running the server.
12
12
  *
13
13
  * Without the env var, this module is an inert no-op.
14
14
  */
15
15
 
16
- const DSN = process.env.M0SSAD_SENTRY_DSN;
16
+ const DSN = process.env.MOSADD_SENTRY_DSN;
17
17
  const ENV =
18
- process.env.M0SSAD_SENTRY_ENVIRONMENT ??
18
+ process.env.MOSADD_SENTRY_ENVIRONMENT ??
19
19
  process.env.NODE_ENV ??
20
20
  "production";
21
- const RELEASE = process.env.M0SSAD_SENTRY_RELEASE;
21
+ const RELEASE = process.env.MOSADD_SENTRY_RELEASE;
22
22
 
23
23
  let initialized = false;
24
24
  // @sentry/node is an OPTIONAL peer — operators install it only if they opt in
25
- // via M0SSAD_SENTRY_DSN. Typed as `any` + loaded via a non-literal specifier so
25
+ // via MOSADD_SENTRY_DSN. Typed as `any` + loaded via a non-literal specifier so
26
26
  // the package compiles and ships without the dependency present.
27
27
  let sentryRef: any = null;
28
28
 
@@ -32,7 +32,7 @@ export class SupabaseDmProvider implements DmProvider {
32
32
  const { data: u, error: ue } = await sb.auth.getUser();
33
33
  if (ue || !u?.user) {
34
34
  throw new Error(
35
- "Unable to resolve current user. Ensure M0SSAD_USER_JWT is set to a valid Supabase session token.",
35
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
36
36
  );
37
37
  }
38
38
  const { data: identity, error } = await sb
@@ -1,80 +1,96 @@
1
- /**
2
- * Supabase provider for the alpha MCP server.
3
- *
4
- * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
- * via env vars. The MCP server creates a per-request Supabase client and
6
- * invokes the m0ssad-3 Edge Functions on the user's behalf.
7
- *
8
- * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
- * holds keys server-side via the BYOK broker.
10
- */
11
-
12
- import { createClient, type SupabaseClient } from "@supabase/supabase-js";
13
-
14
- export interface SupabaseEnv {
15
- url: string;
16
- anonKey: string;
17
- userJwt?: string;
18
- }
19
-
20
- export class MissingSupabaseEnvError extends Error {
21
- constructor(missing: string[]) {
22
- super(
23
- `Missing Supabase env vars: ${missing.join(", ")}. ` +
24
- `Set M0SSAD_SUPABASE_URL, M0SSAD_SUPABASE_ANON_KEY, and (for authenticated calls) M0SSAD_USER_JWT.`,
25
- );
26
- this.name = "MissingSupabaseEnvError";
27
- }
28
- }
29
-
30
- export function readSupabaseEnv(): SupabaseEnv {
31
- const url = process.env.M0SSAD_SUPABASE_URL;
32
- const anonKey = process.env.M0SSAD_SUPABASE_ANON_KEY;
33
- const userJwt = process.env.M0SSAD_USER_JWT;
34
- const missing: string[] = [];
35
- if (!url) missing.push("M0SSAD_SUPABASE_URL");
36
- if (!anonKey) missing.push("M0SSAD_SUPABASE_ANON_KEY");
37
- if (missing.length) throw new MissingSupabaseEnvError(missing);
38
- return { url: url!, anonKey: anonKey!, userJwt };
39
- }
40
-
41
- export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
42
- return createClient(env.url, env.anonKey, {
43
- auth: {
44
- persistSession: false,
45
- autoRefreshToken: false,
46
- detectSessionInUrl: false,
47
- },
48
- global: env.userJwt
49
- ? {
50
- headers: { Authorization: `Bearer ${env.userJwt}` },
51
- }
52
- : undefined,
53
- });
54
- }
55
-
56
- /**
57
- * Invoke a m0ssad-3 Edge Function. Wraps `supabase.functions.invoke` with
58
- * normalized error handling so MCP tool handlers can throw clean errors that
59
- * agents can reason about.
60
- */
61
- export async function invokeFunction<T = unknown>(
62
- fn: string,
63
- body: Record<string, unknown>,
64
- ): Promise<T> {
65
- const client = getSupabase();
66
- const { data, error } = await client.functions.invoke<T>(fn, { body });
67
- if (error) {
68
- const msg =
69
- error instanceof Error
70
- ? error.message
71
- : typeof (error as { message?: unknown })?.message === "string"
72
- ? (error as { message: string }).message
73
- : `Edge function ${fn} failed`;
74
- throw new Error(msg);
75
- }
76
- if (data == null) {
77
- throw new Error(`Edge function ${fn} returned no data`);
78
- }
79
- return data;
80
- }
1
+ /**
2
+ * Supabase provider for the alpha MCP server.
3
+ *
4
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
+ * via env vars. The MCP server creates a per-request Supabase client and
6
+ * invokes the m0ssad-3 Edge Functions on the user's behalf.
7
+ *
8
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
+ * holds keys server-side via the BYOK broker.
10
+ */
11
+
12
+ import { createClient, type SupabaseClient } from "@supabase/supabase-js";
13
+ import { loadSession, isSessionExpired } from "../config.js";
14
+
15
+ export interface SupabaseEnv {
16
+ url: string;
17
+ anonKey: string;
18
+ userJwt?: string;
19
+ }
20
+
21
+ export class MissingSupabaseEnvError extends Error {
22
+ constructor(missing: string[]) {
23
+ super(
24
+ `Missing Supabase credentials: ${missing.join(", ")}. ` +
25
+ `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
26
+ );
27
+ this.name = "MissingSupabaseEnvError";
28
+ }
29
+ }
30
+
31
+ export function readSupabaseEnv(): SupabaseEnv {
32
+ // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
33
+ // honored (deprecated) so anyone who set them before the brand sweep keeps
34
+ // working. Env vars take precedence; fall back to the session saved by
35
+ // `mosadd login`.
36
+ const env = (canonical: string, legacy: string): string | undefined =>
37
+ process.env[canonical] ?? process.env[legacy];
38
+ const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
39
+
40
+ const session = loadSession();
41
+ const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
42
+ const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
43
+ const userJwt = userJwtEnv ?? session?.accessToken;
44
+
45
+ const missing: string[] = [];
46
+ if (!url) missing.push("MOSADD_SUPABASE_URL");
47
+ if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
48
+ if (missing.length) throw new MissingSupabaseEnvError(missing);
49
+
50
+ // Surface an expired `mosadd login` token early with an actionable message.
51
+ if (!userJwtEnv && session && isSessionExpired(session)) {
52
+ throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
53
+ }
54
+ return { url: url!, anonKey: anonKey!, userJwt };
55
+ }
56
+
57
+ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
58
+ return createClient(env.url, env.anonKey, {
59
+ auth: {
60
+ persistSession: false,
61
+ autoRefreshToken: false,
62
+ detectSessionInUrl: false,
63
+ },
64
+ global: env.userJwt
65
+ ? {
66
+ headers: { Authorization: `Bearer ${env.userJwt}` },
67
+ }
68
+ : undefined,
69
+ });
70
+ }
71
+
72
+ /**
73
+ * Invoke a m0ssad-3 Edge Function. Wraps `supabase.functions.invoke` with
74
+ * normalized error handling so MCP tool handlers can throw clean errors that
75
+ * agents can reason about.
76
+ */
77
+ export async function invokeFunction<T = unknown>(
78
+ fn: string,
79
+ body: Record<string, unknown>,
80
+ ): Promise<T> {
81
+ const client = getSupabase();
82
+ const { data, error } = await client.functions.invoke<T>(fn, { body });
83
+ if (error) {
84
+ const msg =
85
+ error instanceof Error
86
+ ? error.message
87
+ : typeof (error as { message?: unknown })?.message === "string"
88
+ ? (error as { message: string }).message
89
+ : `Edge function ${fn} failed`;
90
+ throw new Error(msg);
91
+ }
92
+ if (data == null) {
93
+ throw new Error(`Edge function ${fn} returned no data`);
94
+ }
95
+ return data;
96
+ }
package/src/tools/mdm.ts CHANGED
@@ -94,7 +94,7 @@ async function resolveSelfIdentityId(): Promise<string> {
94
94
  const { data: u, error: ue } = await sb.auth.getUser();
95
95
  if (ue || !u?.user) {
96
96
  throw new Error(
97
- "Unable to resolve current user. Ensure M0SSAD_USER_JWT is set to a valid Supabase session token.",
97
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
98
98
  );
99
99
  }
100
100
  const { data: identity, error } = await sb