@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
581 lines (579 loc) • 20.3 kB
JavaScript
import { assert } from "./assertions.js";
import { softrApiUrl } from "./softr-api.js";
import { fetch } from "./fetch.js";
import { softrConfig } from "./softr-config.js";
import { sessionConfig } from "./auth/config.js";
import { makePlatform } from "./auth/platform.js";
import { readSessionToken, withSessionToken } from "./auth/session.js";
import { isDatasourceAction } from "./action.js";
import { ds } from "./datasource/datasource.js";
import { z } from "zod";
import { createMiddleware } from "@tanstack/react-start";
//#region src/mcp.ts
const MCP_PATH = "/_softr/mcp";
const AUTHORIZE_PATH = "/_softr/oauth/authorize";
const TOKEN_PATH = "/_softr/oauth/token";
const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
const AUTHORIZATION_SERVER_PATH = "/.well-known/oauth-authorization-server";
/** What the platform grants. Advertised here so a client asks for the same. */
const SCOPES = ["mcp:read", "mcp:write"];
/** What a client that named no scope gets. Matches the platform's own default. */
const DEFAULT_SCOPE = "mcp:read";
const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"];
/**
* Serves the MCP endpoint and its OAuth flow from the app's own origin.
*
* Register it in the app's `src/start.ts`, ahead of `softrAuthMiddleware`: it
* answers its own paths and resolves the caller from the bearer token, so it
* must not sit behind the session lookup that middleware does on every
* request. Everything else passes straight through.
*
* @example
* import { publishedPosts, addCafe } from './actions'
*
* export const startInstance = createStart(() => ({
* requestMiddleware: [
* softrMcpMiddleware({ actions: [publishedPosts, addCafe] }),
* softrAuthMiddleware(),
* ],
* }))
*/
function softrMcpMiddleware(options = {}) {
const login = softrConfig().auth.routes.login;
const actions = /* @__PURE__ */ new Map();
for (const action of options.actions ?? []) {
assert(isDatasourceAction(action), "softrMcpMiddleware takes actions built by defineQuery or defineMutation");
const value = action;
assert(!actions.has(value.id), `two actions share the id "${value.id}"`);
actions.set(value.id, value);
}
return createMiddleware({ type: "request" }).server(async ({ next, request }) => {
const url = new URL(request.url);
const origin = url.origin;
switch (url.pathname) {
case PROTECTED_RESOURCE_PATH: return json({
resource: `${origin}${MCP_PATH}`,
authorization_servers: [origin],
bearer_methods_supported: ["header"],
scopes_supported: SCOPES
});
case AUTHORIZATION_SERVER_PATH: return json({
issuer: origin,
authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
token_endpoint: `${origin}${TOKEN_PATH}`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none", "client_secret_basic"],
client_id_metadata_document_supported: true,
scopes_supported: SCOPES
});
case AUTHORIZE_PATH: return await authorize(request, login);
case TOKEN_PATH: return await issueToken(request);
case MCP_PATH: return await rpc(request, origin, actions);
default: return await next();
}
});
}
const authorizeQuerySchema = z.object({
client_id: z.string().min(1),
redirect_uri: z.string().url(),
response_type: z.literal("code"),
code_challenge: z.string().min(1),
code_challenge_method: z.literal("S256"),
state: z.string().optional(),
scope: z.string().optional(),
resource: z.string().optional()
});
/**
* The Allow page, and the approval itself.
*
* We know who the visitor is from the app's session cookie — readable only
* because this runs on the app's origin. The client and the code are the
* platform's, so we ask it for both.
*/
async function authorize(request, login) {
const url = new URL(request.url);
const query = authorizeQuerySchema.safeParse(Object.fromEntries(url.searchParams));
if (!query.success) return html(400, page("This request is not valid", "The app that sent you here left something out. Close this window and try connecting again."));
if (request.method !== "GET" && request.method !== "POST") return methodNotAllowed("GET, POST");
const sessionToken = readSessionToken();
const user = sessionToken === null ? null : await resolveUser(sessionToken);
if (user === null || sessionToken === null) return html(200, signInPage(url, login));
const client = await platformConsent(query.data);
if (!client.ok) return html(400, page("We can't connect this right now", escapeHtml(client.message)));
if (request.method === "GET") return html(200, consentPage(user, url, client.name));
const form = await request.formData();
const decision = await platformApprove(sessionToken, query.data, form.get("decision") === "allow");
if (!decision.ok) return html(502, page("We could not finish this", decision.message));
return redirect(decision.redirectUri);
}
/**
* Passes the token request straight through. The code and refresh token are the
* platform's, so only it can redeem them. The client's credentials ride along
* in the Authorization header untouched.
*/
async function issueToken(request) {
if (request.method !== "POST") return methodNotAllowed("POST");
const authorization = request.headers.get("authorization");
const response = await platformFetch("/v1/oauth/token", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
...authorization === null ? {} : { authorization }
},
body: await request.text()
});
return new Response(await response.text(), {
status: response.status,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*",
"cache-control": "no-store"
}
});
}
/**
* Tells the platform which app this is about. It normally works that out from
* the domain, and none of the calls below arrive on the app's domain.
*/
const APPLICATION_ID_HEADER = "Softr-Application-ID";
/**
* An unreachable platform comes back as a 503, not a thrown error, so callers
* can handle it with the `response.ok` check they already do. If it threw, the
* MCP endpoint would answer 500 where the client needs a refusal it can act on.
*/
async function platformFetch(path, init) {
const { applicationId } = sessionConfig();
try {
return await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}${path}`, {
method: init.method,
headers: {
accept: "application/json",
[APPLICATION_ID_HEADER]: applicationId,
...init.headers
},
body: init.body
});
} catch {
return json({ message: "Softr could not be reached. Try again in a moment." }, 503);
}
}
/** The name to show on the Allow page, or why there's nothing to approve. */
async function platformConsent(query) {
const response = await platformFetch(`/v1/oauth/authorize?${new URLSearchParams({
client_id: query.client_id,
redirect_uri: query.redirect_uri,
response_type: query.response_type,
code_challenge: query.code_challenge,
code_challenge_method: query.code_challenge_method,
state: query.state ?? "",
scope: query.scope ?? DEFAULT_SCOPE
})}`, { method: "GET" });
const body = await response.json().catch(() => null);
if (!response.ok) {
const refusal = z.object({ message: z.string() }).safeParse(body);
return {
ok: false,
message: refusal.success ? refusal.data.message : "The assistant asking for access is not set up for this app."
};
}
const parsed = z.object({ client_name: z.string().nullish() }).safeParse(body);
return {
ok: true,
name: parsed.success && parsed.data.client_name ? parsed.data.client_name : "An AI assistant"
};
}
/**
* Records the answer and returns where to send the browser next — with a code
* if they allowed it, an error if they didn't. The session token goes in the
* header. The platform reads a cookie from its own consent page, but this
* isn't that page.
*/
async function platformApprove(sessionToken, query, approved) {
const response = await platformFetch("/v1/oauth/authorize", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${sessionToken}`
},
body: JSON.stringify({
client_id: query.client_id,
redirect_uri: query.redirect_uri,
state: query.state ?? "",
code_challenge: query.code_challenge,
code_challenge_method: query.code_challenge_method,
scope: query.scope ?? DEFAULT_SCOPE,
approved
})
});
const parsed = z.object({ redirect_uri: z.string().url() }).safeParse(await response.json().catch(() => null));
if (!response.ok || !parsed.success) return {
ok: false,
message: "The app could not record your answer. Close this window and try connecting again."
};
return {
ok: true,
redirectUri: parsed.data.redirect_uri
};
}
async function platformSession(accessToken) {
const response = await platformFetch("/v1/mcp/session", {
method: "POST",
headers: { authorization: `Bearer ${accessToken}` }
});
if (!response.ok) return {
ok: false,
refused: response.status === 401 || response.status === 403
};
const parsed = z.object({ sessionJwt: z.string() }).safeParse(await response.json().catch(() => null));
return parsed.success ? {
ok: true,
sessionToken: parsed.data.sessionJwt
} : {
ok: false,
refused: false
};
}
const WHOAMI = {
name: "whoami",
title: "Who am I",
description: "Returns the Softr user this connection is authenticated as: their name, email and user group ids. Use it to confirm which account the app sees.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false
}
};
/** How many records a read returns when the caller does not say. */
const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;
/**
* One tool per action the app chose to expose.
*
* The app passes its actions in rather than the SDK discovering them, so that
* being reachable over MCP is something an app opts into per action. An app
* that only ever reads one datasource exposes one read, even though its
* credentials would allow more.
*/
function describeTool(action) {
const { operation, fields } = action.resource;
const names = Object.keys(fields ?? {});
const fieldProps = Object.fromEntries(names.map((name) => [name, { description: `The "${name}" field.` }]));
switch (operation) {
case "read": return {
name: action.id,
description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
inputSchema: {
type: "object",
properties: {
limit: {
type: "integer",
minimum: 1,
maximum: MAX_LIMIT,
description: `How many records to return. Defaults to ${DEFAULT_LIMIT}.`
},
offset: {
type: "integer",
minimum: 0,
description: "Where the page starts. Use nextOffset from a previous call."
}
},
additionalProperties: false
}
};
case "create": return {
name: action.id,
description: `Create a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
inputSchema: {
type: "object",
properties: fieldProps,
additionalProperties: false
}
};
case "update": return {
name: action.id,
description: `Update a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
inputSchema: {
type: "object",
properties: {
id: {
type: "string",
description: "The id of the record to update."
},
...fieldProps
},
required: ["id"],
additionalProperties: false
}
};
case "delete": return {
name: action.id,
description: `Delete a record with "${action.id}".`,
inputSchema: {
type: "object",
properties: { id: {
type: "string",
description: "The id of the record to delete."
} },
required: ["id"],
additionalProperties: false
}
};
}
}
/**
* Runs one action as the visitor the access token belongs to.
*
* Every call goes through `ds`, so the platform authorizes it against that
* visitor's user groups exactly as it would a click in the app. Nothing here
* decides what is allowed.
*/
async function runTool(action, args) {
const typed = action;
switch (action.resource.operation) {
case "read": {
const limit = clampLimit(args.limit);
const offset = clampOffset(args.offset);
const result$1 = await ds.list(typed).limit(limit).offset(offset);
return {
records: result$1.records,
nextOffset: result$1.nextOffset
};
}
case "create": return await ds.create(typed, { data: writableFields(action, args) });
case "update": {
const { id,...data } = args;
assert(typeof id === "string" && id !== "", "update needs a record id");
return await ds.update(typed, {
id,
data: writableFields(action, data)
});
}
case "delete": {
const { id } = args;
assert(typeof id === "string" && id !== "", "delete needs a record id");
await ds.delete(typed, { id });
return { deleted: id };
}
}
}
/**
* Only the fields the action declared.
*
* `additionalProperties: false` in the tool schema is a hint to the model, not
* a check — a client can send whatever it likes. An unlisted key reaches the
* datasource as a raw field id, because `dealiasData` passes an unknown alias
* straight through. So the action's field list gets enforced here, or it isn't
* a boundary at all.
*/
function writableFields(action, args) {
const allowed = action.resource.fields ?? {};
return Object.fromEntries(Object.entries(args).filter(([name]) => name in allowed));
}
function clampLimit(raw) {
if (typeof raw !== "number" || !Number.isInteger(raw)) return DEFAULT_LIMIT;
return Math.min(Math.max(raw, 1), MAX_LIMIT);
}
function clampOffset(raw) {
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) return null;
return raw;
}
async function rpc(request, origin, actions) {
if (request.method !== "POST") return methodNotAllowed("POST");
const token = bearerToken(request);
if (token === null) return unauthorized(origin);
const session = await platformSession(token);
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
const { sessionToken } = session;
const body = await readJson(request);
const message = z.object({
id: z.union([z.string(), z.number()]).optional(),
method: z.string(),
params: z.record(z.string(), z.unknown()).optional()
}).safeParse(body);
if (!message.success) return json({
jsonrpc: "2.0",
id: null,
error: {
code: -32700,
message: "Parse error"
}
});
const { id, method, params } = message.data;
if (id === void 0) return new Response(null, { status: 202 });
switch (method) {
case "initialize": {
const requested = params?.protocolVersion;
return result(id, {
protocolVersion: typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0],
capabilities: { tools: { listChanged: false } },
serverInfo: {
name: "softr-app",
version: "0.1.0"
}
});
}
case "tools/list": return result(id, { tools: [WHOAMI, ...[...actions.values()].map(describeTool)] });
case "tools/call": {
const name = params?.name;
const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {};
if (name === WHOAMI.name) {
const user = await resolveUser(sessionToken);
if (user === null) return unauthorized(origin);
return result(id, toolResult(user));
}
const action = typeof name === "string" ? actions.get(name) : void 0;
if (action === void 0) return failure(id, -32602, `Unknown tool: ${String(name)}`);
try {
return result(id, toolResult(await withSessionToken(sessionToken, () => runTool(action, args))));
} catch (error) {
return result(id, {
isError: true,
content: [{
type: "text",
text: error instanceof Error ? error.message : String(error)
}]
});
}
}
default: return failure(id, -32601, `Method not found: ${method}`);
}
}
function toolResult(output) {
return {
content: [{
type: "text",
text: JSON.stringify(output, null, 2)
}],
structuredContent: output
};
}
function result(id, payload) {
return json({
jsonrpc: "2.0",
id,
result: payload
});
}
function failure(id, code, message) {
return json({
jsonrpc: "2.0",
id,
error: {
code,
message
}
});
}
function unauthorized(origin) {
return new Response(JSON.stringify({ error: "invalid_token" }), {
status: 401,
headers: {
"content-type": "application/json",
"www-authenticate": `Bearer resource_metadata="${origin}${PROTECTED_RESOURCE_PATH}", scope="${SCOPES.join(" ")}"`
}
});
}
/** The platform is down, not the token. 503 so the client retries rather than
* throwing its token away. */
function unavailable() {
return json({ error: "temporarily_unavailable" }, 503);
}
function bearerToken(request) {
const header = request.headers.get("authorization");
if (header === null) return null;
const [scheme, value] = header.split(" ");
return scheme?.toLowerCase() === "bearer" && value ? value : null;
}
/**
* The visitor a session token belongs to, or `null` when the platform refuses
* it — expired, revoked, or issued for another application.
*/
async function resolveUser(sessionToken) {
const { applicationId } = sessionConfig();
const result$1 = await makePlatform(applicationId).session(sessionToken);
return result$1.ok ? result$1.data.user : null;
}
async function readJson(request) {
try {
return await request.json();
} catch {
return null;
}
}
function json(payload, status = 200) {
return new Response(JSON.stringify(payload), {
status,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*",
"cache-control": "no-store"
}
});
}
function methodNotAllowed(allowed) {
return new Response(null, {
status: 405,
headers: { allow: allowed }
});
}
function redirect(location) {
return new Response(null, {
status: 302,
headers: { location }
});
}
function html(status, body) {
return new Response(body, {
status,
headers: {
"content-type": "text/html; charset=utf-8",
"cache-control": "no-store"
}
});
}
function consentPage(user, url, clientName) {
return page("Connect to this app?", `<strong>${escapeHtml(clientName)}</strong> is asking to use this app as <strong>${escapeHtml(user.fullName || user.email)}</strong>. It will see only what you can see.`, `<form method="post" action="${escapeHtml(url.pathname + url.search)}">
<button type="submit" name="decision" value="allow" class="primary">Allow</button>
<button type="submit" name="decision" value="deny">Cancel</button>
</form>`);
}
function signInPage(url, login) {
const back = new URLSearchParams({ [login.redirectParam]: url.pathname + url.search });
return page("Sign in first", "You need to be signed in to this app before you can connect an assistant to it.", `<a class="primary" href="${escapeHtml(`${login.path}?${back}`)}">Sign in</a>`);
}
function page(title, body, actions = "") {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>
:root { color-scheme: light dark; }
body {
margin: 0; min-height: 100vh; display: grid; place-items: center;
font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
background: Canvas; color: CanvasText; padding: 24px;
}
main { max-width: 26rem; }
h1 { font-size: 1.35rem; margin: 0 0 .6rem; }
p { margin: 0 0 1.5rem; opacity: .8; }
form { display: flex; gap: .6rem; flex-wrap: wrap; }
button, a.primary {
font: inherit; padding: .55rem 1.1rem; border-radius: .4rem; cursor: pointer;
border: 1px solid currentColor; background: transparent; color: inherit;
text-decoration: none; display: inline-block;
}
.primary { background: CanvasText; color: Canvas; border-color: CanvasText; }
</style>
</head>
<body><main><h1>${escapeHtml(title)}</h1><p>${body}</p>${actions}</main></body>
</html>`;
}
function escapeHtml(value) {
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
}
//#endregion
export { softrMcpMiddleware };