@mosadd/mcp 3.0.0-alpha.47 → 3.0.0-alpha.49
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/dist/bin/mcp.js +1 -1
- package/dist/{chunk-XTQMZ6K7.js → chunk-MGF7BV3M.js} +41 -23
- package/dist/index.js +1 -1
- package/package.json +73 -73
- package/src/__tests__/knowledge-ingest.test.ts +114 -114
- package/src/__tests__/presence.test.ts +190 -190
- package/src/__tests__/serverJsonVersion.test.ts +45 -45
- package/src/providers/supabase.ts +231 -231
- package/src/server.ts +162 -162
- package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
- package/src/tools/knowledge-graph.ts +186 -186
- package/src/tools/mail-agentbox.ts +155 -155
- package/src/tools/mcall.ts +216 -216
- package/src/tools/mdm-as-agent.ts +126 -126
- package/src/tools/mdm-voice.ts +220 -220
- package/src/tools/mdm.ts +495 -494
- package/src/tools/mirc-messages.ts +186 -185
- package/src/tools/murl.ts +314 -314
- package/src/tools/presence.ts +442 -414
- package/src/tools/ptt-ingest.ts +99 -99
- package/src/tools/threat.ts +123 -123
- package/src/tools/voice-format.ts +28 -0
- package/src/version.ts +8 -8
- package/LICENSE +0 -201
- package/dist/bin/login.d.ts +0 -13
- package/dist/bin/mcp.d.ts +0 -1
- package/dist/index.d.ts +0 -310
|
@@ -1,231 +1,231 @@
|
|
|
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 mosadd 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 { AsyncLocalStorage } from "node:async_hooks";
|
|
13
|
-
import { randomUUID } from "node:crypto";
|
|
14
|
-
import { hostname } from "node:os";
|
|
15
|
-
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
|
|
16
|
-
import { loadSession, isSessionExpired } from "../config.js";
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Tożsamość TEGO procesu — stała przez całe życie sesji, nowa przy każdym starcie.
|
|
20
|
-
*
|
|
21
|
-
* ⛔ NIE MOŻE być pochodną konta ani hosta. Dwie sesje generałów potrafią stać na tej samej
|
|
22
|
-
* maszynie i pod tym samym kontem (box floty), więc identyfikator z hosta zlepiłby je z powrotem
|
|
23
|
-
* w jedną — czyli odtworzył dokładnie ten błąd, który to naprawia. Nazwa hosta zostaje tylko jako
|
|
24
|
-
* czytelny przedrostek do diagnostyki; o rozróżnieniu decyduje losowy ogon.
|
|
25
|
-
*/
|
|
26
|
-
let cachedSessionId: string | null = null;
|
|
27
|
-
export function sessionId(): string {
|
|
28
|
-
// ⛔ BRAMA HOSTOWANA ≠ PROCES (audyt 2026-08-27). Na mcp.mosadd.com jeden proces lambdy obsługuje
|
|
29
|
-
// WIELU najemców, a kolejne wywołania tej samej rozmowy potrafią trafić w RÓŻNE procesy — więc
|
|
30
|
-
// tożsamość per-proces byłaby tam jednocześnie wspólna (wyciek między najemcami) i niestała
|
|
31
|
-
// (fałszywe 409 przy każdym przełączeniu instancji). W kontekście bramy prawda żyje w ALS:
|
|
32
|
-
// brama wyznacza stabilny `sessionKey` per klucz API; brak klucza = puste "" (semantyka legacy,
|
|
33
|
-
// zero roszczeń per-sesja). Losowy identyfikator per-proces zostaje TYLKO dla stdio.
|
|
34
|
-
const perRequest = requestEnv.getStore();
|
|
35
|
-
if (perRequest) return perRequest.sessionKey ?? "";
|
|
36
|
-
if (cachedSessionId) return cachedSessionId;
|
|
37
|
-
let host = "mcp";
|
|
38
|
-
try { host = (hostname() || "mcp").slice(0, 24); } catch { /* bez nazwy hosta też działa */ }
|
|
39
|
-
cachedSessionId = `${host}:${randomUUID()}`;
|
|
40
|
-
return cachedSessionId;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface SupabaseEnv {
|
|
44
|
-
url: string;
|
|
45
|
-
anonKey: string;
|
|
46
|
-
userJwt?: string;
|
|
47
|
-
/** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
|
|
48
|
-
sessionKey?: string;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
|
|
53
|
-
*
|
|
54
|
-
* stdio runs one user per process, so credentials live in process.env. The
|
|
55
|
-
* hosted gateway serves MANY users from one process — sharing process.env would
|
|
56
|
-
* leak user A's JWT into user B's concurrent request. The gateway instead
|
|
57
|
-
* resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
|
|
58
|
-
* whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
|
|
59
|
-
* this store first and falls back to process.env, so stdio is unaffected.
|
|
60
|
-
*/
|
|
61
|
-
const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
|
|
62
|
-
|
|
63
|
-
/** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
|
|
64
|
-
export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
|
|
65
|
-
return requestEnv.run(env, fn);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export class MissingSupabaseEnvError extends Error {
|
|
69
|
-
constructor(missing: string[]) {
|
|
70
|
-
super(
|
|
71
|
-
`Missing Supabase credentials: ${missing.join(", ")}. ` +
|
|
72
|
-
`Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
|
|
73
|
-
);
|
|
74
|
-
this.name = "MissingSupabaseEnvError";
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export function readSupabaseEnv(): SupabaseEnv {
|
|
79
|
-
// Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
|
|
80
|
-
// over any process-global env (multi-tenant safety). stdio has no store → falls
|
|
81
|
-
// through to the env/login resolution below.
|
|
82
|
-
const perRequest = requestEnv.getStore();
|
|
83
|
-
if (perRequest) return perRequest;
|
|
84
|
-
|
|
85
|
-
// Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
|
|
86
|
-
// honored (deprecated) so anyone who set them before the brand sweep keeps
|
|
87
|
-
// working. Env vars take precedence; fall back to the session saved by
|
|
88
|
-
// `mosadd login`.
|
|
89
|
-
const env = (canonical: string, legacy: string): string | undefined =>
|
|
90
|
-
process.env[canonical] ?? process.env[legacy];
|
|
91
|
-
const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
|
|
92
|
-
|
|
93
|
-
const session = loadSession();
|
|
94
|
-
const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
|
|
95
|
-
const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
|
|
96
|
-
const userJwt = userJwtEnv ?? session?.accessToken;
|
|
97
|
-
|
|
98
|
-
const missing: string[] = [];
|
|
99
|
-
if (!url) missing.push("MOSADD_SUPABASE_URL");
|
|
100
|
-
if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
|
|
101
|
-
if (missing.length) throw new MissingSupabaseEnvError(missing);
|
|
102
|
-
|
|
103
|
-
// Surface an expired `mosadd login` token early with an actionable message.
|
|
104
|
-
if (!userJwtEnv && session && isSessionExpired(session)) {
|
|
105
|
-
throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
|
|
106
|
-
}
|
|
107
|
-
return { url: url!, anonKey: anonKey!, userJwt };
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
|
|
111
|
-
return createClient(env.url, env.anonKey, {
|
|
112
|
-
auth: {
|
|
113
|
-
persistSession: false,
|
|
114
|
-
autoRefreshToken: false,
|
|
115
|
-
detectSessionInUrl: false,
|
|
116
|
-
},
|
|
117
|
-
// ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
|
|
118
|
-
// rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
|
|
119
|
-
// kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
|
|
120
|
-
// hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
|
|
121
|
-
// post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
|
|
122
|
-
// wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
|
|
123
|
-
global: {
|
|
124
|
-
headers: {
|
|
125
|
-
...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
|
|
126
|
-
"x-mosadd-origin": "hub-gateway",
|
|
127
|
-
// Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
|
|
128
|
-
// więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
|
|
129
|
-
...(sessionId() ? { "x-mosadd-session": sessionId() } : {}),
|
|
130
|
-
// ⛔ KTÓRA TO SESJA (2026-08-27, „każdy generał co chwilę gubi mózg"). Wszyscy generałowie
|
|
131
|
-
// wpinają się kluczem hub TEGO SAMEGO właściciela, więc dla serwera ich wywołania były
|
|
132
|
-
// nieodróżnialne — a deklaracja linii (`comms_session_attach as_agent`) trzymała JEDEN
|
|
133
|
-
// wiersz na konto. Skutek: kto wpiął się ostatni, odbierał linię wszystkim pozostałym, a
|
|
134
|
-
// ich posty na kanałach zaczynały wracać z 403. Tożsamość sesji (stdio: per proces,
|
|
135
|
-
// brama: per klucz API) pozwala dziewięciu liniom na jednym koncie nie deptać sobie po piętach.
|
|
136
|
-
},
|
|
137
|
-
},
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
|
|
143
|
-
* normalized error handling so MCP tool handlers can throw clean errors that
|
|
144
|
-
* agents can reason about.
|
|
145
|
-
*/
|
|
146
|
-
export async function invokeFunction<T = unknown>(
|
|
147
|
-
fn: string,
|
|
148
|
-
body: Record<string, unknown>,
|
|
149
|
-
): Promise<T> {
|
|
150
|
-
const client = getSupabase();
|
|
151
|
-
const { data, error } = await client.functions.invoke<T>(fn, { body });
|
|
152
|
-
if (error) {
|
|
153
|
-
// supabase-js throws FunctionsHttpError for any non-2xx, whose `.message`
|
|
154
|
-
// is the FIXED generic string "Edge Function returned a non-2xx status
|
|
155
|
-
// code" — the *real* reason (e.g. {"error":"wrapped_group_key required"},
|
|
156
|
-
// "forbidden", an RLS denial) lives in `error.context`, a Response. Read it
|
|
157
|
-
// so the agent gets an actionable message (and the HTTP status) it can
|
|
158
|
-
// reason about and self-correct on, instead of the same opaque sentence
|
|
159
|
-
// for every failure across mDM/mIRC/mp0st/mRAG/prekey/message-list.
|
|
160
|
-
let msg =
|
|
161
|
-
error instanceof Error && error.message
|
|
162
|
-
? error.message
|
|
163
|
-
: `Edge function ${fn} failed`;
|
|
164
|
-
const ctx = (error as { context?: unknown }).context;
|
|
165
|
-
if (ctx && typeof (ctx as Response).text === "function") {
|
|
166
|
-
const res = ctx as Response;
|
|
167
|
-
try {
|
|
168
|
-
const raw = await res.text();
|
|
169
|
-
if (raw) {
|
|
170
|
-
let detail = raw;
|
|
171
|
-
let recipe = "";
|
|
172
|
-
try {
|
|
173
|
-
const parsed = JSON.parse(raw) as {
|
|
174
|
-
error?: unknown;
|
|
175
|
-
message?: unknown;
|
|
176
|
-
code?: unknown;
|
|
177
|
-
message_en?: unknown;
|
|
178
|
-
next_steps?: unknown;
|
|
179
|
-
};
|
|
180
|
-
detail =
|
|
181
|
-
(typeof parsed.error === "string" && parsed.error) ||
|
|
182
|
-
(typeof parsed.message === "string" && parsed.message) ||
|
|
183
|
-
raw;
|
|
184
|
-
// ⛔ The refusal CONTRACT (supabase/functions/_shared/errors.ts) travels as
|
|
185
|
-
// { code, message_en, message_pl, next_steps[] }. Until 2026-09-04 this block read
|
|
186
|
-
// `error` alone and threw the rest away — so the server said "here is exactly what to
|
|
187
|
-
// do next" and the agent received one flat sentence. The recipe is the whole point of
|
|
188
|
-
// the contract: it is written FOR a machine to act on. Measured on production the same
|
|
189
|
-
// day: mIRC_post_message with someone else's agent returned only
|
|
190
|
-
// "message-send (403): agent_not_owned" — code, both messages and 2 next_steps dropped.
|
|
191
|
-
// Rendered below as plain text because that is what an MCP tool error carries.
|
|
192
|
-
const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
|
|
193
|
-
const lines: string[] = [];
|
|
194
|
-
if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
|
|
195
|
-
if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
|
|
196
|
-
lines.push(parsed.message_en);
|
|
197
|
-
}
|
|
198
|
-
for (const raw_step of steps) {
|
|
199
|
-
const step = raw_step as { actor?: unknown; tool?: unknown; ui?: unknown; args?: unknown; why?: unknown };
|
|
200
|
-
const who = typeof step.actor === "string" ? step.actor : "?";
|
|
201
|
-
const what =
|
|
202
|
-
(typeof step.tool === "string" && step.tool) ||
|
|
203
|
-
(typeof step.ui === "string" && step.ui) ||
|
|
204
|
-
"";
|
|
205
|
-
if (!what) continue;
|
|
206
|
-
const why = typeof step.why === "string" ? ` — ${step.why}` : "";
|
|
207
|
-
const args =
|
|
208
|
-
step.args && typeof step.args === "object"
|
|
209
|
-
? ` ${JSON.stringify(step.args)}`
|
|
210
|
-
: "";
|
|
211
|
-
lines.push(`next (${who}): ${what}${args}${why}`);
|
|
212
|
-
}
|
|
213
|
-
if (lines.length) recipe = "\n" + lines.join("\n");
|
|
214
|
-
} catch {
|
|
215
|
-
// non-JSON body — use the raw text as-is
|
|
216
|
-
}
|
|
217
|
-
const status = typeof res.status === "number" ? res.status : undefined;
|
|
218
|
-
// First line stays byte-for-byte what callers have always matched on; the recipe follows.
|
|
219
|
-
msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
|
|
220
|
-
}
|
|
221
|
-
} catch {
|
|
222
|
-
// body already consumed or unreadable — keep the generic message
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
throw new Error(msg);
|
|
226
|
-
}
|
|
227
|
-
if (data == null) {
|
|
228
|
-
throw new Error(`Edge function ${fn} returned no data`);
|
|
229
|
-
}
|
|
230
|
-
return data;
|
|
231
|
-
}
|
|
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 mosadd 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 { AsyncLocalStorage } from "node:async_hooks";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { hostname } from "node:os";
|
|
15
|
+
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
|
|
16
|
+
import { loadSession, isSessionExpired } from "../config.js";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Tożsamość TEGO procesu — stała przez całe życie sesji, nowa przy każdym starcie.
|
|
20
|
+
*
|
|
21
|
+
* ⛔ NIE MOŻE być pochodną konta ani hosta. Dwie sesje generałów potrafią stać na tej samej
|
|
22
|
+
* maszynie i pod tym samym kontem (box floty), więc identyfikator z hosta zlepiłby je z powrotem
|
|
23
|
+
* w jedną — czyli odtworzył dokładnie ten błąd, który to naprawia. Nazwa hosta zostaje tylko jako
|
|
24
|
+
* czytelny przedrostek do diagnostyki; o rozróżnieniu decyduje losowy ogon.
|
|
25
|
+
*/
|
|
26
|
+
let cachedSessionId: string | null = null;
|
|
27
|
+
export function sessionId(): string {
|
|
28
|
+
// ⛔ BRAMA HOSTOWANA ≠ PROCES (audyt 2026-08-27). Na mcp.mosadd.com jeden proces lambdy obsługuje
|
|
29
|
+
// WIELU najemców, a kolejne wywołania tej samej rozmowy potrafią trafić w RÓŻNE procesy — więc
|
|
30
|
+
// tożsamość per-proces byłaby tam jednocześnie wspólna (wyciek między najemcami) i niestała
|
|
31
|
+
// (fałszywe 409 przy każdym przełączeniu instancji). W kontekście bramy prawda żyje w ALS:
|
|
32
|
+
// brama wyznacza stabilny `sessionKey` per klucz API; brak klucza = puste "" (semantyka legacy,
|
|
33
|
+
// zero roszczeń per-sesja). Losowy identyfikator per-proces zostaje TYLKO dla stdio.
|
|
34
|
+
const perRequest = requestEnv.getStore();
|
|
35
|
+
if (perRequest) return perRequest.sessionKey ?? "";
|
|
36
|
+
if (cachedSessionId) return cachedSessionId;
|
|
37
|
+
let host = "mcp";
|
|
38
|
+
try { host = (hostname() || "mcp").slice(0, 24); } catch { /* bez nazwy hosta też działa */ }
|
|
39
|
+
cachedSessionId = `${host}:${randomUUID()}`;
|
|
40
|
+
return cachedSessionId;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface SupabaseEnv {
|
|
44
|
+
url: string;
|
|
45
|
+
anonKey: string;
|
|
46
|
+
userJwt?: string;
|
|
47
|
+
/** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
|
|
48
|
+
sessionKey?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
|
|
53
|
+
*
|
|
54
|
+
* stdio runs one user per process, so credentials live in process.env. The
|
|
55
|
+
* hosted gateway serves MANY users from one process — sharing process.env would
|
|
56
|
+
* leak user A's JWT into user B's concurrent request. The gateway instead
|
|
57
|
+
* resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
|
|
58
|
+
* whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
|
|
59
|
+
* this store first and falls back to process.env, so stdio is unaffected.
|
|
60
|
+
*/
|
|
61
|
+
const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
|
|
62
|
+
|
|
63
|
+
/** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
|
|
64
|
+
export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
|
|
65
|
+
return requestEnv.run(env, fn);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class MissingSupabaseEnvError extends Error {
|
|
69
|
+
constructor(missing: string[]) {
|
|
70
|
+
super(
|
|
71
|
+
`Missing Supabase credentials: ${missing.join(", ")}. ` +
|
|
72
|
+
`Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
|
|
73
|
+
);
|
|
74
|
+
this.name = "MissingSupabaseEnvError";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function readSupabaseEnv(): SupabaseEnv {
|
|
79
|
+
// Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
|
|
80
|
+
// over any process-global env (multi-tenant safety). stdio has no store → falls
|
|
81
|
+
// through to the env/login resolution below.
|
|
82
|
+
const perRequest = requestEnv.getStore();
|
|
83
|
+
if (perRequest) return perRequest;
|
|
84
|
+
|
|
85
|
+
// Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
|
|
86
|
+
// honored (deprecated) so anyone who set them before the brand sweep keeps
|
|
87
|
+
// working. Env vars take precedence; fall back to the session saved by
|
|
88
|
+
// `mosadd login`.
|
|
89
|
+
const env = (canonical: string, legacy: string): string | undefined =>
|
|
90
|
+
process.env[canonical] ?? process.env[legacy];
|
|
91
|
+
const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
|
|
92
|
+
|
|
93
|
+
const session = loadSession();
|
|
94
|
+
const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
|
|
95
|
+
const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
|
|
96
|
+
const userJwt = userJwtEnv ?? session?.accessToken;
|
|
97
|
+
|
|
98
|
+
const missing: string[] = [];
|
|
99
|
+
if (!url) missing.push("MOSADD_SUPABASE_URL");
|
|
100
|
+
if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
|
|
101
|
+
if (missing.length) throw new MissingSupabaseEnvError(missing);
|
|
102
|
+
|
|
103
|
+
// Surface an expired `mosadd login` token early with an actionable message.
|
|
104
|
+
if (!userJwtEnv && session && isSessionExpired(session)) {
|
|
105
|
+
throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
|
|
106
|
+
}
|
|
107
|
+
return { url: url!, anonKey: anonKey!, userJwt };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
|
|
111
|
+
return createClient(env.url, env.anonKey, {
|
|
112
|
+
auth: {
|
|
113
|
+
persistSession: false,
|
|
114
|
+
autoRefreshToken: false,
|
|
115
|
+
detectSessionInUrl: false,
|
|
116
|
+
},
|
|
117
|
+
// ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
|
|
118
|
+
// rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
|
|
119
|
+
// kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
|
|
120
|
+
// hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
|
|
121
|
+
// post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
|
|
122
|
+
// wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
|
|
123
|
+
global: {
|
|
124
|
+
headers: {
|
|
125
|
+
...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
|
|
126
|
+
"x-mosadd-origin": "hub-gateway",
|
|
127
|
+
// Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
|
|
128
|
+
// więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
|
|
129
|
+
...(sessionId() ? { "x-mosadd-session": sessionId() } : {}),
|
|
130
|
+
// ⛔ KTÓRA TO SESJA (2026-08-27, „każdy generał co chwilę gubi mózg"). Wszyscy generałowie
|
|
131
|
+
// wpinają się kluczem hub TEGO SAMEGO właściciela, więc dla serwera ich wywołania były
|
|
132
|
+
// nieodróżnialne — a deklaracja linii (`comms_session_attach as_agent`) trzymała JEDEN
|
|
133
|
+
// wiersz na konto. Skutek: kto wpiął się ostatni, odbierał linię wszystkim pozostałym, a
|
|
134
|
+
// ich posty na kanałach zaczynały wracać z 403. Tożsamość sesji (stdio: per proces,
|
|
135
|
+
// brama: per klucz API) pozwala dziewięciu liniom na jednym koncie nie deptać sobie po piętach.
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
|
|
143
|
+
* normalized error handling so MCP tool handlers can throw clean errors that
|
|
144
|
+
* agents can reason about.
|
|
145
|
+
*/
|
|
146
|
+
export async function invokeFunction<T = unknown>(
|
|
147
|
+
fn: string,
|
|
148
|
+
body: Record<string, unknown>,
|
|
149
|
+
): Promise<T> {
|
|
150
|
+
const client = getSupabase();
|
|
151
|
+
const { data, error } = await client.functions.invoke<T>(fn, { body });
|
|
152
|
+
if (error) {
|
|
153
|
+
// supabase-js throws FunctionsHttpError for any non-2xx, whose `.message`
|
|
154
|
+
// is the FIXED generic string "Edge Function returned a non-2xx status
|
|
155
|
+
// code" — the *real* reason (e.g. {"error":"wrapped_group_key required"},
|
|
156
|
+
// "forbidden", an RLS denial) lives in `error.context`, a Response. Read it
|
|
157
|
+
// so the agent gets an actionable message (and the HTTP status) it can
|
|
158
|
+
// reason about and self-correct on, instead of the same opaque sentence
|
|
159
|
+
// for every failure across mDM/mIRC/mp0st/mRAG/prekey/message-list.
|
|
160
|
+
let msg =
|
|
161
|
+
error instanceof Error && error.message
|
|
162
|
+
? error.message
|
|
163
|
+
: `Edge function ${fn} failed`;
|
|
164
|
+
const ctx = (error as { context?: unknown }).context;
|
|
165
|
+
if (ctx && typeof (ctx as Response).text === "function") {
|
|
166
|
+
const res = ctx as Response;
|
|
167
|
+
try {
|
|
168
|
+
const raw = await res.text();
|
|
169
|
+
if (raw) {
|
|
170
|
+
let detail = raw;
|
|
171
|
+
let recipe = "";
|
|
172
|
+
try {
|
|
173
|
+
const parsed = JSON.parse(raw) as {
|
|
174
|
+
error?: unknown;
|
|
175
|
+
message?: unknown;
|
|
176
|
+
code?: unknown;
|
|
177
|
+
message_en?: unknown;
|
|
178
|
+
next_steps?: unknown;
|
|
179
|
+
};
|
|
180
|
+
detail =
|
|
181
|
+
(typeof parsed.error === "string" && parsed.error) ||
|
|
182
|
+
(typeof parsed.message === "string" && parsed.message) ||
|
|
183
|
+
raw;
|
|
184
|
+
// ⛔ The refusal CONTRACT (supabase/functions/_shared/errors.ts) travels as
|
|
185
|
+
// { code, message_en, message_pl, next_steps[] }. Until 2026-09-04 this block read
|
|
186
|
+
// `error` alone and threw the rest away — so the server said "here is exactly what to
|
|
187
|
+
// do next" and the agent received one flat sentence. The recipe is the whole point of
|
|
188
|
+
// the contract: it is written FOR a machine to act on. Measured on production the same
|
|
189
|
+
// day: mIRC_post_message with someone else's agent returned only
|
|
190
|
+
// "message-send (403): agent_not_owned" — code, both messages and 2 next_steps dropped.
|
|
191
|
+
// Rendered below as plain text because that is what an MCP tool error carries.
|
|
192
|
+
const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
|
|
193
|
+
const lines: string[] = [];
|
|
194
|
+
if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
|
|
195
|
+
if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
|
|
196
|
+
lines.push(parsed.message_en);
|
|
197
|
+
}
|
|
198
|
+
for (const raw_step of steps) {
|
|
199
|
+
const step = raw_step as { actor?: unknown; tool?: unknown; ui?: unknown; args?: unknown; why?: unknown };
|
|
200
|
+
const who = typeof step.actor === "string" ? step.actor : "?";
|
|
201
|
+
const what =
|
|
202
|
+
(typeof step.tool === "string" && step.tool) ||
|
|
203
|
+
(typeof step.ui === "string" && step.ui) ||
|
|
204
|
+
"";
|
|
205
|
+
if (!what) continue;
|
|
206
|
+
const why = typeof step.why === "string" ? ` — ${step.why}` : "";
|
|
207
|
+
const args =
|
|
208
|
+
step.args && typeof step.args === "object"
|
|
209
|
+
? ` ${JSON.stringify(step.args)}`
|
|
210
|
+
: "";
|
|
211
|
+
lines.push(`next (${who}): ${what}${args}${why}`);
|
|
212
|
+
}
|
|
213
|
+
if (lines.length) recipe = "\n" + lines.join("\n");
|
|
214
|
+
} catch {
|
|
215
|
+
// non-JSON body — use the raw text as-is
|
|
216
|
+
}
|
|
217
|
+
const status = typeof res.status === "number" ? res.status : undefined;
|
|
218
|
+
// First line stays byte-for-byte what callers have always matched on; the recipe follows.
|
|
219
|
+
msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
// body already consumed or unreadable — keep the generic message
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
throw new Error(msg);
|
|
226
|
+
}
|
|
227
|
+
if (data == null) {
|
|
228
|
+
throw new Error(`Edge function ${fn} returned no data`);
|
|
229
|
+
}
|
|
230
|
+
return data;
|
|
231
|
+
}
|