UNPKG

@ekwo-ai/mcp

Version:

MCP server for Ekwo OS: let an AI agent work on the books, under the user's own row level security.

202 lines • 9.29 kB
/** * The recommended backend: PostgREST, with the user's own session. * * Supabase already turns the schema into a REST API with an OpenAPI * description, and row level security decides what each request may see. So * this server holds no privileges of its own: it signs in as the person using * it — or is handed their access token — and everything it can do afterwards * is what that person can do. There is no service_role path here, on purpose. * A server that could read every company would turn "an AI keeps my books" * into "an AI holds the keys to everybody's books". * * `@supabase/supabase-js` does two things this package deliberately does not * hand-write: the password grant with its token refresh, and the query string * PostgREST expects. Both are the part that cannot be tested here — no test * talks to a Supabase project — and a library that is known to work is worth * more than code of ours that is merely untested. */ import { createClient } from '@supabase/supabase-js'; import { onSocle, socleMarkerAnswer, socleSchemaResolver, SOCLE_MARKER } from '@ekwo-ai/core'; import { EkwoMcpError, explain, identifier, } from './backend.js'; function applyFilters(builder, filters) { let out = builder; for (const filter of filters ?? []) { const column = identifier(filter.column); switch (filter.op) { case 'is': out = out.is(column, null); break; case 'in': out = out.in(column, filter.value); break; case 'ilike': out = out.ilike(column, filter.value); break; default: out = out[filter.op](column, filter.value); } } return out; } /** Unwraps a PostgREST answer, letting the schema's own message through. */ function unwrap(answer, what) { if (answer.error !== null) { const { message, details, hint } = answer.error; // `details` is where Postgres puts the rest of a raise; keep it. const full = [message, details, hint].filter((part) => typeof part === 'string' && part.length > 0).join(' — '); throw explain(full.length > 0 ? full : `${what} failed`); } if (answer.data === null) { throw new EkwoMcpError(`${what}: nothing came back`); } return answer.data; } /** The header the core's pre-request hook reads a key out of. */ export const API_KEY_HEADER = 'X-Ekwo-Api-Key'; /** The header that says a request is an agent's (`agent_call()`), and its session's choice. */ export const AGENT_HEADER = 'X-Ekwo-Agent'; /** The header that names the session of an agent, for the audit trail. */ export const AGENT_SESSION_HEADER = 'X-Ekwo-Agent-Session'; /** * A `fetch` that never sends `Authorization`. * * `supabase-js` puts the publishable key in `Authorization` when nothing else * is there. With a key of Ekwo OS on the request that is the one header that * must be absent, so it is taken off on the way out rather than trusted not to * be added. */ function withoutAuthorization(inner) { return (input, init) => { const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined)); headers.delete('authorization'); return inner(input, { ...init, headers }); }; } /** * Signs in, or takes the token it was given, and returns the backend. * * With an email and a password the client keeps the session in memory and * refreshes it on its own; nothing is written to disk, so a long-running * server outlives the first hour without a credential cache existing. */ export async function postgrestBackend(options) { const apiKey = options.apiKey !== undefined && options.apiKey.length > 0 ? options.apiKey : undefined; const headers = {}; if (apiKey !== undefined) { headers[API_KEY_HEADER] = apiKey; } else if (options.accessToken !== undefined && options.accessToken.length > 0) { headers['Authorization'] = `Bearer ${options.accessToken}`; } if (options.agent !== undefined) { headers[AGENT_HEADER] = options.agent.posting ?? 'on'; if (options.agent.id !== undefined) headers[AGENT_SESSION_HEADER] = options.agent.id; } const baseFetch = options.fetch ?? globalThis.fetch; const client = createClient(options.supabaseUrl, options.anonKey, { auth: { persistSession: false, autoRefreshToken: apiKey === undefined && options.accessToken === undefined, detectSessionInUrl: false, }, global: { headers, fetch: apiKey === undefined ? baseFetch : withoutAuthorization(baseFetch) }, }); let actingAs; if (apiKey !== undefined) { // A key is not a person: there is nobody to sign in and no user id to // report. What it may do is decided by the capabilities it carries, on // the one company it was issued for. actingAs = undefined; } else if (options.accessToken === undefined || options.accessToken.length === 0) { if (options.email === undefined || options.password === undefined) { throw new EkwoMcpError('no_credentials: set EKWO_EMAIL and EKWO_PASSWORD, or EKWO_ACCESS_TOKEN'); } const { data, error } = await client.auth.signInWithPassword({ email: options.email, password: options.password, }); if (error !== null) { throw new EkwoMcpError(`sign_in_failed: ${error.message}`); } actingAs = data.user?.id; } else { const { data } = await client.auth.getUser(options.accessToken); actingAs = data.user?.id; } /** * The client, pointed at one schema. * * PostgREST serves a schema other than `public` through the `Accept-Profile` * and `Content-Profile` headers, which `supabase-js` sets for you through * `.schema()`. It answers 406 for a schema the project does not expose, and * no migration can expose one — `ekwo module enable` prints the line to add. * The socle's schema is always named too (`onSocle()`, below), so a call * never rests on whichever schema the project happens to list first. */ const on = (schema) => schema === undefined ? client : client.schema(identifier(schema)); const backend = { mode: 'postgrest', actingAs, agent: options.agent, async rpc(fn, args = {}, schema) { const answer = (await on(schema).rpc(identifier(fn), args)); const data = unwrap(answer, fn); // A function returning one composite row comes back as an object, a // set-returning one as an array. Tools see an array either way. return (Array.isArray(data) ? data : [data]); }, async rpcVoid(fn, args = {}, schema) { const answer = (await on(schema).rpc(identifier(fn), args)); if (answer.error !== null) { throw explain(answer.error.message); } }, async select(query) { let builder = on(query.schema).from(identifier(query.table)).select(query.columns.join(',')); builder = applyFilters(builder, query.where); for (const order of query.order ?? []) { builder = builder.order(identifier(order.column), { ascending: order.ascending !== false }); } if (query.limit !== undefined) builder = builder.limit(query.limit); return unwrap((await builder), `select from ${query.table}`); }, async insert(table, rows, returning = ['*'], schema) { const answer = (await on(schema) .from(identifier(table)) .insert(rows) .select(returning.join(','))); return unwrap(answer, `insert into ${table}`); }, async update(table, patch, where, returning = ['*'], schema) { let builder = on(schema).from(identifier(table)).update(patch); builder = applyFilters(builder, where); const answer = (await builder.select(returning.join(','))); return unwrap(answer, `update ${table}`); }, async remove(table, where, schema) { let builder = on(schema).from(identifier(table)).delete(); builder = applyFilters(builder, where); const answer = (await builder); if (answer.error !== null) throw explain(answer.error.message); }, async close() { // Stops the refresh timer; there is no socket to give back. await client.auth.stopAutoRefresh(); }, }; return onSocle(backend, socleSchemaResolver((schema) => socleMarkerOver(on(schema)))); } /** Whether the socle's marker answers in the schema this client is pointed at. */ async function socleMarkerOver(client) { const answer = (await client.rpc(SOCLE_MARKER)); const found = socleMarkerAnswer({ ok: answer.error === null, status: answer.status, code: answer.error?.code }); if (found === undefined) throw explain(answer.error?.message ?? `${SOCLE_MARKER} failed`); return found; } //# sourceMappingURL=postgrest.js.map