@lowdefy/api 6.1.0 → 7.1.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.
Files changed (195) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +8 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -14,36 +14,62 @@
14
14
  limitations under the License.
15
15
  */ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
16
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
- import { AuthenticationError } from '@lowdefy/errors';
18
- import { serializer, type } from '@lowdefy/helpers';
17
+ import { cleanBuildArtifact, serializer, type } from '@lowdefy/helpers';
18
+ import formatErrorForAgent from '../../response/formatErrorForAgent.js';
19
19
  import callEndpoint from '../endpoints/callEndpoint.js';
20
- import createWireProjection from '../../response/createWireProjection.js';
21
- import isUnauthenticatedHuman from '../endpoints/isUnauthenticatedHuman.js';
20
+ import runAfterToolCall from './runAfterToolCall.js';
22
21
  // LLM-safe tool names use the same rule as buildAgents tool naming.
23
22
  function toToolName(id) {
24
23
  return id.replaceAll('/', '__');
25
24
  }
26
- // Twin of cleanBuildArtifact in packages/utils/ai-utils/src/buildAgentTools.js -
27
- // duplicated here rather than shared, since pulling in @lowdefy/ai-utils would
28
- // add the ai SDK and MCP client deps to api just for this. Strips build-artifact
29
- // serializer markers (~k, ~r, ~l) and unwraps { '~arr': [...] } back to a plain
30
- // array, so payloadSchema reaches MCP clients as plain JSON Schema.
31
- function cleanBuildArtifact(obj) {
32
- return JSON.parse(JSON.stringify(serializer.deserialize(obj)));
25
+ // Whether the caller's token grant covers an endpoint's scope tag, over the
26
+ // closed vocabulary (mcp:read, mcp:write) with mcp:write implying mcp:read.
27
+ // An undefined grant is a caller with no token: consent never happened, so
28
+ // there is nothing to filter on - the authorization outcome alone limits them
29
+ // to public tools. An empty grant is the opposite: consent happened and
30
+ // granted this client nothing on this surface, so it covers no scope.
31
+ function scopeCovers({ grantedScopes, endpointScope }) {
32
+ if (type.isUndefined(grantedScopes)) {
33
+ return true;
34
+ }
35
+ if (endpointScope === 'mcp:write') {
36
+ return grantedScopes.includes('mcp:write');
37
+ }
38
+ return grantedScopes.includes('mcp:read') || grantedScopes.includes('mcp:write');
33
39
  }
34
40
  // A stateless per-request MCP server exposing the configured api endpoints
35
41
  // as tools. Built with the SDK's low-level Server: tool input schemas are
36
42
  // config-provided JSON Schema (payloadSchema), which the low-level handlers
37
43
  // accept directly - no zod conversion. The server is constructed with the
38
- // request's context, so the caller is known at construction time: tools/list
39
- // filters by context.authorize, and tools/call re-authorizes inside
40
- // callEndpoint (defense in depth). Returns null when no mcp block is
41
- // configured.
44
+ // request's context, so the caller is known at construction time: a tool is
45
+ // visible only when the authorization outcome is 'allow' AND the caller's
46
+ // token grant covers the endpoint's scope tag. tools/call re-applies both
47
+ // checks before dispatch - callEndpoint re-authorizes roles inside, but the
48
+ // scope filter exists only on this surface. Returns null when no mcp block
49
+ // is configured.
42
50
  async function createMcpServer({ context }) {
43
51
  const mcpConfig = await context.readConfigFile('mcp.json');
44
52
  if (type.isNone(mcpConfig) || mcpConfig.configured !== true) {
45
53
  return null;
46
54
  }
55
+ async function readVisibleEndpointConfig({ id, scope }) {
56
+ const endpointConfig = await context.readConfigFile(`api/${id}.json`);
57
+ if (type.isNone(endpointConfig)) {
58
+ return null;
59
+ }
60
+ // 'deny' and 'enrol_required' both hide the tool - an unenrolled member
61
+ // must not see an enrolment redirect leak which tools exist for them.
62
+ if (context.authorizeOutcome(endpointConfig) !== 'allow') {
63
+ return null;
64
+ }
65
+ if (!scopeCovers({
66
+ grantedScopes: context.mcpAuth?.grantedScopes,
67
+ endpointScope: scope
68
+ })) {
69
+ return null;
70
+ }
71
+ return endpointConfig;
72
+ }
47
73
  // serverInfo doubles as the connector card in clients such as claude.ai:
48
74
  // title, websiteUrl and icons are optional branding the app may configure,
49
75
  // and are omitted (not sent as undefined) when it does not. icons is config
@@ -64,23 +90,34 @@ async function createMcpServer({ context }) {
64
90
  if (!type.isNone(mcpConfig.icons)) {
65
91
  serverInfo.icons = cleanBuildArtifact(mcpConfig.icons);
66
92
  }
67
- const server = new Server(serverInfo, {
93
+ const serverOptions = {
68
94
  capabilities: {
69
95
  tools: {}
70
96
  }
71
- });
97
+ };
98
+ if (!type.isNone(mcpConfig.instructions)) {
99
+ serverOptions.instructions = mcpConfig.instructions;
100
+ }
101
+ const server = new Server(serverInfo, serverOptions);
72
102
  server.setRequestHandler(ListToolsRequestSchema, async ()=>{
73
103
  const tools = [];
74
- for (const endpointId of mcpConfig.endpoints){
75
- const endpointConfig = await context.readConfigFile(`api/${endpointId}.json`);
76
- if (type.isNone(endpointConfig) || !context.authorize(endpointConfig)) {
104
+ for (const { id, scope, annotations } of mcpConfig.endpoints){
105
+ const endpointConfig = await readVisibleEndpointConfig({
106
+ id,
107
+ scope
108
+ });
109
+ if (type.isNone(endpointConfig)) {
77
110
  continue;
78
111
  }
79
- tools.push({
80
- name: toToolName(endpointId),
112
+ const tool = {
113
+ name: toToolName(id),
81
114
  description: endpointConfig.description,
82
115
  inputSchema: cleanBuildArtifact(endpointConfig.payloadSchema)
83
- });
116
+ };
117
+ if (!type.isNone(annotations)) {
118
+ tool.annotations = cleanBuildArtifact(annotations);
119
+ }
120
+ tools.push(tool);
84
121
  }
85
122
  return {
86
123
  tools
@@ -92,81 +129,104 @@ async function createMcpServer({ context }) {
92
129
  event: 'mcp_tool_call',
93
130
  tool: name
94
131
  });
95
- const endpointId = mcpConfig.endpoints.find((id)=>toToolName(id) === name);
96
- try {
97
- if (!type.isNone(endpointId)) {
98
- const { error, response, success } = await callEndpoint(context, {
99
- blockId: '_mcp',
100
- endpointId,
101
- pageId: '_mcp',
102
- payload: args ?? {}
103
- });
104
- if (!success) {
105
- const deserialized = serializer.deserialize(error);
106
- let text = deserialized?.message ?? 'Endpoint failed.';
107
- // The dev MCP route serves a coding agent, which is a dev tool: it gets the real
108
- // message and the config location so it can go straight to the YAML. A prod MCP
109
- // client is an end-user reader and keeps the wire message.
110
- if (context.mode === 'dev' && !type.isNone(error?.devError)) {
111
- const devError = serializer.deserialize(error.devError);
112
- text = devError.message;
113
- if (!type.isNone(devError.source)) {
114
- text = `${text} (at ${devError.source})`;
115
- }
116
- if (!type.isNone(devError.hint)) {
117
- text = `${text} Hint: ${devError.hint}`;
118
- }
119
- }
120
- return {
121
- content: [
122
- {
123
- type: 'text',
124
- text
125
- }
126
- ],
127
- isError: true
128
- };
132
+ // A role or scope shortfall answers exactly like a name that does not
133
+ // exist: any distinguishable error would let a caller enumerate which
134
+ // gated tools this app has. Same reason it is isError content over 200,
135
+ // not an HTTP status.
136
+ const unknownTool = {
137
+ content: [
138
+ {
139
+ type: 'text',
140
+ text: `Unknown tool "${name}".`
129
141
  }
130
- return {
142
+ ],
143
+ isError: true
144
+ };
145
+ const endpoint = (mcpConfig.endpoints ?? []).find(({ id })=>toToolName(id) === name);
146
+ if (type.isNone(endpoint)) {
147
+ return unknownTool;
148
+ }
149
+ try {
150
+ const endpointConfig = await readVisibleEndpointConfig({
151
+ id: endpoint.id,
152
+ scope: endpoint.scope
153
+ });
154
+ if (type.isNone(endpointConfig)) {
155
+ return unknownTool;
156
+ }
157
+ const payload = args ?? {};
158
+ const { error, response, success } = await callEndpoint(context, {
159
+ blockId: '_mcp',
160
+ endpointId: endpoint.id,
161
+ outsideCaller: true,
162
+ pageId: '_mcp',
163
+ payload
164
+ });
165
+ const deserializedResponse = success ? serializer.deserialize(response) : null;
166
+ let reply;
167
+ if (success) {
168
+ reply = {
131
169
  content: [
132
170
  {
133
171
  type: 'text',
134
- text: JSON.stringify(serializer.deserialize(response))
172
+ text: JSON.stringify(deserializedResponse)
135
173
  }
136
174
  ]
137
175
  };
176
+ } else {
177
+ const deserialized = serializer.deserialize(error);
178
+ // The wire error is generic for every reader. The dev server also attaches the full
179
+ // error for dev tools, and the dev MCP client is a coding agent that needs it to find
180
+ // the failing config.
181
+ const devError = serializer.deserialize(error?.devError);
182
+ reply = {
183
+ content: [
184
+ {
185
+ type: 'text',
186
+ text: type.isNone(deserialized) ? 'Endpoint failed.' : formatErrorForAgent(context, devError ?? deserialized)
187
+ }
188
+ ],
189
+ isError: true
190
+ };
138
191
  }
139
- // An unknown tool answers like a gated one for an anonymous caller on an
140
- // auth'd app, so tools/call cannot be used to enumerate tool names that
141
- // tools/list already hides from that caller.
142
- if (await isUnauthenticatedHuman(context)) {
143
- throw new AuthenticationError(`Authentication required for API endpoint "${name}".`);
144
- }
145
- return {
146
- content: [
147
- {
148
- type: 'text',
149
- text: `Unknown tool "${name}".`
192
+ // Only a call that reached its endpoint's routine runs the hook: the
193
+ // early returns above and the refusals caught below never do.
194
+ if (!type.isNone(mcpConfig.afterToolCall)) {
195
+ await runAfterToolCall(context, {
196
+ hookId: mcpConfig.afterToolCall,
197
+ payload: {
198
+ tool: name,
199
+ endpoint_id: endpoint.id,
200
+ scope: endpoint.scope,
201
+ payload,
202
+ success,
203
+ response: deserializedResponse
150
204
  }
151
- ],
152
- isError: true
153
- };
205
+ });
206
+ }
207
+ return reply;
154
208
  } catch (error) {
155
- // Unauthenticated calls to gated tools are expected probing traffic -
156
- // a warn line and the 401-shaped message, not a structured error log.
157
- if (error.name === 'AuthenticationError') {
158
- context.logger.warn(`Unauthenticated MCP tool call: ${name}`);
209
+ // Refused calls to gated tools and payloads that miss the payloadSchema
210
+ // (UserError) are expected traffic - a warn line and the message the
211
+ // model needs to retry, not a structured error log. Everything else
212
+ // goes through the server's error sink, which resolves the config
213
+ // source, logs it and collects it for the dev feedback channel.
214
+ if ([
215
+ 'AuthenticationError',
216
+ 'AuthorizationError',
217
+ 'TwoFactorEnrolmentRequiredError'
218
+ ].includes(error.name)) {
219
+ context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
220
+ } else if (error.name === 'UserError') {
221
+ context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
159
222
  } else {
160
- context.logger.error(error);
223
+ await context.handleError(error);
161
224
  }
162
- // This error never went through an endpoint result, so it has not been projected yet.
163
- // The projection keeps an AuthenticationError's message.
164
- const text = context.mode === 'dev' ? error.message : createWireProjection(context)(error).message;
165
225
  return {
166
226
  content: [
167
227
  {
168
228
  type: 'text',
169
- text
229
+ text: formatErrorForAgent(context, error)
170
230
  }
171
231
  ],
172
232
  isError: true
@@ -176,3 +236,4 @@ async function createMcpServer({ context }) {
176
236
  return server;
177
237
  }
178
238
  export default createMcpServer;
239
+ export { scopeCovers };
@@ -0,0 +1,93 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { createLocalJWKSet } from 'jose';
16
+ import { type } from '@lowdefy/helpers';
17
+ // Verification keys for MCP access tokens, read in-process from the jwks
18
+ // rows the core jwt plugin persists - the same rows /api/auth/jwks serves.
19
+ // Reading through the adapter keeps token verification free of a self-HTTP
20
+ // dependency: the server never needs to reach its own public origin to
21
+ // authenticate a request. Only the publicKey column is read - it is the
22
+ // plaintext JSON-serialized public JWK, while privateKey is encrypted with
23
+ // the BetterAuth secret and never needed for verification. The row id is
24
+ // the kid the plugin stamps on every token it signs.
25
+ // Mirrors the served JWKS: rows persisted before the alg column existed
26
+ // default to the plugin's EdDSA, and a rotated key stays servable for the
27
+ // plugin's 30-day grace window so tokens signed just before rotation still
28
+ // verify until they expire.
29
+ const DEFAULT_ALG = 'EdDSA';
30
+ const ROTATION_GRACE_MS = 30 * 24 * 3600 * 1000;
31
+ const resolverByAuth = new WeakMap();
32
+ async function loadKeySet({ auth }) {
33
+ const { adapter } = await auth.$context;
34
+ const rows = await adapter.findMany({
35
+ model: 'jwks'
36
+ });
37
+ const now = Date.now();
38
+ const keys = (rows ?? []).filter((row)=>type.isNone(row.expiresAt) || new Date(row.expiresAt).getTime() + ROTATION_GRACE_MS > now).map((row)=>({
39
+ alg: row.alg ?? DEFAULT_ALG,
40
+ ...type.isNone(row.crv) ? {} : {
41
+ crv: row.crv
42
+ },
43
+ ...JSON.parse(row.publicKey),
44
+ kid: row.id
45
+ }));
46
+ return createLocalJWKSet({
47
+ keys
48
+ });
49
+ }
50
+ function createKeyResolver({ auth }) {
51
+ let keySetPromise = null;
52
+ function load() {
53
+ if (keySetPromise === null) {
54
+ // A failed load is never cached - a transient adapter error must not
55
+ // poison the resolver until restart.
56
+ keySetPromise = loadKeySet({
57
+ auth
58
+ }).catch((error)=>{
59
+ keySetPromise = null;
60
+ throw error;
61
+ });
62
+ }
63
+ return keySetPromise;
64
+ }
65
+ return async function resolveMcpKey(protectedHeader, token) {
66
+ const keySet = await load();
67
+ try {
68
+ return await keySet(protectedHeader, token);
69
+ } catch (error) {
70
+ if (error?.code !== 'ERR_JWKS_NO_MATCHING_KEY') {
71
+ throw error;
72
+ }
73
+ // An unknown kid can be a freshly rotated key this process has not
74
+ // seen - refetch once so rotation never strands verification.
75
+ keySetPromise = null;
76
+ const refreshed = await load();
77
+ return refreshed(protectedHeader, token);
78
+ }
79
+ };
80
+ }
81
+ // Returns a jose key resolver, cached per auth instance for the life of the
82
+ // process alongside the instance itself.
83
+ function getMcpJwks({ auth }) {
84
+ let resolver = resolverByAuth.get(auth);
85
+ if (resolver === undefined) {
86
+ resolver = createKeyResolver({
87
+ auth
88
+ });
89
+ resolverByAuth.set(auth, resolver);
90
+ }
91
+ return resolver;
92
+ }
93
+ export default getMcpJwks;
@@ -0,0 +1,41 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // The engine retains the MCP resource URI per auth instance. The /api/mcp
17
+ // bearer-token guard reads it synchronously at request time as the audience
18
+ // a presented token must carry, and the resource-row ensure reads it as the
19
+ // row identifier. Registered at startup only when the app is configured as an
20
+ // authorization server (auth.oauthProvider), so a null binding means the MCP
21
+ // OAuth surface is off.
22
+ const bindingByAuth = new WeakMap();
23
+ function registerMcpResourceBinding({ auth, resourceUri }) {
24
+ bindingByAuth.set(auth, {
25
+ resourceUri
26
+ });
27
+ }
28
+ function getMcpResourceBinding({ auth }) {
29
+ if (type.isNone(auth)) {
30
+ return null;
31
+ }
32
+ const binding = bindingByAuth.get(auth);
33
+ if (type.isNone(binding)) {
34
+ return null;
35
+ }
36
+ return {
37
+ resourceUri: binding.resourceUri
38
+ };
39
+ }
40
+ export { registerMcpResourceBinding };
41
+ export default getMcpResourceBinding;
@@ -0,0 +1,69 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import getCanonicalUrl from '../../context/getCanonicalUrl.js';
16
+ // The OAuth URI templates for the MCP protected resource live together here
17
+ // so the resource identifier, the aud check, the RFC 9728 metadata, and the
18
+ // WWW-Authenticate challenge can never drift apart. There is ONE MCP resource
19
+ // per deployment - the organization a token acts in is a claim the
20
+ // authorization server stamps at consent time, not a path segment.
21
+ // The origin always comes from the pinned canonical URL (BETTER_AUTH_URL, else the current
22
+ // environment's url) - never a Host header, which is caller-controlled.
23
+ function getCanonicalOrigin({ config }) {
24
+ const canonicalUrl = getCanonicalUrl({
25
+ config
26
+ });
27
+ if (canonicalUrl === null) {
28
+ return null;
29
+ }
30
+ return canonicalUrl.replace(/\/$/, '');
31
+ }
32
+ // The resource identifier (RFC 8707) every MCP access token is minted for,
33
+ // and the audience the /api/mcp route verifies against.
34
+ function getMcpResourceUri({ config }) {
35
+ const canonicalUrl = getCanonicalOrigin({
36
+ config
37
+ });
38
+ if (canonicalUrl === null) {
39
+ return null;
40
+ }
41
+ return `${canonicalUrl}${config.basePath ?? ''}/api/mcp`;
42
+ }
43
+ // The authorization server's issuer identifier - what it stamps on iss and
44
+ // its metadata issuer. Carries the /api/auth suffix (BetterAuth baseURL +
45
+ // auth basePath), distinct from the MCP resource URI, and not the bare
46
+ // origin.
47
+ function getAsIssuer({ config }) {
48
+ const canonicalUrl = getCanonicalOrigin({
49
+ config
50
+ });
51
+ if (canonicalUrl === null) {
52
+ return null;
53
+ }
54
+ return `${canonicalUrl}${config.basePath ?? ''}/api/auth`;
55
+ }
56
+ // The RFC 9728 metadata location for the resource - the well-known segment
57
+ // sits after the app basePath, where the servers mount the metadata route.
58
+ // Both the WWW-Authenticate challenge and the served document derive from
59
+ // here, so the pointer and its target cannot drift apart.
60
+ function getMcpResourceMetadataUri({ config }) {
61
+ const canonicalUrl = getCanonicalOrigin({
62
+ config
63
+ });
64
+ if (canonicalUrl === null) {
65
+ return null;
66
+ }
67
+ return `${canonicalUrl}${config.basePath ?? ''}/.well-known/oauth-protected-resource/api/mcp`;
68
+ }
69
+ export { getMcpResourceUri, getMcpResourceMetadataUri, getAsIssuer };
@@ -0,0 +1,122 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import getMcpResourceBinding from './getMcpResourceBinding.js';
17
+ // Lifecycle of the one oauthResource row the authorization server validates
18
+ // MCP token audiences against. The resource is a property of the deployment,
19
+ // not of an organization - which organization a token acts in is a claim
20
+ // stamped at consent time - so a single row, identified by the canonical
21
+ // resource URI, is ensured once per process. The row is owned by this code;
22
+ // the oauth-provider's HTTP resource CRUD is closed (resourcePrivileges:
23
+ // () => false). The write follows the plugin's insertOnly seed stance: insert
24
+ // a missing row, never revert an existing one, so a row an operator disabled
25
+ // stays disabled through restarts. No-ops when no MCP resource binding is
26
+ // registered (the app is not an authorization server), and never throws into
27
+ // the request path that awaits it.
28
+ const model = 'oauthResource';
29
+ // Mirrors the oauth-provider's own seed row (buildSeedRow at 1.7.0): null
30
+ // policy columns mean "inherit the plugin-level default at issuance time".
31
+ function buildResourceRow({ identifier }) {
32
+ const now = new Date();
33
+ return {
34
+ identifier,
35
+ name: identifier,
36
+ accessTokenTtl: null,
37
+ refreshTokenTtl: null,
38
+ signingAlgorithm: null,
39
+ signingKeyId: null,
40
+ allowedScopes: null,
41
+ customClaims: null,
42
+ dpopBoundAccessTokensRequired: false,
43
+ disabled: false,
44
+ policyVersion: 1,
45
+ metadata: null,
46
+ createdAt: now,
47
+ updatedAt: now
48
+ };
49
+ }
50
+ async function insertResourceRowIfMissing({ adapter, identifier }) {
51
+ const existing = await adapter.findOne({
52
+ model,
53
+ where: [
54
+ {
55
+ field: 'identifier',
56
+ value: identifier
57
+ }
58
+ ]
59
+ });
60
+ // An existing row is never reverted - re-enabling a disabled row here would
61
+ // silently undo a deliberate operator disable on every restart.
62
+ if (existing) {
63
+ return;
64
+ }
65
+ try {
66
+ await adapter.create({
67
+ model,
68
+ data: buildResourceRow({
69
+ identifier
70
+ })
71
+ });
72
+ } catch (error) {
73
+ // A racing process inserted the row between the find and the create - the
74
+ // unique identifier index rejected this write, so the wanted row exists.
75
+ const winner = await adapter.findOne({
76
+ model,
77
+ where: [
78
+ {
79
+ field: 'identifier',
80
+ value: identifier
81
+ }
82
+ ]
83
+ });
84
+ if (!winner) {
85
+ throw error;
86
+ }
87
+ }
88
+ }
89
+ const ensuredByAuth = new WeakMap();
90
+ // Awaited per request in the api-context middleware, so it is memoized like
91
+ // resolvePinnedOrganization: after the first success it awaits an
92
+ // already-settled promise.
93
+ async function ensureMcpOauthResource({ auth, logger }) {
94
+ const binding = getMcpResourceBinding({
95
+ auth
96
+ });
97
+ if (type.isNone(binding)) {
98
+ return;
99
+ }
100
+ let promise = ensuredByAuth.get(auth);
101
+ if (type.isNone(promise)) {
102
+ promise = auth.$context.then(({ adapter })=>insertResourceRowIfMissing({
103
+ adapter,
104
+ identifier: binding.resourceUri
105
+ })).catch((error)=>{
106
+ // Do not memoize a failure - the next request retries.
107
+ ensuredByAuth.delete(auth);
108
+ throw error;
109
+ });
110
+ ensuredByAuth.set(auth, promise);
111
+ }
112
+ try {
113
+ await promise;
114
+ } catch (error) {
115
+ // A briefly unreachable database must not fail every request from the
116
+ // middleware - requests keep serving and the next one retries.
117
+ logger.warn({
118
+ err: error
119
+ }, `Failed to ensure the oauthResource row "${binding.resourceUri}" for the MCP resource.`);
120
+ }
121
+ }
122
+ export { ensureMcpOauthResource };
@@ -0,0 +1,50 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import invokeEndpoint from '../endpoints/invokeEndpoint.js';
16
+ // Runs the app's mcp.afterToolCall endpoint as the tool's caller, after the
17
+ // reply to the agent is built. The hook observes the call; it can never change
18
+ // the reply, so every failure (a refused caller, a payload its schema rejects,
19
+ // a routine that errors or rejects) ends as one warning and nothing else.
20
+ // Awaited by the caller rather than left running: a serverless platform may
21
+ // reap the invocation once the response is sent.
22
+ async function runAfterToolCall(context, { hookId, payload }) {
23
+ const { logger } = context;
24
+ try {
25
+ const result = await invokeEndpoint(context, {
26
+ endpointId: hookId,
27
+ payload,
28
+ endpointDepth: 0
29
+ });
30
+ if ([
31
+ 'error',
32
+ 'reject'
33
+ ].includes(result.status)) {
34
+ logger.warn({
35
+ event: 'warn_mcp_after_tool_call',
36
+ hook: hookId,
37
+ tool: payload.tool,
38
+ status: result.status
39
+ }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${result.error?.message}`);
40
+ }
41
+ } catch (error) {
42
+ logger.warn({
43
+ event: 'warn_mcp_after_tool_call',
44
+ hook: hookId,
45
+ tool: payload.tool,
46
+ err: error
47
+ }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${error.message}`);
48
+ }
49
+ }
50
+ export default runAfterToolCall;