@softr/sdk 1.14.0 → 1.15.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/CHANGELOG.md +10 -0
- package/dist/auth/methods/authenticator.js +8 -1
- package/dist/auth/methods/code.js +3 -1
- package/dist/auth/methods/emailCode2fa.js +3 -1
- package/dist/auth/methods/magicLink.js +2 -1
- package/dist/auth/methods/password.js +3 -1
- package/dist/auth/methods/passwordLink.js +3 -1
- package/dist/auth/methods/profile.js +3 -1
- package/dist/auth/methods/signup.js +3 -1
- package/dist/auth/methods/social.js +2 -1
- package/dist/auth/platform.js +14 -8
- package/dist/auth/session.js +18 -3
- package/dist/core/email.js +2 -1
- package/dist/core/file-upload.js +2 -1
- package/dist/core/integration.js +4 -2
- package/dist/core/workflow.js +2 -1
- package/dist/datasource/record.js +4 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/mcp.d.ts +9 -2
- package/dist/mcp.js +102 -22
- package/dist/package.js +1 -1
- package/dist/tool.d.ts +64 -0
- package/dist/tool.js +51 -0
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +1 -1
- package/skills/softr-sdk/ai/SKILL.md +1 -1
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/email/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +1 -1
- package/skills/softr-sdk/mcp/SKILL.md +75 -17
- package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @softr/sdk
|
|
2
2
|
|
|
3
|
+
## 1.15.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- `defineTool` declares an MCP tool that runs the app's own logic as the signed-in user, labelled read-only or not.
|
|
8
|
+
- `softrMcpMiddleware` takes `tools` next to `actions`.
|
|
9
|
+
- A read-only tool cannot change data or send anything through `ds`, `email`, `workflow`, `upload`, an `integration` call that is not a GET or HEAD, or an `auth` call that changes data, sends an email or signs somebody in.
|
|
10
|
+
- Tools built from `actions` carry read-only and destructive hints. An update or a delete is marked destructive.
|
|
11
|
+
- The MCP `whoami` tool names the user's groups, once the platform sends the names.
|
|
12
|
+
|
|
3
13
|
## 1.14.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/authenticator.ts
|
|
@@ -19,6 +19,7 @@ import { authError } from "./utils.js";
|
|
|
19
19
|
* one. Only the newest one enrols them.
|
|
20
20
|
*/
|
|
21
21
|
async function startAuthenticatorSetup() {
|
|
22
|
+
assertCanChange("auth.startAuthenticatorSetup");
|
|
22
23
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupInit(readPendingAuthToken() ?? readSessionToken());
|
|
23
24
|
if (!result.ok) {
|
|
24
25
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
@@ -38,6 +39,7 @@ async function startAuthenticatorSetup() {
|
|
|
38
39
|
* once. Nothing fetches them again, so render them before leaving the page.
|
|
39
40
|
*/
|
|
40
41
|
async function confirmAuthenticatorSetup(details) {
|
|
42
|
+
assertCanChange("auth.confirmAuthenticatorSetup");
|
|
41
43
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code);
|
|
42
44
|
if (!result.ok) {
|
|
43
45
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
@@ -63,6 +65,7 @@ async function confirmAuthenticatorSetup(details) {
|
|
|
63
65
|
* Later sign-ins stop asking.
|
|
64
66
|
*/
|
|
65
67
|
async function skipAuthenticatorSetup() {
|
|
68
|
+
assertCanChange("auth.skipAuthenticatorSetup");
|
|
66
69
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken());
|
|
67
70
|
if (!result.ok) {
|
|
68
71
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
@@ -86,6 +89,7 @@ async function skipAuthenticatorSetup() {
|
|
|
86
89
|
* Each backup code works once.
|
|
87
90
|
*/
|
|
88
91
|
async function verifyAuthenticator(credentials) {
|
|
92
|
+
assertCanChange("auth.verifyAuthenticator");
|
|
89
93
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode });
|
|
90
94
|
if (!result.ok) {
|
|
91
95
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
@@ -110,6 +114,7 @@ async function verifyAuthenticator(credentials) {
|
|
|
110
114
|
* on top of being signed in.
|
|
111
115
|
*/
|
|
112
116
|
async function sendAuthenticatorResetCode() {
|
|
117
|
+
assertCanChange("auth.sendAuthenticatorResetCode");
|
|
113
118
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSendResetCode(readSessionToken());
|
|
114
119
|
if (!result.ok) {
|
|
115
120
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
@@ -129,6 +134,7 @@ async function sendAuthenticatorResetCode() {
|
|
|
129
134
|
* `code` is the one {@link sendAuthenticatorResetCode} emailed.
|
|
130
135
|
*/
|
|
131
136
|
async function resetAuthenticator(details) {
|
|
137
|
+
assertCanChange("auth.resetAuthenticator");
|
|
132
138
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorReset(readSessionToken(), details.code);
|
|
133
139
|
if (!result.ok) {
|
|
134
140
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
@@ -149,6 +155,7 @@ async function resetAuthenticator(details) {
|
|
|
149
155
|
* sign-in.
|
|
150
156
|
*/
|
|
151
157
|
async function removeAuthenticator(details) {
|
|
158
|
+
assertCanChange("auth.removeAuthenticator");
|
|
152
159
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorRemove(readSessionToken(), details.code);
|
|
153
160
|
if (!result.ok) {
|
|
154
161
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/code.ts
|
|
@@ -15,6 +15,7 @@ const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccou
|
|
|
15
15
|
* `accountDeactivated`, so the visitor is not left waiting for an email.
|
|
16
16
|
*/
|
|
17
17
|
async function sendSignInCode(details) {
|
|
18
|
+
assertCanChange("auth.sendSignInCode");
|
|
18
19
|
const result = await makePlatform(sessionConfig().applicationId).sendSignInCode(details.email);
|
|
19
20
|
if (!result.ok) {
|
|
20
21
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
@@ -35,6 +36,7 @@ async function sendSignInCode(details) {
|
|
|
35
36
|
* to send them to next.
|
|
36
37
|
*/
|
|
37
38
|
async function signInWithCode(credentials) {
|
|
39
|
+
assertCanChange("auth.signInWithCode");
|
|
38
40
|
const result = await makePlatform(sessionConfig().applicationId).signInWithCode(credentials);
|
|
39
41
|
if (!result.ok) {
|
|
40
42
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/emailCode2fa.ts
|
|
@@ -15,6 +15,7 @@ import { authError } from "./utils.js";
|
|
|
15
15
|
* to send them to next.
|
|
16
16
|
*/
|
|
17
17
|
async function verifyEmailCode(details) {
|
|
18
|
+
assertCanChange("auth.verifyEmailCode");
|
|
18
19
|
const result = await makePlatform(sessionConfig().applicationId).emailCodeVerify(readPendingAuthToken(), details.code);
|
|
19
20
|
if (!result.ok) {
|
|
20
21
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
@@ -51,6 +52,7 @@ async function verifyEmailCode(details) {
|
|
|
51
52
|
* short wait sends nothing and still succeeds.
|
|
52
53
|
*/
|
|
53
54
|
async function resendEmailCode() {
|
|
55
|
+
assertCanChange("auth.resendEmailCode");
|
|
54
56
|
const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken());
|
|
55
57
|
if (!result.ok) {
|
|
56
58
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
|
+
import { assertCanChange, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/magicLink.ts
|
|
@@ -15,6 +15,7 @@ import { authError } from "./utils.js";
|
|
|
15
15
|
*
|
|
16
16
|
*/
|
|
17
17
|
async function signInWithMagicLink(credentials) {
|
|
18
|
+
assertCanChange("auth.signInWithMagicLink");
|
|
18
19
|
const result = await makePlatform(sessionConfig().applicationId).signInWithMagicLink(credentials);
|
|
19
20
|
if (!result.ok) {
|
|
20
21
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
@@ -2,7 +2,7 @@ import { assert, panic, softAssert } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/password.ts
|
|
@@ -15,6 +15,7 @@ import { authError } from "./utils.js";
|
|
|
15
15
|
* `emailCodeRequired`; `verifyEmailCode` finishes it.
|
|
16
16
|
*/
|
|
17
17
|
async function signIn(credentials) {
|
|
18
|
+
assertCanChange("auth.signIn");
|
|
18
19
|
const result = await makePlatform(sessionConfig().applicationId).tokens(credentials);
|
|
19
20
|
if (!result.ok) {
|
|
20
21
|
if (result.status === 401) return authError("invalidCredentials", result.message);
|
|
@@ -57,6 +58,7 @@ async function signIn(credentials) {
|
|
|
57
58
|
* is no per-device sign-out.
|
|
58
59
|
*/
|
|
59
60
|
async function signOut() {
|
|
61
|
+
assertCanChange("auth.signOut");
|
|
60
62
|
const token = readSessionToken();
|
|
61
63
|
clearSession();
|
|
62
64
|
if (!token) return;
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/passwordLink.ts
|
|
@@ -13,6 +13,7 @@ import { authError } from "./utils.js";
|
|
|
13
13
|
* it has none.
|
|
14
14
|
*/
|
|
15
15
|
async function requestPasswordReset(details) {
|
|
16
|
+
assertCanChange("auth.requestPasswordReset");
|
|
16
17
|
const result = await makePlatform(sessionConfig().applicationId).forgotPassword(details);
|
|
17
18
|
if (!result.ok) {
|
|
18
19
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
@@ -47,6 +48,7 @@ async function checkPasswordLink(details) {
|
|
|
47
48
|
* the visitor's other sessions.
|
|
48
49
|
*/
|
|
49
50
|
async function setPasswordWithLink(details) {
|
|
51
|
+
assertCanChange("auth.setPasswordWithLink");
|
|
50
52
|
const result = await makePlatform(sessionConfig().applicationId).setPassword(details);
|
|
51
53
|
if (!result.ok) {
|
|
52
54
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { sessionConfig } from "../config.js";
|
|
3
3
|
import { makePlatform } from "../platform.js";
|
|
4
|
-
import { clearSessionData, readSessionToken } from "../session.js";
|
|
4
|
+
import { assertCanChange, clearSessionData, readSessionToken } from "../session.js";
|
|
5
5
|
import { authError } from "./utils.js";
|
|
6
6
|
|
|
7
7
|
//#region src/auth/methods/profile.ts
|
|
@@ -25,6 +25,7 @@ import { authError } from "./utils.js";
|
|
|
25
25
|
* const result = await auth.updateProfile({ avatar: file })
|
|
26
26
|
*/
|
|
27
27
|
async function updateProfile(changes) {
|
|
28
|
+
assertCanChange("auth.updateProfile");
|
|
28
29
|
assert(changes.fullName !== void 0 || changes.avatar !== void 0, "updateProfile needs a name or a photo to change");
|
|
29
30
|
const token = readSessionToken();
|
|
30
31
|
if (token === null) return authError("notAuthenticated", "Nobody is signed in.");
|
|
@@ -44,6 +45,7 @@ async function updateProfile(changes) {
|
|
|
44
45
|
* const result = await auth.removeAvatar()
|
|
45
46
|
*/
|
|
46
47
|
async function removeAvatar() {
|
|
48
|
+
assertCanChange("auth.removeAvatar");
|
|
47
49
|
const token = readSessionToken();
|
|
48
50
|
if (token === null) return authError("notAuthenticated", "Nobody is signed in.");
|
|
49
51
|
return answer(await makePlatform(sessionConfig().applicationId).removeAvatar(token), "invalidPhoto");
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/signup.ts
|
|
@@ -12,6 +12,7 @@ import { authError } from "./utils.js";
|
|
|
12
12
|
* User only exists once `confirmSignUp` returns the code.
|
|
13
13
|
*/
|
|
14
14
|
async function signUp(details) {
|
|
15
|
+
assertCanChange("auth.signUp");
|
|
15
16
|
const result = await makePlatform(sessionConfig().applicationId).sendSignUpCode(details);
|
|
16
17
|
if (!result.ok) {
|
|
17
18
|
if (result.status === 409) return authError("emailTaken", result.message);
|
|
@@ -39,6 +40,7 @@ async function signUp(details) {
|
|
|
39
40
|
* to send them to next.
|
|
40
41
|
*/
|
|
41
42
|
async function confirmSignUp(details) {
|
|
43
|
+
assertCanChange("auth.confirmSignUp");
|
|
42
44
|
const platform = makePlatform(sessionConfig().applicationId);
|
|
43
45
|
const { password,...rest } = details;
|
|
44
46
|
const result = password === void 0 ? await platform.signUpWithCode(rest) : await platform.signUpWithPassword({
|
|
@@ -2,7 +2,7 @@ import { assert, panic } from "../../assertions.js";
|
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
|
+
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
|
|
@@ -24,6 +24,7 @@ const errorBodySchema = z.object({ code: z.string() });
|
|
|
24
24
|
* sign-in, as after a downgrade.
|
|
25
25
|
*/
|
|
26
26
|
async function signInWithGoogle(credentials) {
|
|
27
|
+
assertCanChange("auth.signInWithGoogle");
|
|
27
28
|
const result = await makePlatform(sessionConfig().applicationId).signInWithGoogle(credentials);
|
|
28
29
|
if (!result.ok) {
|
|
29
30
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
package/dist/auth/platform.js
CHANGED
|
@@ -72,16 +72,18 @@ function makePlatform(applicationId) {
|
|
|
72
72
|
}),
|
|
73
73
|
returnPath: z.string()
|
|
74
74
|
});
|
|
75
|
+
async function readSession(token, user) {
|
|
76
|
+
const result = await request(`/v1/vibe/applications/${applicationId}/users/session${withAttributes}`, {
|
|
77
|
+
method: "GET",
|
|
78
|
+
token
|
|
79
|
+
}, z.object({ user: user.nullable() }));
|
|
80
|
+
if (result.status === 404) panic(`Application ${applicationId} not found. Check SOFTR_APPLICATION_ID.`);
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
75
83
|
return {
|
|
76
84
|
authSettings: () => request(`/v1/vibe/applications/${applicationId}/users/auth-settings`, { method: "GET" }, authSettingsSchema),
|
|
77
|
-
session:
|
|
78
|
-
|
|
79
|
-
method: "GET",
|
|
80
|
-
token
|
|
81
|
-
}, z.object({ user: userSchema.nullable() }));
|
|
82
|
-
if (result.status === 404) panic(`Application ${applicationId} not found. Check SOFTR_APPLICATION_ID.`);
|
|
83
|
-
return result;
|
|
84
|
-
},
|
|
85
|
+
session: (token) => readSession(token, userSchema),
|
|
86
|
+
sessionWithGroupNames: (token) => readSession(token, z.intersection(userSchema, userGroupNamesSchema)),
|
|
85
87
|
tokens: (credentials) => request(`/v1/vibe/applications/${applicationId}/users/tokens${withAttributes}`, {
|
|
86
88
|
method: "POST",
|
|
87
89
|
json: credentials
|
|
@@ -369,6 +371,10 @@ function makePlatform(applicationId) {
|
|
|
369
371
|
};
|
|
370
372
|
}
|
|
371
373
|
const errorSchema = z.object({ message: z.string() });
|
|
374
|
+
const userGroupNamesSchema = z.object({ userGroups: z.array(z.object({
|
|
375
|
+
id: z.string(),
|
|
376
|
+
name: z.string().nullable()
|
|
377
|
+
})).optional() });
|
|
372
378
|
async function request(path, init, schema, parse = (response$1) => response$1.json()) {
|
|
373
379
|
assert(init.json === void 0 || init.form === void 0, "A platform request carries a JSON body or a form, not both");
|
|
374
380
|
const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}${path}`, {
|
package/dist/auth/session.js
CHANGED
|
@@ -47,8 +47,23 @@ function sessionCookie(base) {
|
|
|
47
47
|
* For requests that carry who they are somewhere other than the cookie: an MCP
|
|
48
48
|
* call authenticates with a bearer token and has no cookie at all.
|
|
49
49
|
*/
|
|
50
|
-
function withSessionToken(token, fn) {
|
|
51
|
-
return standIn.run({
|
|
50
|
+
function withSessionToken(token, fn, options = {}) {
|
|
51
|
+
return standIn.run({
|
|
52
|
+
token,
|
|
53
|
+
readOnly: options.readOnly === true,
|
|
54
|
+
user: options.user && Promise.resolve(options.user)
|
|
55
|
+
}, fn);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Throws inside a read-only {@link withSessionToken} scope. Every SDK call that
|
|
59
|
+
* changes data, sends something or signs somebody in calls it first.
|
|
60
|
+
*
|
|
61
|
+
* An MCP tool marked read-only runs in such a scope. So an assistant the user
|
|
62
|
+
* approved to read only can't change data through those calls, whatever the
|
|
63
|
+
* tool's code does. The SDK `mcp` skill lists what is covered and what is not.
|
|
64
|
+
*/
|
|
65
|
+
function assertCanChange(what) {
|
|
66
|
+
if (standIn.getStore()?.readOnly === true) panic(`${what} is not allowed in a read-only tool.`);
|
|
52
67
|
}
|
|
53
68
|
/**
|
|
54
69
|
* The visitor of the token that {@link withSessionToken} stands in, fetched once
|
|
@@ -284,4 +299,4 @@ function openEnvelope(raw, purpose) {
|
|
|
284
299
|
}
|
|
285
300
|
|
|
286
301
|
//#endregion
|
|
287
|
-
export { clearPendingAuth, clearSession, clearSessionData, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readFreshUser, readPendingAuthToken, readSessionData, readSessionToken, readSsoBinding, readStandInUser, withSessionToken };
|
|
302
|
+
export { assertCanChange, clearPendingAuth, clearSession, clearSessionData, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readFreshUser, readPendingAuthToken, readSessionData, readSessionToken, readSsoBinding, readStandInUser, withSessionToken };
|
package/dist/core/email.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { softrApiUrl } from "../softr-api.js";
|
|
2
2
|
import { fetch } from "../fetch.js";
|
|
3
3
|
import { sessionConfig } from "../auth/config.js";
|
|
4
|
-
import { readSessionToken } from "../auth/session.js";
|
|
4
|
+
import { assertCanChange, readSessionToken } from "../auth/session.js";
|
|
5
5
|
|
|
6
6
|
//#region src/core/email.ts
|
|
7
7
|
const EMAIL_ERROR_CODES = [
|
|
@@ -46,6 +46,7 @@ var EmailError = class extends Error {
|
|
|
46
46
|
};
|
|
47
47
|
/** Sends one email through the action. Never retries by itself. */
|
|
48
48
|
async function sendEmail(action, init) {
|
|
49
|
+
assertCanChange(`Email "${action.id}"`);
|
|
49
50
|
const { to, cc, bcc, replyTo, subject, body } = init;
|
|
50
51
|
const sessionToken = readSessionToken();
|
|
51
52
|
let res;
|
package/dist/core/file-upload.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { softrApiUrl } from "../softr-api.js";
|
|
2
2
|
import { fetch } from "../fetch.js";
|
|
3
3
|
import { sessionConfig } from "../auth/config.js";
|
|
4
|
-
import { readSessionToken } from "../auth/session.js";
|
|
4
|
+
import { assertCanChange, readSessionToken } from "../auth/session.js";
|
|
5
5
|
import { describeFailure } from "../datasource/record.js";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
|
|
8
8
|
//#region src/core/file-upload.ts
|
|
9
9
|
async function upload(action, file) {
|
|
10
|
+
assertCanChange(`Upload "${action.id}"`);
|
|
10
11
|
const { applicationId } = sessionConfig();
|
|
11
12
|
const baseUrl = softrApiUrl("SOFTR_PLATFORM_API_URL");
|
|
12
13
|
const uploadUrl = new URL(`${baseUrl}/v1/vibe/applications/${applicationId}/actions/${action.id}/uploads`);
|
package/dist/core/integration.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { fetch } from "../fetch.js";
|
|
2
|
-
import { readSessionToken } from "../auth/session.js";
|
|
2
|
+
import { assertCanChange, readSessionToken } from "../auth/session.js";
|
|
3
3
|
import { dsUrl, refererHeader } from "../datasource/record.js";
|
|
4
4
|
|
|
5
5
|
//#region src/core/integration.ts
|
|
6
6
|
async function integrationFetch(action, { params, query, headers = {}, body, signal } = {}) {
|
|
7
7
|
if (signal?.aborted) throw signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
8
|
+
const method = action.resource.method;
|
|
9
|
+
if (method !== "GET" && method !== "HEAD") assertCanChange(`Integration "${action.id}"`);
|
|
8
10
|
const payload = {
|
|
9
|
-
method
|
|
11
|
+
method,
|
|
10
12
|
url: buildUrl(action.resource.url, params, query),
|
|
11
13
|
headers
|
|
12
14
|
};
|
package/dist/core/workflow.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { softrApiUrl } from "../softr-api.js";
|
|
2
2
|
import { fetch } from "../fetch.js";
|
|
3
3
|
import { sessionConfig } from "../auth/config.js";
|
|
4
|
-
import { readSessionToken } from "../auth/session.js";
|
|
4
|
+
import { assertCanChange, readSessionToken } from "../auth/session.js";
|
|
5
5
|
import { describeFailure } from "../datasource/record.js";
|
|
6
6
|
|
|
7
7
|
//#region src/core/workflow.ts
|
|
8
8
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
9
9
|
async function triggerWorkflow(action, payload) {
|
|
10
|
+
assertCanChange(`Workflow "${action.id}"`);
|
|
10
11
|
const triggerRes = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${sessionConfig().applicationId}/actions/${action.id}/workflow`, {
|
|
11
12
|
method: "POST",
|
|
12
13
|
headers: {
|
|
@@ -3,7 +3,7 @@ import { softrApiUrl } from "../softr-api.js";
|
|
|
3
3
|
import { fetch } from "../fetch.js";
|
|
4
4
|
import { softrConfig } from "../softr-config.js";
|
|
5
5
|
import { readUserTimezone } from "../cookies.js";
|
|
6
|
-
import { readFreshUser, readSessionToken, readStandInUser } from "../auth/session.js";
|
|
6
|
+
import { assertCanChange, readFreshUser, readSessionToken, readStandInUser } from "../auth/session.js";
|
|
7
7
|
import { andGroups, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
|
|
8
8
|
import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
|
|
9
9
|
import { filterForVisitor, readsVisitor } from "./enforced-filter.js";
|
|
@@ -283,6 +283,7 @@ async function executeGet(query, id, filters) {
|
|
|
283
283
|
* })
|
|
284
284
|
*/
|
|
285
285
|
async function createRecord(action, options) {
|
|
286
|
+
assertCanChange(`ds.create "${action.id}"`);
|
|
286
287
|
const { actionId, select } = resolveTarget(action, "create");
|
|
287
288
|
const data = options.data;
|
|
288
289
|
const rawFields = dealiasData(data, select);
|
|
@@ -313,6 +314,7 @@ async function createRecord(action, options) {
|
|
|
313
314
|
* })
|
|
314
315
|
*/
|
|
315
316
|
async function updateRecord(action, options) {
|
|
317
|
+
assertCanChange(`ds.update "${action.id}"`);
|
|
316
318
|
if (!options.id) throw new Error(`datasource update: id must not be empty`);
|
|
317
319
|
const target = resolveTarget(action, "update");
|
|
318
320
|
const { actionId, select } = target;
|
|
@@ -343,6 +345,7 @@ async function updateRecord(action, options) {
|
|
|
343
345
|
* await ds.delete(removePost, { id: "record-id" })
|
|
344
346
|
*/
|
|
345
347
|
async function deleteRecord(action, options) {
|
|
348
|
+
assertCanChange(`ds.delete "${action.id}"`);
|
|
346
349
|
const target = resolveTarget(action, "delete");
|
|
347
350
|
const { actionId } = target;
|
|
348
351
|
await requireFilterMatch(target, options.id, "delete");
|
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { toReturnPath } from "./auth/returnPath.js";
|
|
|
14
14
|
import { SsoError, ssoSignInHref } from "./auth/sso.js";
|
|
15
15
|
import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
16
16
|
import { useIdleTimeout } from "./auth/idle-timeout.js";
|
|
17
|
+
import { Tool, ToolDefinition, defineTool } from "./tool.js";
|
|
17
18
|
import { softrMcpMiddleware } from "./mcp.js";
|
|
18
19
|
import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
19
20
|
import { useOverrides } from "./core/use-overrides.js";
|
|
@@ -24,4 +25,4 @@ import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
|
24
25
|
import { Audience } from "./route/audience.js";
|
|
25
26
|
import { Logo, LogoFile } from "./softr-config.schema.js";
|
|
26
27
|
import { getLogo } from "./softr-config.js";
|
|
27
|
-
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
|
28
|
+
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,7 @@ import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
|
11
11
|
import { usePushNotifications } from "./push.js";
|
|
12
12
|
import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
13
13
|
import { useIdleTimeout } from "./auth/idle-timeout.js";
|
|
14
|
+
import { defineTool } from "./tool.js";
|
|
14
15
|
import { softrMcpMiddleware } from "./mcp.js";
|
|
15
16
|
import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
16
17
|
import { useOverrides } from "./core/use-overrides.js";
|
|
@@ -18,4 +19,4 @@ import { useUserTimezone } from "./timezone.js";
|
|
|
18
19
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
19
20
|
import { Audience } from "./route/audience.js";
|
|
20
21
|
|
|
21
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
|
22
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DatasourceAction } from "./action.js";
|
|
2
|
+
import { Tool } from "./tool.js";
|
|
2
3
|
import * as _tanstack_react_start10 from "@tanstack/react-start";
|
|
3
4
|
|
|
4
5
|
//#region src/mcp.d.ts
|
|
@@ -12,6 +13,11 @@ type SoftrMcpOptions = {
|
|
|
12
13
|
* decide who may run the ones that are listed.
|
|
13
14
|
*/
|
|
14
15
|
actions?: Array<DatasourceAction>;
|
|
16
|
+
/**
|
|
17
|
+
* Tools that run the app's own logic, from `defineTool`. Listed the same way
|
|
18
|
+
* as `actions`, and their names share one namespace with the action ids.
|
|
19
|
+
*/
|
|
20
|
+
tools?: Array<Tool>;
|
|
15
21
|
};
|
|
16
22
|
/**
|
|
17
23
|
* Serves the MCP endpoint and its OAuth flow from the app's own origin.
|
|
@@ -22,11 +28,12 @@ type SoftrMcpOptions = {
|
|
|
22
28
|
* request. Everything else passes straight through.
|
|
23
29
|
*
|
|
24
30
|
* @example
|
|
25
|
-
* import { publishedPosts
|
|
31
|
+
* import { publishedPosts } from './actions'
|
|
32
|
+
* import { createIssue } from './mcp-tools'
|
|
26
33
|
*
|
|
27
34
|
* export const startInstance = createStart(() => ({
|
|
28
35
|
* requestMiddleware: [
|
|
29
|
-
* softrMcpMiddleware({ actions: [publishedPosts,
|
|
36
|
+
* softrMcpMiddleware({ actions: [publishedPosts], tools: [createIssue] }),
|
|
30
37
|
* softrAuthMiddleware(),
|
|
31
38
|
* ],
|
|
32
39
|
* }))
|
package/dist/mcp.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assert } from "./assertions.js";
|
|
2
|
+
import { logger } from "./logger.js";
|
|
2
3
|
import { softrApiUrl } from "./softr-api.js";
|
|
3
4
|
import { fetch } from "./fetch.js";
|
|
4
5
|
import { softrConfig } from "./softr-config.js";
|
|
@@ -7,6 +8,7 @@ import { makePlatform } from "./auth/platform.js";
|
|
|
7
8
|
import { readSessionToken, withSessionToken } from "./auth/session.js";
|
|
8
9
|
import { isDatasourceAction } from "./action.js";
|
|
9
10
|
import { ds } from "./datasource/datasource.js";
|
|
11
|
+
import { isTool } from "./tool.js";
|
|
10
12
|
import { z } from "zod";
|
|
11
13
|
import { createMiddleware } from "@tanstack/react-start";
|
|
12
14
|
|
|
@@ -33,23 +35,36 @@ const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"];
|
|
|
33
35
|
* request. Everything else passes straight through.
|
|
34
36
|
*
|
|
35
37
|
* @example
|
|
36
|
-
* import { publishedPosts
|
|
38
|
+
* import { publishedPosts } from './actions'
|
|
39
|
+
* import { createIssue } from './mcp-tools'
|
|
37
40
|
*
|
|
38
41
|
* export const startInstance = createStart(() => ({
|
|
39
42
|
* requestMiddleware: [
|
|
40
|
-
* softrMcpMiddleware({ actions: [publishedPosts,
|
|
43
|
+
* softrMcpMiddleware({ actions: [publishedPosts], tools: [createIssue] }),
|
|
41
44
|
* softrAuthMiddleware(),
|
|
42
45
|
* ],
|
|
43
46
|
* }))
|
|
44
47
|
*/
|
|
45
48
|
function softrMcpMiddleware(options = {}) {
|
|
46
49
|
const login = softrConfig().auth.routes.login;
|
|
47
|
-
const
|
|
50
|
+
const entries = /* @__PURE__ */ new Map();
|
|
48
51
|
for (const action of options.actions ?? []) {
|
|
49
52
|
assert(isDatasourceAction(action), "softrMcpMiddleware takes actions built by defineQuery or defineMutation");
|
|
50
53
|
const value = action;
|
|
51
|
-
assert(!
|
|
52
|
-
|
|
54
|
+
assert(!entries.has(value.id), `two actions share the id "${value.id}"`);
|
|
55
|
+
entries.set(value.id, {
|
|
56
|
+
kind: "action",
|
|
57
|
+
value
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
for (const tool of options.tools ?? []) {
|
|
61
|
+
assert(isTool(tool), "softrMcpMiddleware takes tools built by defineTool");
|
|
62
|
+
const value = tool;
|
|
63
|
+
assert(value.name !== WHOAMI.name && !entries.has(value.name), `two tools share the name "${value.name}"`);
|
|
64
|
+
entries.set(value.name, {
|
|
65
|
+
kind: "tool",
|
|
66
|
+
value
|
|
67
|
+
});
|
|
53
68
|
}
|
|
54
69
|
return createMiddleware({ type: "request" }).server(async ({ next, request }) => {
|
|
55
70
|
const url = new URL(request.url);
|
|
@@ -74,7 +89,7 @@ function softrMcpMiddleware(options = {}) {
|
|
|
74
89
|
});
|
|
75
90
|
case AUTHORIZE_PATH: return await authorize(request, login);
|
|
76
91
|
case TOKEN_PATH: return await issueToken(request);
|
|
77
|
-
case MCP_PATH: return await rpc(request, origin,
|
|
92
|
+
case MCP_PATH: return await rpc(request, origin, entries);
|
|
78
93
|
default: return await next();
|
|
79
94
|
}
|
|
80
95
|
});
|
|
@@ -249,16 +264,22 @@ async function platformSession(accessToken) {
|
|
|
249
264
|
const WHOAMI = {
|
|
250
265
|
name: "whoami",
|
|
251
266
|
title: "Who am I",
|
|
252
|
-
description: "Returns the Softr user this connection is authenticated as: their name, email and user
|
|
267
|
+
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.",
|
|
253
268
|
inputSchema: {
|
|
254
269
|
type: "object",
|
|
255
270
|
properties: {},
|
|
256
271
|
additionalProperties: false
|
|
257
|
-
}
|
|
272
|
+
},
|
|
273
|
+
annotations: { readOnlyHint: true }
|
|
258
274
|
};
|
|
259
275
|
/** How many records a read returns when the caller does not say. */
|
|
260
276
|
const DEFAULT_LIMIT = 20;
|
|
261
277
|
const MAX_LIMIT = 100;
|
|
278
|
+
/** Whether the tool only reads. A read-only grant may run only these. */
|
|
279
|
+
function isReadOnly(entry) {
|
|
280
|
+
if (entry.kind === "action") return entry.value.resource.operation === "read";
|
|
281
|
+
return entry.value.readOnly;
|
|
282
|
+
}
|
|
262
283
|
/**
|
|
263
284
|
* One tool per action the app chose to expose.
|
|
264
285
|
*
|
|
@@ -274,6 +295,7 @@ function describeTool(action) {
|
|
|
274
295
|
switch (operation) {
|
|
275
296
|
case "read": return {
|
|
276
297
|
name: action.id,
|
|
298
|
+
annotations: { readOnlyHint: true },
|
|
277
299
|
description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
|
|
278
300
|
inputSchema: {
|
|
279
301
|
type: "object",
|
|
@@ -295,6 +317,10 @@ function describeTool(action) {
|
|
|
295
317
|
};
|
|
296
318
|
case "create": return {
|
|
297
319
|
name: action.id,
|
|
320
|
+
annotations: {
|
|
321
|
+
readOnlyHint: false,
|
|
322
|
+
destructiveHint: false
|
|
323
|
+
},
|
|
298
324
|
description: `Create a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
|
|
299
325
|
inputSchema: {
|
|
300
326
|
type: "object",
|
|
@@ -304,6 +330,10 @@ function describeTool(action) {
|
|
|
304
330
|
};
|
|
305
331
|
case "update": return {
|
|
306
332
|
name: action.id,
|
|
333
|
+
annotations: {
|
|
334
|
+
readOnlyHint: false,
|
|
335
|
+
destructiveHint: true
|
|
336
|
+
},
|
|
307
337
|
description: `Update a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
|
|
308
338
|
inputSchema: {
|
|
309
339
|
type: "object",
|
|
@@ -320,6 +350,10 @@ function describeTool(action) {
|
|
|
320
350
|
};
|
|
321
351
|
case "delete": return {
|
|
322
352
|
name: action.id,
|
|
353
|
+
annotations: {
|
|
354
|
+
readOnlyHint: false,
|
|
355
|
+
destructiveHint: true
|
|
356
|
+
},
|
|
323
357
|
description: `Delete a record with "${action.id}".`,
|
|
324
358
|
inputSchema: {
|
|
325
359
|
type: "object",
|
|
@@ -391,14 +425,14 @@ function clampOffset(raw) {
|
|
|
391
425
|
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) return null;
|
|
392
426
|
return raw;
|
|
393
427
|
}
|
|
394
|
-
async function rpc(request, origin,
|
|
428
|
+
async function rpc(request, origin, entries) {
|
|
395
429
|
if (request.method !== "POST") return methodNotAllowed("POST");
|
|
396
430
|
const token = bearerToken(request);
|
|
397
431
|
if (token === null) return unauthorized(origin);
|
|
398
432
|
const session = await platformSession(token);
|
|
399
433
|
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
|
|
400
434
|
const { sessionToken, canWrite } = session;
|
|
401
|
-
const allowed = (
|
|
435
|
+
const allowed = (entry) => canWrite || isReadOnly(entry);
|
|
402
436
|
const body = await readJson(request);
|
|
403
437
|
const message = z.object({
|
|
404
438
|
id: z.union([z.string(), z.number()]).optional(),
|
|
@@ -427,27 +461,71 @@ async function rpc(request, origin, actions) {
|
|
|
427
461
|
}
|
|
428
462
|
});
|
|
429
463
|
}
|
|
430
|
-
case "tools/list": return result(id, { tools: [WHOAMI, ...[...
|
|
464
|
+
case "tools/list": return result(id, { tools: [WHOAMI, ...[...entries.values()].filter(allowed).map((entry) => {
|
|
465
|
+
if (entry.kind === "action") return describeTool(entry.value);
|
|
466
|
+
const { name, title, description, inputSchema, readOnly, destructive } = entry.value;
|
|
467
|
+
return {
|
|
468
|
+
name,
|
|
469
|
+
...title === void 0 ? {} : { title },
|
|
470
|
+
description,
|
|
471
|
+
inputSchema,
|
|
472
|
+
annotations: readOnly ? { readOnlyHint: true } : {
|
|
473
|
+
readOnlyHint: false,
|
|
474
|
+
...destructive === void 0 ? {} : { destructiveHint: destructive }
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
})] });
|
|
431
478
|
case "tools/call": {
|
|
432
479
|
const name = params?.name;
|
|
433
480
|
const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
434
481
|
if (name === WHOAMI.name) {
|
|
435
|
-
const
|
|
482
|
+
const { applicationId } = sessionConfig();
|
|
483
|
+
const session$1 = await makePlatform(applicationId).sessionWithGroupNames(sessionToken);
|
|
484
|
+
if (!session$1.ok && session$1.status !== 401 && session$1.status !== 403) return unavailable();
|
|
485
|
+
const user = session$1.ok ? session$1.data.user : null;
|
|
436
486
|
if (user === null) return unauthorized(origin);
|
|
437
487
|
return result(id, toolResult(user));
|
|
438
488
|
}
|
|
439
|
-
const
|
|
440
|
-
if (
|
|
441
|
-
if (!allowed(
|
|
489
|
+
const entry = typeof name === "string" ? entries.get(name) : void 0;
|
|
490
|
+
if (entry === void 0) return failure(id, -32602, `Unknown tool: ${String(name)}`);
|
|
491
|
+
if (!allowed(entry)) return result(id, {
|
|
442
492
|
isError: true,
|
|
443
493
|
content: [{
|
|
444
494
|
type: "text",
|
|
445
|
-
text: `"${
|
|
495
|
+
text: `"${name}" changes data, and this assistant's connection allows reading only, so it cannot run it.`
|
|
446
496
|
}]
|
|
447
497
|
});
|
|
448
498
|
try {
|
|
449
|
-
|
|
499
|
+
let run;
|
|
500
|
+
let user;
|
|
501
|
+
if (entry.kind === "action") run = () => runTool(entry.value, args);
|
|
502
|
+
else {
|
|
503
|
+
const input = await entry.value.input.safeParseAsync(args);
|
|
504
|
+
if (!input.success) return result(id, {
|
|
505
|
+
isError: true,
|
|
506
|
+
content: [{
|
|
507
|
+
type: "text",
|
|
508
|
+
text: ["The arguments are not valid:", ...input.error.issues.map((issue) => {
|
|
509
|
+
const path = issue.path.join(".");
|
|
510
|
+
return path === "" ? `- ${issue.message}` : `- ${path}: ${issue.message}`;
|
|
511
|
+
})].join("\n")
|
|
512
|
+
}]
|
|
513
|
+
});
|
|
514
|
+
const { applicationId } = sessionConfig();
|
|
515
|
+
const lookup = await makePlatform(applicationId).session(sessionToken);
|
|
516
|
+
if (!lookup.ok && lookup.status !== 401 && lookup.status !== 403) return unavailable();
|
|
517
|
+
const found = lookup.ok ? lookup.data.user : null;
|
|
518
|
+
if (found === null) return unauthorized(origin);
|
|
519
|
+
user = found;
|
|
520
|
+
run = () => entry.value.handler(input.data, { user: found });
|
|
521
|
+
}
|
|
522
|
+
return result(id, toolResult(await withSessionToken(sessionToken, run, {
|
|
523
|
+
readOnly: isReadOnly(entry),
|
|
524
|
+
user
|
|
525
|
+
})));
|
|
450
526
|
} catch (error) {
|
|
527
|
+
if (entry.kind === "tool") console.error(`[@softr/sdk] MCP tool "${entry.value.name}" failed:`, error);
|
|
528
|
+
else logger.error("MCP tool failed", error);
|
|
451
529
|
return result(id, {
|
|
452
530
|
isError: true,
|
|
453
531
|
content: [{
|
|
@@ -461,13 +539,15 @@ async function rpc(request, origin, actions) {
|
|
|
461
539
|
}
|
|
462
540
|
}
|
|
463
541
|
function toolResult(output) {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
542
|
+
const content = [{
|
|
543
|
+
type: "text",
|
|
544
|
+
text: output === void 0 ? "Done." : JSON.stringify(output, null, 2)
|
|
545
|
+
}];
|
|
546
|
+
if (typeof output === "object" && output !== null && !Array.isArray(output)) return {
|
|
547
|
+
content,
|
|
469
548
|
structuredContent: output
|
|
470
549
|
};
|
|
550
|
+
return { content };
|
|
471
551
|
}
|
|
472
552
|
function result(id, payload) {
|
|
473
553
|
return json({
|
package/dist/package.js
CHANGED
package/dist/tool.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { User } from "./auth/user.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/tool.d.ts
|
|
5
|
+
declare const TOOL: unique symbol;
|
|
6
|
+
/** A tool from {@link defineTool}, ready for `softrMcpMiddleware({ tools })`. */
|
|
7
|
+
type Tool = {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly [TOOL]: true;
|
|
10
|
+
};
|
|
11
|
+
type ToolDefinition<TInput extends z.ZodObject, TOutput> = {
|
|
12
|
+
/** What the assistant calls it, e.g. `create_issue`. Letters, digits, `_`, `-` and `.`. */
|
|
13
|
+
name: string;
|
|
14
|
+
/** A short name for people, e.g. "Create issue". */
|
|
15
|
+
title?: string;
|
|
16
|
+
/** What the tool does and when to use it. The assistant picks tools by this. */
|
|
17
|
+
description: string;
|
|
18
|
+
/**
|
|
19
|
+
* The arguments. Describe each field with `.describe()`: the assistant reads it.
|
|
20
|
+
* Top-level keys the schema does not name are refused, not dropped. A nested
|
|
21
|
+
* object drops them, unless it is a `z.strictObject`.
|
|
22
|
+
*/
|
|
23
|
+
input: TInput;
|
|
24
|
+
/**
|
|
25
|
+
* `true` when the tool only reads. Required, so every tool says which it is.
|
|
26
|
+
*
|
|
27
|
+
* The SDK calls that change data or send something fail inside a read-only
|
|
28
|
+
* tool. It is the only kind an assistant the user approved to read only may call.
|
|
29
|
+
*/
|
|
30
|
+
readOnly: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* `true` when the tool deletes or overwrites data, `false` when it only adds.
|
|
33
|
+
* Only for a tool that is not read-only.
|
|
34
|
+
*
|
|
35
|
+
* Left out, the assistant is told neither, and treats the tool as one that
|
|
36
|
+
* may delete or overwrite.
|
|
37
|
+
*/
|
|
38
|
+
destructive?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Runs the tool as the signed-in user. `ds` calls inside it act as that user,
|
|
41
|
+
* with their groups, as a click in the app would. Return JSON.
|
|
42
|
+
*/
|
|
43
|
+
handler: (input: z.output<TInput>, context: {
|
|
44
|
+
user: User;
|
|
45
|
+
}) => Promise<TOutput>;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* An MCP tool that runs the app's own logic, for `softrMcpMiddleware({ tools })`.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* export const createIssue = defineTool({
|
|
52
|
+
* name: 'create_issue',
|
|
53
|
+
* description: 'Create an issue in a project. Returns the new issue with its key.',
|
|
54
|
+
* input: z.object({
|
|
55
|
+
* projectId: z.string().describe('The project record id.'),
|
|
56
|
+
* title: z.string().describe('A one-line summary.'),
|
|
57
|
+
* }),
|
|
58
|
+
* readOnly: false,
|
|
59
|
+
* handler: async (input, { user }) => createIssueFor(user, input),
|
|
60
|
+
* })
|
|
61
|
+
*/
|
|
62
|
+
declare function defineTool<TInput extends z.ZodObject, TOutput>(definition: ToolDefinition<TInput, TOutput>): Tool;
|
|
63
|
+
//#endregion
|
|
64
|
+
export { Tool, ToolDefinition, defineTool };
|
package/dist/tool.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { assert, panic } from "./assertions.js";
|
|
2
|
+
|
|
3
|
+
//#region src/tool.ts
|
|
4
|
+
const TOOL = Symbol.for("@softr/sdk/tool");
|
|
5
|
+
/** What the MCP spec allows in a tool name. */
|
|
6
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
7
|
+
/**
|
|
8
|
+
* An MCP tool that runs the app's own logic, for `softrMcpMiddleware({ tools })`.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* export const createIssue = defineTool({
|
|
12
|
+
* name: 'create_issue',
|
|
13
|
+
* description: 'Create an issue in a project. Returns the new issue with its key.',
|
|
14
|
+
* input: z.object({
|
|
15
|
+
* projectId: z.string().describe('The project record id.'),
|
|
16
|
+
* title: z.string().describe('A one-line summary.'),
|
|
17
|
+
* }),
|
|
18
|
+
* readOnly: false,
|
|
19
|
+
* handler: async (input, { user }) => createIssueFor(user, input),
|
|
20
|
+
* })
|
|
21
|
+
*/
|
|
22
|
+
function defineTool(definition) {
|
|
23
|
+
const { name, title, description, input, readOnly, destructive, handler } = definition;
|
|
24
|
+
assert(TOOL_NAME.test(name), () => `defineTool "${name}": a name is 1 to 128 letters, digits, "_", "-" or ".".`);
|
|
25
|
+
assert(description.trim() !== "", () => `defineTool "${name}": the description must not be empty.`);
|
|
26
|
+
assert(!(readOnly && destructive === true), () => `defineTool "${name}": a read-only tool cannot be destructive.`);
|
|
27
|
+
const strict = input.strict();
|
|
28
|
+
let inputSchema;
|
|
29
|
+
try {
|
|
30
|
+
inputSchema = strict["~standard"].jsonSchema.input({ target: "draft-07" });
|
|
31
|
+
} catch (error) {
|
|
32
|
+
panic(`defineTool "${name}": the input cannot be described to an assistant. ${error instanceof Error ? error.message : String(error)}`);
|
|
33
|
+
}
|
|
34
|
+
const value = {
|
|
35
|
+
name,
|
|
36
|
+
title,
|
|
37
|
+
description,
|
|
38
|
+
input: strict,
|
|
39
|
+
inputSchema,
|
|
40
|
+
readOnly,
|
|
41
|
+
destructive,
|
|
42
|
+
handler
|
|
43
|
+
};
|
|
44
|
+
return Object.assign(value, { [TOOL]: true });
|
|
45
|
+
}
|
|
46
|
+
function isTool(value) {
|
|
47
|
+
return typeof value === "object" && value !== null && TOOL in value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { defineTool, isTool };
|
package/package.json
CHANGED
|
@@ -13,7 +13,7 @@ description: >-
|
|
|
13
13
|
metadata:
|
|
14
14
|
type: sub-skill
|
|
15
15
|
library: softr-sdk
|
|
16
|
-
library_version: 1.
|
|
16
|
+
library_version: 1.15.0
|
|
17
17
|
---
|
|
18
18
|
|
|
19
19
|
**Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -10,7 +10,7 @@ description: >-
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: sub-skill
|
|
12
12
|
library: softr-sdk
|
|
13
|
-
library_version: 1.
|
|
13
|
+
library_version: 1.15.0
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
**Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
|
|
@@ -10,7 +10,7 @@ description: >-
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: sub-skill
|
|
12
12
|
library: softr-sdk
|
|
13
|
-
library_version: 1.
|
|
13
|
+
library_version: 1.15.0
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A helper that calls `ds` outside a handler goes in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary). `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -12,7 +12,7 @@ description: >-
|
|
|
12
12
|
metadata:
|
|
13
13
|
type: sub-skill
|
|
14
14
|
library: softr-sdk
|
|
15
|
-
library_version: 1.
|
|
15
|
+
library_version: 1.15.0
|
|
16
16
|
---
|
|
17
17
|
|
|
18
18
|
**Boundary.** `email` and `EmailError` live on `@softr/sdk/server` and run only inside a `createServerFn` handler — importing them into a component fails the build. `defineEmailAction` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 1.
|
|
10
|
+
library_version: 1.15.0
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 1.
|
|
10
|
+
library_version: 1.15.0
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: mcp
|
|
3
3
|
description: >-
|
|
4
|
-
Open the app to AI assistants over MCP: softrMcpMiddleware({ actions })
|
|
5
|
-
@softr/sdk, registered in src/start.ts ahead of softrAuthMiddleware,
|
|
6
|
-
actions you list into tools an assistant can
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
Open the app to AI assistants over MCP: softrMcpMiddleware({ actions, tools })
|
|
5
|
+
from @softr/sdk, registered in src/start.ts ahead of softrAuthMiddleware,
|
|
6
|
+
turns the actions and defineTool tools you list into tools an assistant can
|
|
7
|
+
call as the signed-in visitor. defineTool runs the app's own logic, labelled
|
|
8
|
+
read-only or not. The list is explicit — anything left out is invisible over
|
|
9
|
+
MCP. The app's own login must land on toReturnPath, or the approval step
|
|
10
|
+
dead-ends.
|
|
9
11
|
metadata:
|
|
10
12
|
type: sub-skill
|
|
11
13
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
14
|
+
library_version: 1.15.0
|
|
13
15
|
---
|
|
14
16
|
|
|
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.
|
|
17
|
+
**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. The tools you hand it come from `defineTool`, also on `@softr/sdk`, and call the same server logic the pages do.
|
|
16
18
|
|
|
17
19
|
# MCP
|
|
18
20
|
|
|
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.
|
|
21
|
+
An app can answer an AI assistant on its own origin. The assistant signs in as an ordinary app user, and the actions and tools 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
22
|
|
|
21
23
|
## The URL
|
|
22
24
|
|
|
@@ -34,12 +36,13 @@ Custom domain, default subdomain, a staging host — whatever origin the app is
|
|
|
34
36
|
// src/start.ts
|
|
35
37
|
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'
|
|
36
38
|
import { softrAuthMiddleware, softrMcpMiddleware } from '@softr/sdk'
|
|
37
|
-
import { listCafes
|
|
39
|
+
import { listCafes } from './actions'
|
|
40
|
+
import { addCafe, findCafes } from './mcp-tools'
|
|
38
41
|
|
|
39
42
|
export const startInstance = createStart(() => ({
|
|
40
43
|
requestMiddleware: [
|
|
41
44
|
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
|
|
42
|
-
softrMcpMiddleware({ actions: [listCafes, addCafe] }),
|
|
45
|
+
softrMcpMiddleware({ actions: [listCafes], tools: [findCafes, addCafe] }),
|
|
43
46
|
softrAuthMiddleware(),
|
|
44
47
|
],
|
|
45
48
|
}))
|
|
@@ -47,16 +50,66 @@ export const startInstance = createStart(() => ({
|
|
|
47
50
|
|
|
48
51
|
Order is part of the contract. `softrMcpMiddleware` goes **before** `softrAuthMiddleware`, and that is the only order it supports.
|
|
49
52
|
|
|
50
|
-
##
|
|
53
|
+
## Tools from the app's own logic
|
|
54
|
+
|
|
55
|
+
An action is one list, create, update or delete on one datasource. When the app does more than that — a number from a counter, an activity log entry, an email, an author stamped on the record — a tool built from the action skips it. Use `defineTool` and call the logic the app's pages already run:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
// src/mcp-tools.ts
|
|
59
|
+
import { defineTool } from '@softr/sdk'
|
|
60
|
+
import { ds } from '@softr/sdk/server'
|
|
61
|
+
import { z } from 'zod'
|
|
62
|
+
import { createIssueFor } from './issues'
|
|
63
|
+
import { projectIssues } from './actions'
|
|
64
|
+
|
|
65
|
+
export const createIssue = defineTool({
|
|
66
|
+
name: 'create_issue',
|
|
67
|
+
title: 'Create issue',
|
|
68
|
+
description: 'Create an issue in a project. Returns the new issue with its key.',
|
|
69
|
+
input: z.object({
|
|
70
|
+
projectId: z.string().describe('The project record id.'),
|
|
71
|
+
title: z.string().describe('A one-line summary.'),
|
|
72
|
+
}),
|
|
73
|
+
readOnly: false,
|
|
74
|
+
destructive: false,
|
|
75
|
+
handler: async (input, { user }) => createIssueFor(user, input),
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
export const findIssues = defineTool({
|
|
79
|
+
name: 'find_issues',
|
|
80
|
+
description: 'Issues in a project, newest first. Filter by status.',
|
|
81
|
+
input: z.object({
|
|
82
|
+
projectId: z.string().describe('The project record id.'),
|
|
83
|
+
status: z.enum(['open', 'done']).optional().describe('Only issues with this status.'),
|
|
84
|
+
}),
|
|
85
|
+
readOnly: true,
|
|
86
|
+
handler: async (input) => {
|
|
87
|
+
let list = ds.list(projectIssues).where((q) => q.project.isOneOf([input.projectId]))
|
|
88
|
+
if (input.status) list = list.where((q) => q.status.is(input.status))
|
|
89
|
+
const { records } = await list.orderBy((q) => q.createdAt.desc).limit(50)
|
|
90
|
+
return { issues: records.map((r) => ({ id: r.id, ...r.fields })) }
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
- **`handler` runs as the signed-in user.** `ds` calls inside it act as that user, with their groups, as a click in the app would. `user` is the same `User` a server function reads from `context.user`. Move logic a server function and a tool share into a function that takes the user, and pass `context.user` from the server function and `user` from the tool.
|
|
96
|
+
- **`readOnly` is required.** `true` only when the tool changes nothing. A read-only tool that calls `ds.create`, `ds.update`, `ds.delete`, `email`, `workflow`, `upload` or an `integration` action whose method is not `GET` or `HEAD` from `@softr/sdk/server` fails with an error, and nothing is written or sent. An integration that reads with `POST`, such as a search or GraphQL API, fails too: make that tool `readOnly: false`. So does every `auth` call that is not a plain read: a sign-in, a sign-up, a password reset, a sign-out, a profile change or an authenticator change. Your own calls to other services are not stopped, so keep them out of a read-only tool too. An `ai` call is not stopped either: it changes no data, but it spends the workspace's AI credits for an assistant approved to read only, so use it there on purpose.
|
|
97
|
+
- **`destructive`** says whether a tool that is not read-only deletes or overwrites data: `true` when it does, `false` when it only adds. The assistant may ask the user before it runs a destructive one. Left out, the assistant is told neither and treats the tool as one that may delete or overwrite, so set it on every tool that is not read-only.
|
|
98
|
+
- **`input` is a zod object.** Describe each field with `.describe()`: the assistant reads it. Use types JSON can carry: a string for a date, not `z.date()`, which fails when the tool is defined. A top-level argument the schema does not name is refused with a message saying which, and the handler does not run. Inside a nested object an unknown key is dropped without a word, so declare a nested object with `z.strictObject` to have it refused too.
|
|
99
|
+
- **`description` says what the tool does and when to use it.** The assistant picks tools by it.
|
|
100
|
+
- **Return JSON.** An object is best: the assistant gets it as structured data.
|
|
101
|
+
- **What the handler throws is shown to the assistant.** Throw an `Error` whose message says what went wrong in words the assistant can act on. The message of any other throw reaches it too, so catch a failed call to another service and throw your own message, not one that may carry a URL or a key.
|
|
102
|
+
|
|
103
|
+
## Choosing the tools
|
|
51
104
|
|
|
52
105
|
The list is the whole tool surface. Write it out:
|
|
53
106
|
|
|
54
|
-
- An action you leave out is invisible to the assistant, even where the app's pages use it freely.
|
|
55
|
-
- An action you list still obeys its own `permissions
|
|
56
|
-
-
|
|
57
|
-
- Two actions with the same `id` throw at startup. So does anything that is not a `defineQuery` or `
|
|
107
|
+
- An action or tool you leave out is invisible to the assistant, even where the app's pages use it freely.
|
|
108
|
+
- An action you list still obeys its own `permissions`, and a tool's `ds` calls obey theirs. Listing it does not widen who may run it — the assistant runs as whoever signed in, with that user's groups.
|
|
109
|
+
- Anything that changes data reaches only an assistant the user allowed to make changes when they connected it. One allowed to read only sees the reads, the read-only tools and `whoami`.
|
|
110
|
+
- Two actions with the same `id` throw at startup, and so does a tool whose `name` is taken. So does anything that is not a `defineQuery`, `defineMutation` or `defineTool` value.
|
|
58
111
|
|
|
59
|
-
|
|
112
|
+
Name every tool back to the owner, saying which ones may change data.
|
|
60
113
|
|
|
61
114
|
## The login round trip
|
|
62
115
|
|
|
@@ -68,7 +121,11 @@ Connecting starts with an approval page the app serves. Most people hit it signe
|
|
|
68
121
|
|
|
69
122
|
## Failure modes
|
|
70
123
|
|
|
71
|
-
**Registering with no actions.** `softrMcpMiddleware()` is valid and serves an endpoint with nothing on it. The assistant connects, lists tools, finds only `whoami`. Pass
|
|
124
|
+
**Registering with no actions or tools.** `softrMcpMiddleware()` is valid and serves an endpoint with nothing on it. The assistant connects, lists tools, finds only `whoami`. Pass them.
|
|
125
|
+
|
|
126
|
+
**A write as an action, where the app has logic around it.** The record is written and everything the app does around it is skipped: no counter, no log entry, no email, no author. Write it as a `defineTool` that calls that logic.
|
|
127
|
+
|
|
128
|
+
**Marking a tool read-only that changes data.** Its writes fail when it runs. Set `readOnly: false`.
|
|
72
129
|
|
|
73
130
|
**Registering after `softrAuthMiddleware`.** Not a supported order. Put the MCP middleware first.
|
|
74
131
|
|
|
@@ -82,4 +139,5 @@ Connecting starts with an approval page the app serves. Most people hit it signe
|
|
|
82
139
|
|
|
83
140
|
- [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the read actions you expose
|
|
84
141
|
- [record-mutations/SKILL.md](../record-mutations/SKILL.md): declaring the write actions you expose
|
|
142
|
+
- [current-user/SKILL.md](../current-user/SKILL.md): the `User` a tool's handler gets
|
|
85
143
|
- [auth/SKILL.md](../auth/SKILL.md): the sign-in and second-factor flows the round trip passes through
|
|
@@ -10,7 +10,7 @@ description: >-
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: sub-skill
|
|
12
12
|
library: softr-sdk
|
|
13
|
-
library_version: 1.
|
|
13
|
+
library_version: 1.15.0
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -11,7 +11,7 @@ description: >-
|
|
|
11
11
|
metadata:
|
|
12
12
|
type: sub-skill
|
|
13
13
|
library: softr-sdk
|
|
14
|
-
library_version: 1.
|
|
14
|
+
library_version: 1.15.0
|
|
15
15
|
---
|
|
16
16
|
|
|
17
17
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A route `loader` also runs in the browser, so it calls a server function, never `ds`. A helper that calls `ds` outside a handler, in this file or in another one, goes in `createServerOnlyFn` from `@tanstack/react-start`, or inside the handler. An exported helper without it keeps the server-only import in the browser bundle, and every page stops loading until it moves. Do not make such a helper a server function when it takes an id: any visitor can call a server function with any id. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
12
|
+
library_version: 1.15.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
12
|
+
library_version: 1.15.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.
|