@softr/sdk 0.0.43 → 0.0.45-alpha.0
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/auth/session.js +15 -1
- package/dist/boot-error.js +42 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/mcp.d.ts +36 -0
- package/dist/mcp.js +581 -0
- package/dist/package.js +1 -1
- package/dist/server.js +1 -1
- package/package.json +33 -10
- package/skills/softr-sdk/SKILL.md +6 -2
- package/skills/softr-sdk/mcp/SKILL.md +74 -0
package/dist/auth/session.js
CHANGED
|
@@ -3,6 +3,7 @@ import { permissionsSchema } from "./permissions.js";
|
|
|
3
3
|
import { sessionConfig } from "./config.js";
|
|
4
4
|
import { userSchema } from "./user.js";
|
|
5
5
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
7
|
import { getRequestProtocol } from "@tanstack/react-start/server";
|
|
7
8
|
import { z } from "zod";
|
|
8
9
|
|
|
@@ -35,8 +36,20 @@ function sessionCookie(base) {
|
|
|
35
36
|
secure
|
|
36
37
|
};
|
|
37
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Runs `fn` with `token` standing in for the request's session cookie, so that
|
|
41
|
+
* every datasource call inside it acts as that visitor.
|
|
42
|
+
*
|
|
43
|
+
* For requests that carry who they are somewhere other than the cookie: an MCP
|
|
44
|
+
* call authenticates with a bearer token and has no cookie at all.
|
|
45
|
+
*/
|
|
46
|
+
function withSessionToken(token, fn) {
|
|
47
|
+
return standInToken.run(token, fn);
|
|
48
|
+
}
|
|
38
49
|
/** The platform token this request carries, or `null`. */
|
|
39
50
|
function readSessionToken() {
|
|
51
|
+
const standIn = standInToken.getStore();
|
|
52
|
+
if (standIn !== void 0) return standIn;
|
|
40
53
|
const { name } = sessionCookie(SESSION_TOKEN);
|
|
41
54
|
return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
|
|
42
55
|
}
|
|
@@ -105,6 +118,7 @@ function clearSession() {
|
|
|
105
118
|
PENDING_AUTH
|
|
106
119
|
]);
|
|
107
120
|
}
|
|
121
|
+
const standInToken = new AsyncLocalStorage();
|
|
108
122
|
const sessionDataSchema = z.object({
|
|
109
123
|
user: userSchema.nullable(),
|
|
110
124
|
permissions: permissionsSchema,
|
|
@@ -196,4 +210,4 @@ function openEnvelope(raw, purpose) {
|
|
|
196
210
|
}
|
|
197
211
|
|
|
198
212
|
//#endregion
|
|
199
|
-
export { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken };
|
|
213
|
+
export { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
|
package/dist/boot-error.js
CHANGED
|
@@ -23,6 +23,17 @@ function bootErrorMiddleware() {
|
|
|
23
23
|
}
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Faults of the dev server rather than the app: a module graph swapped under a render already in
|
|
28
|
+
* flight, so React's dispatcher or a split chunk belongs to a generation that is gone. The next
|
|
29
|
+
* request reads the settled graph and succeeds, which is why these clear on their own — and why
|
|
30
|
+
* showing one is worse than useless. The page invites the reader to copy it to the agent, and an
|
|
31
|
+
* agent handed a phantom spends a repair round looking for it in code that is correct.
|
|
32
|
+
*/
|
|
33
|
+
const TRANSIENT = [/Cannot read properties of (?:null|undefined) \(reading 'use[A-Z]/, /Failed to fetch dynamically imported module/];
|
|
34
|
+
function isTransientBootError(message) {
|
|
35
|
+
return TRANSIENT.some((pattern) => pattern.test(message));
|
|
36
|
+
}
|
|
26
37
|
function errorPage(error) {
|
|
27
38
|
if (process.env.NODE_ENV === "production") return page("Something went wrong", "This page couldn’t be shown. Try again in a moment, and if it keeps happening, reach out to the owner of this app.", { note: "If you are the owner, you can check what happened in Studio." });
|
|
28
39
|
const cause = error instanceof Error ? error.cause : void 0;
|
|
@@ -31,6 +42,7 @@ function errorPage(error) {
|
|
|
31
42
|
const stack = root instanceof Error ? root.stack : void 0;
|
|
32
43
|
return page("This app crashed", "The app stopped before it could start. The technical details below show where it failed and can be copied to the agent to help fix the issue.", {
|
|
33
44
|
note: "These details are only shown because the app is running in development mode.",
|
|
45
|
+
autoRetry: isTransientBootError(message),
|
|
34
46
|
detail: `<pre class="message">${escapeHtml(message)}</pre>`,
|
|
35
47
|
actions: stack ? `<button type="button" id="toggle" aria-expanded="true" aria-controls="panel">
|
|
36
48
|
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
|
|
@@ -71,7 +83,7 @@ function errorPage(error) {
|
|
|
71
83
|
<\/script>` : ""
|
|
72
84
|
});
|
|
73
85
|
}
|
|
74
|
-
function page(title, description, { note = "", detail = "", actions = "", panel = "" } = {}) {
|
|
86
|
+
function page(title, description, { note = "", detail = "", actions = "", panel = "", autoRetry = false } = {}) {
|
|
75
87
|
return `<!doctype html>
|
|
76
88
|
<html lang="en">
|
|
77
89
|
<head>
|
|
@@ -222,7 +234,7 @@ function page(title, description, { note = "", detail = "", actions = "", panel
|
|
|
222
234
|
</style>
|
|
223
235
|
</head>
|
|
224
236
|
<body>
|
|
225
|
-
<main>
|
|
237
|
+
<main${autoRetry ? " hidden" : ""}>
|
|
226
238
|
<div class="alert">
|
|
227
239
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
|
|
228
240
|
</div>
|
|
@@ -241,9 +253,37 @@ function page(title, description, { note = "", detail = "", actions = "", panel
|
|
|
241
253
|
</div>
|
|
242
254
|
${panel}
|
|
243
255
|
</main>
|
|
256
|
+
${autoRetry ? RETRY_SCRIPT : ""}
|
|
244
257
|
</body>
|
|
245
258
|
</html>`;
|
|
246
259
|
}
|
|
260
|
+
/**
|
|
261
|
+
* One reload, then the page reveals itself. The reload is what the reader would have done by hand,
|
|
262
|
+
* so a fault that clears is never seen; a fault that survives it shows the same page it always did.
|
|
263
|
+
* Session storage is what remembers the attempt, and a preview frame may refuse it — then there is
|
|
264
|
+
* no way to count, and the honest move is to show the error rather than risk reloading forever.
|
|
265
|
+
*/
|
|
266
|
+
const RETRY_SCRIPT = `<noscript><style>main[hidden] { display: flex !important }</style></noscript>
|
|
267
|
+
<script>
|
|
268
|
+
(() => {
|
|
269
|
+
const KEY = 'softr:boot-retry'
|
|
270
|
+
const reveal = () => { document.querySelector('main').hidden = false }
|
|
271
|
+
|
|
272
|
+
let store = null
|
|
273
|
+
try { store = sessionStorage } catch { /* blocked in this frame */ }
|
|
274
|
+
if (!store) return reveal()
|
|
275
|
+
|
|
276
|
+
const now = Date.now()
|
|
277
|
+
if (now - Number(store.getItem(KEY) ?? 0) < 15000) {
|
|
278
|
+
store.removeItem(KEY)
|
|
279
|
+
return reveal()
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
store.setItem(KEY, String(now))
|
|
283
|
+
// A beat, so the reload lands after the dev server has finished rebuilding rather than during.
|
|
284
|
+
setTimeout(() => location.reload(), 500)
|
|
285
|
+
})()
|
|
286
|
+
<\/script>`;
|
|
247
287
|
function escapeHtml(value) {
|
|
248
288
|
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
249
289
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { FileItem, useFileUpload } from "./core/use-file-upload.js";
|
|
|
5
5
|
import { SoftrContext } from "./auth/context.js";
|
|
6
6
|
import { defineVisibility, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./routes/visibility.js";
|
|
7
7
|
import { getSoftrContext, initialSoftrContext, softrAuthMiddleware, useCurrentUser, usePermissions } from "./auth/isomorphic.js";
|
|
8
|
+
import { softrMcpMiddleware } from "./mcp.js";
|
|
8
9
|
import { useUserTimezone } from "./timezone.js";
|
|
9
10
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
10
|
-
export { type ActionPermissions, DefaultErrorOverlay, type FileAttachment, type FileItem, type SoftrContext, type SoftrDatasources, type SoftrUserGroupId, type SoftrUserGroups, type User, defineIntegration, defineMutation, defineQuery, defineVisibility, defineWorkflow, getSoftrContext, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError, softrAuthMiddleware, useCurrentUser, useFileUpload, usePermissions, useUserTimezone };
|
|
11
|
+
export { type ActionPermissions, DefaultErrorOverlay, type FileAttachment, type FileItem, type SoftrContext, type SoftrDatasources, type SoftrUserGroupId, type SoftrUserGroups, type User, defineIntegration, defineMutation, defineQuery, defineVisibility, defineWorkflow, getSoftrContext, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError, softrAuthMiddleware, softrMcpMiddleware, useCurrentUser, useFileUpload, usePermissions, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,8 @@ import { useFileUpload } from "./core/use-file-upload.js";
|
|
|
2
2
|
import { defineIntegration, defineMutation, defineQuery, defineWorkflow } from "./action.js";
|
|
3
3
|
import { defineVisibility, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./routes/visibility.js";
|
|
4
4
|
import { getSoftrContext, initialSoftrContext, softrAuthMiddleware, useCurrentUser, usePermissions } from "./auth/isomorphic.js";
|
|
5
|
+
import { softrMcpMiddleware } from "./mcp.js";
|
|
5
6
|
import { useUserTimezone } from "./timezone.js";
|
|
6
7
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
7
8
|
|
|
8
|
-
export { DefaultErrorOverlay, defineIntegration, defineMutation, defineQuery, defineVisibility, defineWorkflow, getSoftrContext, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError, softrAuthMiddleware, useCurrentUser, useFileUpload, usePermissions, useUserTimezone };
|
|
9
|
+
export { DefaultErrorOverlay, defineIntegration, defineMutation, defineQuery, defineVisibility, defineWorkflow, getSoftrContext, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError, softrAuthMiddleware, softrMcpMiddleware, useCurrentUser, useFileUpload, usePermissions, useUserTimezone };
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { DatasourceAction } from "./action.js";
|
|
2
|
+
import * as _tanstack_react_start2 from "@tanstack/react-start";
|
|
3
|
+
|
|
4
|
+
//#region src/mcp.d.ts
|
|
5
|
+
|
|
6
|
+
type SoftrMcpOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* The actions to expose as tools, from `defineQuery` and `defineMutation`.
|
|
9
|
+
*
|
|
10
|
+
* Listing them is deliberate: an action left out is invisible over MCP, even
|
|
11
|
+
* though the app's own pages may use it. The action's own `permissions` still
|
|
12
|
+
* decide who may run the ones that are listed.
|
|
13
|
+
*/
|
|
14
|
+
actions?: Array<DatasourceAction>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Serves the MCP endpoint and its OAuth flow from the app's own origin.
|
|
18
|
+
*
|
|
19
|
+
* Register it in the app's `src/start.ts`, ahead of `softrAuthMiddleware`: it
|
|
20
|
+
* answers its own paths and resolves the caller from the bearer token, so it
|
|
21
|
+
* must not sit behind the session lookup that middleware does on every
|
|
22
|
+
* request. Everything else passes straight through.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* import { publishedPosts, addCafe } from './actions'
|
|
26
|
+
*
|
|
27
|
+
* export const startInstance = createStart(() => ({
|
|
28
|
+
* requestMiddleware: [
|
|
29
|
+
* softrMcpMiddleware({ actions: [publishedPosts, addCafe] }),
|
|
30
|
+
* softrAuthMiddleware(),
|
|
31
|
+
* ],
|
|
32
|
+
* }))
|
|
33
|
+
*/
|
|
34
|
+
declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { softrMcpMiddleware };
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
import { fetch } from "./fetch.js";
|
|
2
|
+
import { assert } from "./assertions.js";
|
|
3
|
+
import { sessionConfig } from "./auth/config.js";
|
|
4
|
+
import { readSessionToken, withSessionToken } from "./auth/session.js";
|
|
5
|
+
import { makePlatform, platformApiUrl } from "./auth/platform.js";
|
|
6
|
+
import { isDatasourceAction } from "./action.js";
|
|
7
|
+
import { ds } from "./datasource/datasource.js";
|
|
8
|
+
import { createMiddleware } from "@tanstack/react-start";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
//#region src/mcp.ts
|
|
12
|
+
const MCP_PATH = "/_softr/mcp";
|
|
13
|
+
const AUTHORIZE_PATH = "/_softr/oauth/authorize";
|
|
14
|
+
const TOKEN_PATH = "/_softr/oauth/token";
|
|
15
|
+
const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
|
|
16
|
+
const AUTHORIZATION_SERVER_PATH = "/.well-known/oauth-authorization-server";
|
|
17
|
+
/** Where a visitor signs in. The blank template routes `_auth/login` here. */
|
|
18
|
+
const LOGIN_PATH = "/login";
|
|
19
|
+
/** What the platform grants. Advertised here so a client asks for the same. */
|
|
20
|
+
const SCOPES = ["mcp:read", "mcp:write"];
|
|
21
|
+
/** What a client that named no scope gets. Matches the platform's own default. */
|
|
22
|
+
const DEFAULT_SCOPE = "mcp:read";
|
|
23
|
+
const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"];
|
|
24
|
+
/**
|
|
25
|
+
* Serves the MCP endpoint and its OAuth flow from the app's own origin.
|
|
26
|
+
*
|
|
27
|
+
* Register it in the app's `src/start.ts`, ahead of `softrAuthMiddleware`: it
|
|
28
|
+
* answers its own paths and resolves the caller from the bearer token, so it
|
|
29
|
+
* must not sit behind the session lookup that middleware does on every
|
|
30
|
+
* request. Everything else passes straight through.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* import { publishedPosts, addCafe } from './actions'
|
|
34
|
+
*
|
|
35
|
+
* export const startInstance = createStart(() => ({
|
|
36
|
+
* requestMiddleware: [
|
|
37
|
+
* softrMcpMiddleware({ actions: [publishedPosts, addCafe] }),
|
|
38
|
+
* softrAuthMiddleware(),
|
|
39
|
+
* ],
|
|
40
|
+
* }))
|
|
41
|
+
*/
|
|
42
|
+
function softrMcpMiddleware(options = {}) {
|
|
43
|
+
const actions = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const action of options.actions ?? []) {
|
|
45
|
+
assert(isDatasourceAction(action), "softrMcpMiddleware takes actions built by defineQuery or defineMutation");
|
|
46
|
+
const value = action;
|
|
47
|
+
assert(!actions.has(value.id), `two actions share the id "${value.id}"`);
|
|
48
|
+
actions.set(value.id, value);
|
|
49
|
+
}
|
|
50
|
+
return createMiddleware({ type: "request" }).server(async ({ next, request }) => {
|
|
51
|
+
const url = new URL(request.url);
|
|
52
|
+
const origin = url.origin;
|
|
53
|
+
switch (url.pathname) {
|
|
54
|
+
case PROTECTED_RESOURCE_PATH: return json({
|
|
55
|
+
resource: `${origin}${MCP_PATH}`,
|
|
56
|
+
authorization_servers: [origin],
|
|
57
|
+
bearer_methods_supported: ["header"],
|
|
58
|
+
scopes_supported: SCOPES
|
|
59
|
+
});
|
|
60
|
+
case AUTHORIZATION_SERVER_PATH: return json({
|
|
61
|
+
issuer: origin,
|
|
62
|
+
authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
|
|
63
|
+
token_endpoint: `${origin}${TOKEN_PATH}`,
|
|
64
|
+
response_types_supported: ["code"],
|
|
65
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
66
|
+
code_challenge_methods_supported: ["S256"],
|
|
67
|
+
token_endpoint_auth_methods_supported: ["none", "client_secret_basic"],
|
|
68
|
+
client_id_metadata_document_supported: true,
|
|
69
|
+
scopes_supported: SCOPES
|
|
70
|
+
});
|
|
71
|
+
case AUTHORIZE_PATH: return await authorize(request);
|
|
72
|
+
case TOKEN_PATH: return await issueToken(request);
|
|
73
|
+
case MCP_PATH: return await rpc(request, origin, actions);
|
|
74
|
+
default: return await next();
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const authorizeQuerySchema = z.object({
|
|
79
|
+
client_id: z.string().min(1),
|
|
80
|
+
redirect_uri: z.string().url(),
|
|
81
|
+
response_type: z.literal("code"),
|
|
82
|
+
code_challenge: z.string().min(1),
|
|
83
|
+
code_challenge_method: z.literal("S256"),
|
|
84
|
+
state: z.string().optional(),
|
|
85
|
+
scope: z.string().optional(),
|
|
86
|
+
resource: z.string().optional()
|
|
87
|
+
});
|
|
88
|
+
/**
|
|
89
|
+
* The Allow page, and the approval itself.
|
|
90
|
+
*
|
|
91
|
+
* We know who the visitor is from the app's session cookie — readable only
|
|
92
|
+
* because this runs on the app's origin. The client and the code are the
|
|
93
|
+
* platform's, so we ask it for both.
|
|
94
|
+
*/
|
|
95
|
+
async function authorize(request) {
|
|
96
|
+
const url = new URL(request.url);
|
|
97
|
+
const query = authorizeQuerySchema.safeParse(Object.fromEntries(url.searchParams));
|
|
98
|
+
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."));
|
|
99
|
+
if (request.method !== "GET" && request.method !== "POST") return methodNotAllowed("GET, POST");
|
|
100
|
+
const sessionToken = readSessionToken();
|
|
101
|
+
const user = sessionToken === null ? null : await resolveUser(sessionToken);
|
|
102
|
+
if (user === null || sessionToken === null) return html(200, signInPage(url));
|
|
103
|
+
const client = await platformConsent(query.data);
|
|
104
|
+
if (!client.ok) return html(400, page("We can't connect this right now", escapeHtml(client.message)));
|
|
105
|
+
if (request.method === "GET") return html(200, consentPage(user, url, client.name));
|
|
106
|
+
const form = await request.formData();
|
|
107
|
+
const decision = await platformApprove(sessionToken, query.data, form.get("decision") === "allow");
|
|
108
|
+
if (!decision.ok) return html(502, page("We could not finish this", decision.message));
|
|
109
|
+
return redirect(decision.redirectUri);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Passes the token request straight through. The code and refresh token are the
|
|
113
|
+
* platform's, so only it can redeem them. The client's credentials ride along
|
|
114
|
+
* in the Authorization header untouched.
|
|
115
|
+
*/
|
|
116
|
+
async function issueToken(request) {
|
|
117
|
+
if (request.method !== "POST") return methodNotAllowed("POST");
|
|
118
|
+
const authorization = request.headers.get("authorization");
|
|
119
|
+
const response = await platformFetch("/v1/oauth/token", {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: {
|
|
122
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
123
|
+
...authorization === null ? {} : { authorization }
|
|
124
|
+
},
|
|
125
|
+
body: await request.text()
|
|
126
|
+
});
|
|
127
|
+
return new Response(await response.text(), {
|
|
128
|
+
status: response.status,
|
|
129
|
+
headers: {
|
|
130
|
+
"content-type": "application/json",
|
|
131
|
+
"access-control-allow-origin": "*",
|
|
132
|
+
"cache-control": "no-store"
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Tells the platform which app this is about. It normally works that out from
|
|
138
|
+
* the domain, and none of the calls below arrive on the app's domain.
|
|
139
|
+
*/
|
|
140
|
+
const APPLICATION_ID_HEADER = "Softr-Application-ID";
|
|
141
|
+
/**
|
|
142
|
+
* An unreachable platform comes back as a 503, not a thrown error, so callers
|
|
143
|
+
* can handle it with the `response.ok` check they already do. If it threw, the
|
|
144
|
+
* MCP endpoint would answer 500 where the client needs a refusal it can act on.
|
|
145
|
+
*/
|
|
146
|
+
async function platformFetch(path, init) {
|
|
147
|
+
const { applicationId } = sessionConfig();
|
|
148
|
+
try {
|
|
149
|
+
return await fetch(`${await platformApiUrl()}${path}`, {
|
|
150
|
+
method: init.method,
|
|
151
|
+
headers: {
|
|
152
|
+
accept: "application/json",
|
|
153
|
+
[APPLICATION_ID_HEADER]: applicationId,
|
|
154
|
+
...init.headers
|
|
155
|
+
},
|
|
156
|
+
body: init.body
|
|
157
|
+
});
|
|
158
|
+
} catch {
|
|
159
|
+
return json({ message: "Softr could not be reached. Try again in a moment." }, 503);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** The name to show on the Allow page, or why there's nothing to approve. */
|
|
163
|
+
async function platformConsent(query) {
|
|
164
|
+
const response = await platformFetch(`/v1/oauth/authorize?${new URLSearchParams({
|
|
165
|
+
client_id: query.client_id,
|
|
166
|
+
redirect_uri: query.redirect_uri,
|
|
167
|
+
response_type: query.response_type,
|
|
168
|
+
code_challenge: query.code_challenge,
|
|
169
|
+
code_challenge_method: query.code_challenge_method,
|
|
170
|
+
state: query.state ?? "",
|
|
171
|
+
scope: query.scope ?? DEFAULT_SCOPE
|
|
172
|
+
})}`, { method: "GET" });
|
|
173
|
+
const body = await response.json().catch(() => null);
|
|
174
|
+
if (!response.ok) {
|
|
175
|
+
const refusal = z.object({ message: z.string() }).safeParse(body);
|
|
176
|
+
return {
|
|
177
|
+
ok: false,
|
|
178
|
+
message: refusal.success ? refusal.data.message : "The assistant asking for access is not set up for this app."
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
const parsed = z.object({ client_name: z.string().nullish() }).safeParse(body);
|
|
182
|
+
return {
|
|
183
|
+
ok: true,
|
|
184
|
+
name: parsed.success && parsed.data.client_name ? parsed.data.client_name : "An AI assistant"
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Records the answer and returns where to send the browser next — with a code
|
|
189
|
+
* if they allowed it, an error if they didn't. The session token goes in the
|
|
190
|
+
* header. The platform reads a cookie from its own consent page, but this
|
|
191
|
+
* isn't that page.
|
|
192
|
+
*/
|
|
193
|
+
async function platformApprove(sessionToken, query, approved) {
|
|
194
|
+
const response = await platformFetch("/v1/oauth/authorize", {
|
|
195
|
+
method: "POST",
|
|
196
|
+
headers: {
|
|
197
|
+
"content-type": "application/json",
|
|
198
|
+
authorization: `Bearer ${sessionToken}`
|
|
199
|
+
},
|
|
200
|
+
body: JSON.stringify({
|
|
201
|
+
client_id: query.client_id,
|
|
202
|
+
redirect_uri: query.redirect_uri,
|
|
203
|
+
state: query.state ?? "",
|
|
204
|
+
code_challenge: query.code_challenge,
|
|
205
|
+
code_challenge_method: query.code_challenge_method,
|
|
206
|
+
scope: query.scope ?? DEFAULT_SCOPE,
|
|
207
|
+
approved
|
|
208
|
+
})
|
|
209
|
+
});
|
|
210
|
+
const parsed = z.object({ redirect_uri: z.string().url() }).safeParse(await response.json().catch(() => null));
|
|
211
|
+
if (!response.ok || !parsed.success) return {
|
|
212
|
+
ok: false,
|
|
213
|
+
message: "The app could not record your answer. Close this window and try connecting again."
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
ok: true,
|
|
217
|
+
redirectUri: parsed.data.redirect_uri
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async function platformSession(accessToken) {
|
|
221
|
+
const response = await platformFetch("/v1/mcp/session", {
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: { authorization: `Bearer ${accessToken}` }
|
|
224
|
+
});
|
|
225
|
+
if (!response.ok) return {
|
|
226
|
+
ok: false,
|
|
227
|
+
refused: response.status === 401 || response.status === 403
|
|
228
|
+
};
|
|
229
|
+
const parsed = z.object({ jwt: z.string() }).safeParse(await response.json().catch(() => null));
|
|
230
|
+
return parsed.success ? {
|
|
231
|
+
ok: true,
|
|
232
|
+
sessionToken: parsed.data.jwt
|
|
233
|
+
} : {
|
|
234
|
+
ok: false,
|
|
235
|
+
refused: false
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
const WHOAMI = {
|
|
239
|
+
name: "whoami",
|
|
240
|
+
title: "Who am I",
|
|
241
|
+
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.",
|
|
242
|
+
inputSchema: {
|
|
243
|
+
type: "object",
|
|
244
|
+
properties: {},
|
|
245
|
+
additionalProperties: false
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
/** How many records a read returns when the caller does not say. */
|
|
249
|
+
const DEFAULT_LIMIT = 20;
|
|
250
|
+
const MAX_LIMIT = 100;
|
|
251
|
+
/**
|
|
252
|
+
* One tool per action the app chose to expose.
|
|
253
|
+
*
|
|
254
|
+
* The app passes its actions in rather than the SDK discovering them, so that
|
|
255
|
+
* being reachable over MCP is something an app opts into per action. An app
|
|
256
|
+
* that only ever reads one datasource exposes one read, even though its
|
|
257
|
+
* credentials would allow more.
|
|
258
|
+
*/
|
|
259
|
+
function describeTool(action) {
|
|
260
|
+
const { operation, fields } = action.resource;
|
|
261
|
+
const names = Object.keys(fields ?? {});
|
|
262
|
+
const fieldProps = Object.fromEntries(names.map((name) => [name, { description: `The "${name}" field.` }]));
|
|
263
|
+
switch (operation) {
|
|
264
|
+
case "read": return {
|
|
265
|
+
name: action.id,
|
|
266
|
+
description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
|
|
267
|
+
inputSchema: {
|
|
268
|
+
type: "object",
|
|
269
|
+
properties: {
|
|
270
|
+
limit: {
|
|
271
|
+
type: "integer",
|
|
272
|
+
minimum: 1,
|
|
273
|
+
maximum: MAX_LIMIT,
|
|
274
|
+
description: `How many records to return. Defaults to ${DEFAULT_LIMIT}.`
|
|
275
|
+
},
|
|
276
|
+
offset: {
|
|
277
|
+
type: "integer",
|
|
278
|
+
minimum: 0,
|
|
279
|
+
description: "Where the page starts. Use nextOffset from a previous call."
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
additionalProperties: false
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
case "create": return {
|
|
286
|
+
name: action.id,
|
|
287
|
+
description: `Create a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
|
|
288
|
+
inputSchema: {
|
|
289
|
+
type: "object",
|
|
290
|
+
properties: fieldProps,
|
|
291
|
+
additionalProperties: false
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
case "update": return {
|
|
295
|
+
name: action.id,
|
|
296
|
+
description: `Update a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
|
|
297
|
+
inputSchema: {
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
id: {
|
|
301
|
+
type: "string",
|
|
302
|
+
description: "The id of the record to update."
|
|
303
|
+
},
|
|
304
|
+
...fieldProps
|
|
305
|
+
},
|
|
306
|
+
required: ["id"],
|
|
307
|
+
additionalProperties: false
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
case "delete": return {
|
|
311
|
+
name: action.id,
|
|
312
|
+
description: `Delete a record with "${action.id}".`,
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: { id: {
|
|
316
|
+
type: "string",
|
|
317
|
+
description: "The id of the record to delete."
|
|
318
|
+
} },
|
|
319
|
+
required: ["id"],
|
|
320
|
+
additionalProperties: false
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Runs one action as the visitor the access token belongs to.
|
|
327
|
+
*
|
|
328
|
+
* Every call goes through `ds`, so the platform authorizes it against that
|
|
329
|
+
* visitor's user groups exactly as it would a click in the app. Nothing here
|
|
330
|
+
* decides what is allowed.
|
|
331
|
+
*/
|
|
332
|
+
async function runTool(action, args) {
|
|
333
|
+
const typed = action;
|
|
334
|
+
switch (action.resource.operation) {
|
|
335
|
+
case "read": {
|
|
336
|
+
const limit = clampLimit(args.limit);
|
|
337
|
+
const offset = clampOffset(args.offset);
|
|
338
|
+
const result$1 = await ds.list(typed).limit(limit).offset(offset);
|
|
339
|
+
return {
|
|
340
|
+
records: result$1.records,
|
|
341
|
+
nextOffset: result$1.nextOffset
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
case "create": return await ds.create(typed, { data: writableFields(action, args) });
|
|
345
|
+
case "update": {
|
|
346
|
+
const { id,...data } = args;
|
|
347
|
+
assert(typeof id === "string" && id !== "", "update needs a record id");
|
|
348
|
+
return await ds.update(typed, {
|
|
349
|
+
id,
|
|
350
|
+
data: writableFields(action, data)
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
case "delete": {
|
|
354
|
+
const { id } = args;
|
|
355
|
+
assert(typeof id === "string" && id !== "", "delete needs a record id");
|
|
356
|
+
await ds.delete(typed, { id });
|
|
357
|
+
return { deleted: id };
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Only the fields the action declared.
|
|
363
|
+
*
|
|
364
|
+
* `additionalProperties: false` in the tool schema is a hint to the model, not
|
|
365
|
+
* a check — a client can send whatever it likes. An unlisted key reaches the
|
|
366
|
+
* datasource as a raw field id, because `dealiasData` passes an unknown alias
|
|
367
|
+
* straight through. So the action's field list gets enforced here, or it isn't
|
|
368
|
+
* a boundary at all.
|
|
369
|
+
*/
|
|
370
|
+
function writableFields(action, args) {
|
|
371
|
+
const allowed = action.resource.fields ?? {};
|
|
372
|
+
return Object.fromEntries(Object.entries(args).filter(([name]) => name in allowed));
|
|
373
|
+
}
|
|
374
|
+
function clampLimit(raw) {
|
|
375
|
+
if (typeof raw !== "number" || !Number.isInteger(raw)) return DEFAULT_LIMIT;
|
|
376
|
+
return Math.min(Math.max(raw, 1), MAX_LIMIT);
|
|
377
|
+
}
|
|
378
|
+
function clampOffset(raw) {
|
|
379
|
+
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) return null;
|
|
380
|
+
return raw;
|
|
381
|
+
}
|
|
382
|
+
async function rpc(request, origin, actions) {
|
|
383
|
+
if (request.method !== "POST") return methodNotAllowed("POST");
|
|
384
|
+
const token = bearerToken(request);
|
|
385
|
+
if (token === null) return unauthorized(origin);
|
|
386
|
+
const session = await platformSession(token);
|
|
387
|
+
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
|
|
388
|
+
const { sessionToken } = session;
|
|
389
|
+
const body = await readJson(request);
|
|
390
|
+
const message = z.object({
|
|
391
|
+
id: z.union([z.string(), z.number()]).optional(),
|
|
392
|
+
method: z.string(),
|
|
393
|
+
params: z.record(z.string(), z.unknown()).optional()
|
|
394
|
+
}).safeParse(body);
|
|
395
|
+
if (!message.success) return json({
|
|
396
|
+
jsonrpc: "2.0",
|
|
397
|
+
id: null,
|
|
398
|
+
error: {
|
|
399
|
+
code: -32700,
|
|
400
|
+
message: "Parse error"
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
const { id, method, params } = message.data;
|
|
404
|
+
if (id === void 0) return new Response(null, { status: 202 });
|
|
405
|
+
switch (method) {
|
|
406
|
+
case "initialize": {
|
|
407
|
+
const requested = params?.protocolVersion;
|
|
408
|
+
return result(id, {
|
|
409
|
+
protocolVersion: typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0],
|
|
410
|
+
capabilities: { tools: { listChanged: false } },
|
|
411
|
+
serverInfo: {
|
|
412
|
+
name: "softr-app",
|
|
413
|
+
version: "0.1.0"
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
case "tools/list": return result(id, { tools: [WHOAMI, ...[...actions.values()].map(describeTool)] });
|
|
418
|
+
case "tools/call": {
|
|
419
|
+
const name = params?.name;
|
|
420
|
+
const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
421
|
+
if (name === WHOAMI.name) {
|
|
422
|
+
const user = await resolveUser(sessionToken);
|
|
423
|
+
if (user === null) return unauthorized(origin);
|
|
424
|
+
return result(id, toolResult(user));
|
|
425
|
+
}
|
|
426
|
+
const action = typeof name === "string" ? actions.get(name) : void 0;
|
|
427
|
+
if (action === void 0) return failure(id, -32602, `Unknown tool: ${String(name)}`);
|
|
428
|
+
try {
|
|
429
|
+
return result(id, toolResult(await withSessionToken(sessionToken, () => runTool(action, args))));
|
|
430
|
+
} catch (error) {
|
|
431
|
+
return result(id, {
|
|
432
|
+
isError: true,
|
|
433
|
+
content: [{
|
|
434
|
+
type: "text",
|
|
435
|
+
text: error instanceof Error ? error.message : String(error)
|
|
436
|
+
}]
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
default: return failure(id, -32601, `Method not found: ${method}`);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function toolResult(output) {
|
|
444
|
+
return {
|
|
445
|
+
content: [{
|
|
446
|
+
type: "text",
|
|
447
|
+
text: JSON.stringify(output, null, 2)
|
|
448
|
+
}],
|
|
449
|
+
structuredContent: output
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
function result(id, payload) {
|
|
453
|
+
return json({
|
|
454
|
+
jsonrpc: "2.0",
|
|
455
|
+
id,
|
|
456
|
+
result: payload
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
function failure(id, code, message) {
|
|
460
|
+
return json({
|
|
461
|
+
jsonrpc: "2.0",
|
|
462
|
+
id,
|
|
463
|
+
error: {
|
|
464
|
+
code,
|
|
465
|
+
message
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
function unauthorized(origin) {
|
|
470
|
+
return new Response(JSON.stringify({ error: "invalid_token" }), {
|
|
471
|
+
status: 401,
|
|
472
|
+
headers: {
|
|
473
|
+
"content-type": "application/json",
|
|
474
|
+
"www-authenticate": `Bearer resource_metadata="${origin}${PROTECTED_RESOURCE_PATH}", scope="${SCOPES.join(" ")}"`
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
/** The platform is down, not the token. 503 so the client retries rather than
|
|
479
|
+
* throwing its token away. */
|
|
480
|
+
function unavailable() {
|
|
481
|
+
return json({ error: "temporarily_unavailable" }, 503);
|
|
482
|
+
}
|
|
483
|
+
function bearerToken(request) {
|
|
484
|
+
const header = request.headers.get("authorization");
|
|
485
|
+
if (header === null) return null;
|
|
486
|
+
const [scheme, value] = header.split(" ");
|
|
487
|
+
return scheme?.toLowerCase() === "bearer" && value ? value : null;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* The visitor a session token belongs to, or `null` when the platform refuses
|
|
491
|
+
* it — expired, revoked, or issued for another application.
|
|
492
|
+
*/
|
|
493
|
+
async function resolveUser(sessionToken) {
|
|
494
|
+
const { applicationId } = sessionConfig();
|
|
495
|
+
const result$1 = await makePlatform(applicationId).session(sessionToken);
|
|
496
|
+
return result$1.ok ? result$1.data.user : null;
|
|
497
|
+
}
|
|
498
|
+
async function readJson(request) {
|
|
499
|
+
try {
|
|
500
|
+
return await request.json();
|
|
501
|
+
} catch {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function json(payload, status = 200) {
|
|
506
|
+
return new Response(JSON.stringify(payload), {
|
|
507
|
+
status,
|
|
508
|
+
headers: {
|
|
509
|
+
"content-type": "application/json",
|
|
510
|
+
"access-control-allow-origin": "*",
|
|
511
|
+
"cache-control": "no-store"
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
function methodNotAllowed(allowed) {
|
|
516
|
+
return new Response(null, {
|
|
517
|
+
status: 405,
|
|
518
|
+
headers: { allow: allowed }
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
function redirect(location) {
|
|
522
|
+
return new Response(null, {
|
|
523
|
+
status: 302,
|
|
524
|
+
headers: { location }
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
function html(status, body) {
|
|
528
|
+
return new Response(body, {
|
|
529
|
+
status,
|
|
530
|
+
headers: {
|
|
531
|
+
"content-type": "text/html; charset=utf-8",
|
|
532
|
+
"cache-control": "no-store"
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
function consentPage(user, url, clientName) {
|
|
537
|
+
const fields = Array.from(url.searchParams.entries()).map(([key, value]) => `<input type="hidden" name="${escapeHtml(key)}" value="${escapeHtml(value)}">`).join("");
|
|
538
|
+
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)}">
|
|
539
|
+
${fields}
|
|
540
|
+
<button type="submit" name="decision" value="allow" class="primary">Allow</button>
|
|
541
|
+
<button type="submit" name="decision" value="deny">Cancel</button>
|
|
542
|
+
</form>`);
|
|
543
|
+
}
|
|
544
|
+
function signInPage(url) {
|
|
545
|
+
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="${LOGIN_PATH}?redirect=${encodeURIComponent(url.pathname + url.search)}">Sign in</a>`);
|
|
546
|
+
}
|
|
547
|
+
function page(title, body, actions = "") {
|
|
548
|
+
return `<!doctype html>
|
|
549
|
+
<html lang="en">
|
|
550
|
+
<head>
|
|
551
|
+
<meta charset="utf-8">
|
|
552
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
553
|
+
<title>${escapeHtml(title)}</title>
|
|
554
|
+
<style>
|
|
555
|
+
:root { color-scheme: light dark; }
|
|
556
|
+
body {
|
|
557
|
+
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
558
|
+
font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
559
|
+
background: Canvas; color: CanvasText; padding: 24px;
|
|
560
|
+
}
|
|
561
|
+
main { max-width: 26rem; }
|
|
562
|
+
h1 { font-size: 1.35rem; margin: 0 0 .6rem; }
|
|
563
|
+
p { margin: 0 0 1.5rem; opacity: .8; }
|
|
564
|
+
form { display: flex; gap: .6rem; flex-wrap: wrap; }
|
|
565
|
+
button, a.primary {
|
|
566
|
+
font: inherit; padding: .55rem 1.1rem; border-radius: .4rem; cursor: pointer;
|
|
567
|
+
border: 1px solid currentColor; background: transparent; color: inherit;
|
|
568
|
+
text-decoration: none; display: inline-block;
|
|
569
|
+
}
|
|
570
|
+
.primary { background: CanvasText; color: Canvas; border-color: CanvasText; }
|
|
571
|
+
</style>
|
|
572
|
+
</head>
|
|
573
|
+
<body><main><h1>${escapeHtml(title)}</h1><p>${body}</p>${actions}</main></body>
|
|
574
|
+
</html>`;
|
|
575
|
+
}
|
|
576
|
+
function escapeHtml(value) {
|
|
577
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
//#endregion
|
|
581
|
+
export { softrMcpMiddleware };
|
package/dist/package.js
CHANGED
package/dist/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { upload } from "./core/file-upload.js";
|
|
2
|
-
import { auth } from "./auth/server.js";
|
|
3
2
|
import { ds } from "./datasource/datasource.js";
|
|
3
|
+
import { auth } from "./auth/server.js";
|
|
4
4
|
import { workflow } from "./core/workflow.js";
|
|
5
5
|
import { integration } from "./core/integration.js";
|
|
6
6
|
import "@tanstack/react-start/server-only";
|
package/package.json
CHANGED
|
@@ -1,16 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softr/sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.45-alpha.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
|
-
".": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
6
|
+
".": {
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"import": "./dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"./client": {
|
|
11
|
+
"types": "./dist/client.d.ts",
|
|
12
|
+
"import": "./dist/client.js"
|
|
13
|
+
},
|
|
14
|
+
"./server": {
|
|
15
|
+
"types": "./dist/server.d.ts",
|
|
16
|
+
"import": "./dist/server.js"
|
|
17
|
+
},
|
|
18
|
+
"./vite": {
|
|
19
|
+
"types": "./dist/vite.d.ts",
|
|
20
|
+
"import": "./dist/vite.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"bin": {
|
|
24
|
+
"softr-sdk": "./dist/cli.js"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"schema",
|
|
29
|
+
"skills",
|
|
30
|
+
"!skills/_artifacts"
|
|
31
|
+
],
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
14
35
|
"scripts": {
|
|
15
36
|
"build": "tsdown",
|
|
16
37
|
"test": "node --import ./src/test-utils/setup.ts --test",
|
|
@@ -42,7 +63,9 @@
|
|
|
42
63
|
"optional": true
|
|
43
64
|
}
|
|
44
65
|
},
|
|
45
|
-
"keywords": [
|
|
66
|
+
"keywords": [
|
|
67
|
+
"tanstack-intent"
|
|
68
|
+
],
|
|
46
69
|
"intent": {
|
|
47
70
|
"version": 1,
|
|
48
71
|
"repo": "@softr/sdk",
|
|
@@ -20,7 +20,7 @@ metadata:
|
|
|
20
20
|
|
|
21
21
|
> **CRITICAL**: The SDK is split across four entrypoints and the split is enforced. `ds` and `auth` exist only on `@softr/sdk/server` and only run inside a `createServerFn` handler. Importing them anywhere else fails the build.
|
|
22
22
|
> **CRITICAL**: Every route file must declare its audience with `defineVisibility`. There is no default and nothing is inherited from a sibling. A route file without a declaration is a lint error.
|
|
23
|
-
> **CRITICAL**: The
|
|
23
|
+
> **CRITICAL**: The session wiring is already in place. `src/start.ts`, `src/router.tsx` and `src/routes/__root.tsx` register `softrAuthMiddleware` and resolve the visitor. Do not add a second registration of it. `softrMcpMiddleware` is the one thing an app adds to `src/start.ts` itself — load the `softr-sdk/mcp` sub-skill before doing so.
|
|
24
24
|
> **CRITICAL**: `workflow.trigger` lives on `@softr/sdk/server` and only runs inside a `createServerFn` handler. Use `defineWorkflow` from `@softr/sdk` to declare the action, then pass it to `workflow.trigger`. Load the `softr-sdk/workflows` sub-skill for the full pattern.
|
|
25
25
|
|
|
26
26
|
Each sub-skill stands alone for its task and repeats the boundary above, so most work needs **one** sub-skill and not this file. Load this one when you are unsure which sub-skill applies, or when the wiring below is what you are touching. Add a second sub-skill only when the work genuinely crosses that boundary: a page that lists records behind a group restriction needs `record-queries` plus `routes-and-visibility`.
|
|
@@ -46,6 +46,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
46
46
|
| Trigger a Softr workflow | [workflows/SKILL.md](./workflows/SKILL.md) |
|
|
47
47
|
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
|
|
48
48
|
| Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
49
|
+
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
49
50
|
|
|
50
51
|
## Quick Decision Tree
|
|
51
52
|
|
|
@@ -74,13 +75,16 @@ Wiring a login, signup, or sign-out?
|
|
|
74
75
|
Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)?
|
|
75
76
|
load softr-sdk/integrations
|
|
76
77
|
|
|
78
|
+
Opening the app to an AI assistant over MCP?
|
|
79
|
+
load softr-sdk/mcp
|
|
80
|
+
|
|
77
81
|
Writing a server function, loader, or middleware in general?
|
|
78
82
|
not a Softr concern. Use the TanStack Start skills.
|
|
79
83
|
```
|
|
80
84
|
|
|
81
85
|
## The wiring
|
|
82
86
|
|
|
83
|
-
Already present in the app. Read it to understand where the visitor comes from. Do not recreate it.
|
|
87
|
+
Already present in the app. Read it to understand where the visitor comes from. Do not recreate it. `softrMcpMiddleware` is the exception: it is not wired by default and is added here when the app opens itself to AI assistants.
|
|
84
88
|
|
|
85
89
|
```ts
|
|
86
90
|
// src/start.ts: resolves the visitor once per request
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: mcp
|
|
3
|
+
description: >-
|
|
4
|
+
Open the app to AI assistants over MCP: softrMcpMiddleware({ actions }) from
|
|
5
|
+
@softr/sdk, registered in src/start.ts ahead of softrAuthMiddleware, turns the
|
|
6
|
+
actions you list into tools an assistant can call as the signed-in visitor.
|
|
7
|
+
The list is explicit — an action left out is invisible over MCP. The app's own
|
|
8
|
+
login must honour a `redirect` search param, or the approval step dead-ends.
|
|
9
|
+
metadata:
|
|
10
|
+
type: sub-skill
|
|
11
|
+
library: softr-sdk
|
|
12
|
+
library_version: 0.0.44
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
**Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP.
|
|
16
|
+
|
|
17
|
+
# MCP
|
|
18
|
+
|
|
19
|
+
An app can answer an AI assistant on its own origin. The assistant signs in as an ordinary app user, and the actions you list become the tools it may call. Not wired by default — a new app serves no MCP endpoint until you add the middleware.
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// src/start.ts
|
|
25
|
+
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'
|
|
26
|
+
import { softrAuthMiddleware, softrMcpMiddleware } from '@softr/sdk'
|
|
27
|
+
import { listCafes, addCafe } from './actions'
|
|
28
|
+
|
|
29
|
+
export const startInstance = createStart(() => ({
|
|
30
|
+
requestMiddleware: [
|
|
31
|
+
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
|
|
32
|
+
softrMcpMiddleware({ actions: [listCafes, addCafe] }),
|
|
33
|
+
softrAuthMiddleware(),
|
|
34
|
+
],
|
|
35
|
+
}))
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Order is part of the contract. `softrMcpMiddleware` goes **before** `softrAuthMiddleware`: an assistant arrives with a token, not a browser session, so it must not hit the session lookup first.
|
|
39
|
+
|
|
40
|
+
## Choosing the actions
|
|
41
|
+
|
|
42
|
+
The list is the whole tool surface. Write it out:
|
|
43
|
+
|
|
44
|
+
- An action you leave out is invisible to the assistant, even where the app's pages use it freely.
|
|
45
|
+
- An action you list still obeys its own `permissions`. Listing it does not widen who may run it — the assistant runs as whoever signed in, with that user's groups.
|
|
46
|
+
- Two actions with the same `id` throw at startup. So does anything that is not a `defineQuery` or `defineMutation` value.
|
|
47
|
+
|
|
48
|
+
Reads first. Add a write only when the user asked for one, and name it back to them.
|
|
49
|
+
|
|
50
|
+
## The login round trip
|
|
51
|
+
|
|
52
|
+
Connecting starts with an approval page the app serves. Most people hit it signed out, and that page cannot sign anyone in. It sends them to `/login` with a `redirect` search param holding where to come back to.
|
|
53
|
+
|
|
54
|
+
**The app's login has to honour that param.** Carry it through every exit that ends a sign-in, the second-factor step included, and send the visitor there instead of the home page. Drop it anywhere along the way and the approval dies quietly: they land on the home page, the assistant never gets its answer, nothing reports an error.
|
|
55
|
+
|
|
56
|
+
Validate it before following it. A path on this app and nothing else — not a full URL, not one starting `//`. The whole flow starts with a link someone was sent, so this is the one redirect an attacker can reliably aim.
|
|
57
|
+
|
|
58
|
+
The blank template does this in `src/routes/_auth/login.tsx`, `src/routes/verify.tsx` and `src/lib/after-auth.ts`. Read those before writing your own.
|
|
59
|
+
|
|
60
|
+
## Failure modes
|
|
61
|
+
|
|
62
|
+
**Registering with no actions.** `softrMcpMiddleware()` is valid and serves an endpoint with nothing on it. The assistant connects, lists tools, finds only `whoami`. Pass the actions.
|
|
63
|
+
|
|
64
|
+
**Registering after `softrAuthMiddleware`.** The assistant's token is never read. Put the MCP middleware first.
|
|
65
|
+
|
|
66
|
+
**A login that drops `redirect`.** Sign-in works, approval doesn't. The most common break, and silent — test the connect flow signed out, not only signed in.
|
|
67
|
+
|
|
68
|
+
**Following `redirect` unchecked.** Anything that is not a path on this app is someone else's page. Reject it, fall back to `/`.
|
|
69
|
+
|
|
70
|
+
## References
|
|
71
|
+
|
|
72
|
+
- [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the read actions you expose
|
|
73
|
+
- [record-mutations/SKILL.md](../record-mutations/SKILL.md): declaring the write actions you expose
|
|
74
|
+
- [auth/SKILL.md](../auth/SKILL.md): the sign-in and second-factor flows the round trip passes through
|