UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

682 lines (680 loc) • 24.2 kB
import { assert } from "./assertions.js"; import { logger } from "./logger.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 { isTool } from "./tool.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"; /** The scope that lets a caller run an action that is not a read. */ const WRITE_SCOPE = "mcp:write"; /** * What the platform grants. Advertised here so a client asks for the same. A * client that names none is the platform's to decide, so it is passed on as is. */ const SCOPES = ["mcp:read", WRITE_SCOPE]; 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 } from './actions' * import { createIssue } from './mcp-tools' * * export const startInstance = createStart(() => ({ * requestMiddleware: [ * softrMcpMiddleware({ actions: [publishedPosts], tools: [createIssue] }), * softrAuthMiddleware(), * ], * })) */ function softrMcpMiddleware(options = {}) { const login = softrConfig().auth.routes.login; const entries = /* @__PURE__ */ new Map(); for (const action of options.actions ?? []) { assert(isDatasourceAction(action), "softrMcpMiddleware takes actions built by defineQuery or defineMutation"); const value = action; assert(!entries.has(value.id), `two actions share the id "${value.id}"`); entries.set(value.id, { kind: "action", value }); } for (const tool of options.tools ?? []) { assert(isTool(tool), "softrMcpMiddleware takes tools built by defineTool"); const value = tool; assert(value.name !== WHOAMI.name && !entries.has(value.name), `two tools share the name "${value.name}"`); entries.set(value.name, { kind: "tool", 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, entries); 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, query.data)); 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 params = 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 ?? "" }); if (query.scope !== void 0) params.set("scope", query.scope); const response = await platformFetch(`/v1/oauth/authorize?${params}`, { 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, 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(), scope: z.string().nullish() }).safeParse(await response.json().catch(() => null)); if (!parsed.success) return { ok: false, refused: false }; const scopes = parsed.data.scope?.split(" ") ?? []; return { ok: true, sessionToken: parsed.data.sessionJwt, canWrite: scopes.includes(WRITE_SCOPE) }; } const WHOAMI = { name: "whoami", title: "Who am I", description: "Returns the Softr user this connection is authenticated as: their name, email and user groups. Use it to confirm which account the app sees.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } }; /** How many records a read returns when the caller does not say. */ const DEFAULT_LIMIT = 20; const MAX_LIMIT = 100; /** Whether the tool only reads. A read-only grant may run only these. */ function isReadOnly(entry) { if (entry.kind === "action") return entry.value.resource.operation === "read"; return entry.value.readOnly; } /** * 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, annotations: { readOnlyHint: true }, 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", "string"], minimum: 0, description: "Where the page starts. Use nextOffset from a previous call, unchanged: a number is a row position, a string is the datasource's own cursor." } }, additionalProperties: false } }; case "create": return { name: action.id, annotations: { readOnlyHint: false, destructiveHint: false }, description: `Create a record with "${action.id}". Writable fields: ${names.join(", ")}.`, inputSchema: { type: "object", properties: fieldProps, additionalProperties: false } }; case "update": return { name: action.id, annotations: { readOnlyHint: false, destructiveHint: true }, 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, annotations: { readOnlyHint: false, destructiveHint: true }, 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 === "string" && raw !== "") return raw; if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) return null; return raw; } async function rpc(request, origin, entries) { 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, canWrite } = session; const allowed = (entry) => canWrite || isReadOnly(entry); 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, ...[...entries.values()].filter(allowed).map((entry) => { if (entry.kind === "action") return describeTool(entry.value); const { name, title, description, inputSchema, readOnly, destructive } = entry.value; return { name, ...title === void 0 ? {} : { title }, description, inputSchema, annotations: readOnly ? { readOnlyHint: true } : { readOnlyHint: false, ...destructive === void 0 ? {} : { destructiveHint: destructive } } }; })] }); case "tools/call": { const name = params?.name; const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {}; if (name === WHOAMI.name) { const { applicationId } = sessionConfig(); const session$1 = await makePlatform(applicationId).sessionWithGroupNames(sessionToken); if (!session$1.ok && session$1.status !== 401 && session$1.status !== 403) return unavailable(); const user = session$1.ok ? session$1.data.user : null; if (user === null) return unauthorized(origin); return result(id, toolResult(user)); } const entry = typeof name === "string" ? entries.get(name) : void 0; if (entry === void 0) return failure(id, -32602, `Unknown tool: ${String(name)}`); if (!allowed(entry)) return result(id, { isError: true, content: [{ type: "text", text: `"${name}" changes data, and this assistant's connection allows reading only, so it cannot run it.` }] }); try { let run; let user; if (entry.kind === "action") run = () => runTool(entry.value, args); else { const input = await entry.value.input.safeParseAsync(args); if (!input.success) return result(id, { isError: true, content: [{ type: "text", text: ["The arguments are not valid:", ...input.error.issues.map((issue) => { const path = issue.path.join("."); return path === "" ? `- ${issue.message}` : `- ${path}: ${issue.message}`; })].join("\n") }] }); const { applicationId } = sessionConfig(); const lookup = await makePlatform(applicationId).session(sessionToken); if (!lookup.ok && lookup.status !== 401 && lookup.status !== 403) return unavailable(); const found = lookup.ok ? lookup.data.user : null; if (found === null) return unauthorized(origin); user = found; run = () => entry.value.handler(input.data, { user: found }); } return result(id, toolResult(await withSessionToken(sessionToken, run, { readOnly: isReadOnly(entry), user }))); } catch (error) { if (entry.kind === "tool") console.error(`[@softr/sdk] MCP tool "${entry.value.name}" failed:`, error); else logger.error("MCP tool failed", 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) { const content = [{ type: "text", text: output === void 0 ? "Done." : JSON.stringify(output, null, 2) }]; if (typeof output === "object" && output !== null && !Array.isArray(output)) return { content, structuredContent: output }; return { content }; } 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, query) { const clientHost = query.client_id.startsWith("https://") ? `Client registered at ${escapeHtml(new URL(query.client_id).host)}. ` : ""; const redirectHost = `It will send you back to ${escapeHtml(new URL(query.redirect_uri).host)}.`; 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.<br><small>${clientHost}${redirectHost}</small>`, `<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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;"); } //#endregion export { softrMcpMiddleware };