@frontmcp/sdk 1.12.1 → 1.12.3

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 (92) hide show
  1. package/app/instances/app.lazy.instance.d.ts.map +1 -1
  2. package/app/lazy/lazy-app.rules.d.ts +5 -0
  3. package/app/lazy/lazy-app.rules.d.ts.map +1 -1
  4. package/auth/flows/oauth.authorize.flow.d.ts +2 -0
  5. package/auth/flows/oauth.authorize.flow.d.ts.map +1 -1
  6. package/auth/flows/oauth.callback.flow.d.ts +1 -0
  7. package/auth/flows/oauth.callback.flow.d.ts.map +1 -1
  8. package/auth/flows/oauth.provider-callback.flow.d.ts +1 -0
  9. package/auth/flows/oauth.provider-callback.flow.d.ts.map +1 -1
  10. package/auth/flows/session.verify.flow.d.ts +2 -0
  11. package/auth/flows/session.verify.flow.d.ts.map +1 -1
  12. package/auth/instances/instance.local-primary-auth.d.ts +9 -4
  13. package/auth/instances/instance.local-primary-auth.d.ts.map +1 -1
  14. package/auth/instances/instance.remote-primary-auth.d.ts +2 -0
  15. package/auth/instances/instance.remote-primary-auth.d.ts.map +1 -1
  16. package/auth/session-scope-identity.d.ts +5 -3
  17. package/auth/session-scope-identity.d.ts.map +1 -1
  18. package/browser/app/instances/app.lazy.instance.mjs +9 -2
  19. package/browser/app/lazy/lazy-app.rules.mjs +11 -1
  20. package/browser/auth/flows/oauth.authorize.flow.mjs +7 -1
  21. package/browser/auth/flows/oauth.callback.flow.mjs +6 -2
  22. package/browser/auth/flows/oauth.provider-callback.flow.mjs +8 -4
  23. package/browser/auth/flows/session.verify.flow.mjs +17 -14
  24. package/browser/auth/instances/instance.local-primary-auth.mjs +57 -14
  25. package/browser/auth/instances/instance.remote-primary-auth.mjs +13 -1
  26. package/browser/auth/session-scope-identity.mjs +6 -1
  27. package/browser/common/interfaces/flow.interface.mjs +7 -1
  28. package/browser/common/types/auth/session.types.mjs +2 -1
  29. package/browser/common/utils/auth-info.utils.mjs +3 -2
  30. package/browser/event/flows/event-publish-http.flow.mjs +19 -2
  31. package/browser/flows/flow.instance.mjs +43 -5
  32. package/browser/hooks/hooks.utils.mjs +10 -4
  33. package/browser/index.cjs +1371 -1120
  34. package/browser/notification/notification.service.mjs +28 -4
  35. package/browser/notification/resource-update-access.mjs +22 -0
  36. package/browser/plugin/enforced-metadata.check.mjs +2 -1
  37. package/browser/prompt/flows/get-prompt.flow.mjs +13 -0
  38. package/browser/remote-mcp/mcp-client.service.mjs +26 -13
  39. package/browser/remote-mcp/remote-request-headers.mjs +6 -3
  40. package/browser/resource/flows/read-resource.flow.mjs +20 -23
  41. package/browser/resource/flows/subscribe-resource.flow.mjs +9 -4
  42. package/browser/tool/ui/ui-shared.mjs +9 -0
  43. package/browser/transport/flows/handle.mcp-20260728.flow.mjs +9 -3
  44. package/browser/transport/mcp-20260728/index.mjs +1 -1
  45. package/browser/transport/mcp-20260728/subscriptions.mjs +8 -6
  46. package/common/interfaces/flow.interface.d.ts +4 -1
  47. package/common/interfaces/flow.interface.d.ts.map +1 -1
  48. package/common/metadata/app.metadata.d.ts +16 -16
  49. package/common/metadata/front-mcp.metadata.d.ts +37 -37
  50. package/common/types/auth/session.types.d.ts +6 -0
  51. package/common/types/auth/session.types.d.ts.map +1 -1
  52. package/common/types/options/http/interfaces.d.ts +4 -1
  53. package/common/types/options/http/interfaces.d.ts.map +1 -1
  54. package/common/utils/auth-info.utils.d.ts +1 -0
  55. package/common/utils/auth-info.utils.d.ts.map +1 -1
  56. package/esm/index.mjs +25 -25
  57. package/event/flows/event-publish-http.flow.d.ts +2 -0
  58. package/event/flows/event-publish-http.flow.d.ts.map +1 -1
  59. package/flows/flow.instance.d.ts.map +1 -1
  60. package/hooks/hooks.utils.d.ts +2 -4
  61. package/hooks/hooks.utils.d.ts.map +1 -1
  62. package/index.d.ts +5 -5
  63. package/index.js +36 -36
  64. package/notification/notification.service.d.ts +7 -2
  65. package/notification/notification.service.d.ts.map +1 -1
  66. package/notification/resource-update-access.d.ts +9 -0
  67. package/notification/resource-update-access.d.ts.map +1 -0
  68. package/package.json +10 -10
  69. package/plugin/enforced-metadata.check.d.ts +3 -1
  70. package/plugin/enforced-metadata.check.d.ts.map +1 -1
  71. package/prompt/flows/get-prompt.flow.d.ts +3 -1
  72. package/prompt/flows/get-prompt.flow.d.ts.map +1 -1
  73. package/remote-mcp/mcp-client.service.d.ts.map +1 -1
  74. package/remote-mcp/mcp-client.types.d.ts.map +1 -1
  75. package/remote-mcp/remote-request-headers.d.ts +22 -8
  76. package/remote-mcp/remote-request-headers.d.ts.map +1 -1
  77. package/resource/flows/read-resource.flow.d.ts +2 -0
  78. package/resource/flows/read-resource.flow.d.ts.map +1 -1
  79. package/resource/flows/subscribe-resource.flow.d.ts.map +1 -1
  80. package/scope/flows/http.request.flow.d.ts +1 -0
  81. package/scope/flows/http.request.flow.d.ts.map +1 -1
  82. package/server/adapters/express.host.adapter.d.ts +3 -2
  83. package/server/adapters/express.host.adapter.d.ts.map +1 -1
  84. package/shared/shared-endpoint.d.ts +5 -1
  85. package/shared/shared-endpoint.d.ts.map +1 -1
  86. package/shared/unix-socket-fetch.d.ts +7 -0
  87. package/shared/unix-socket-fetch.d.ts.map +1 -1
  88. package/tool/ui/ui-shared.d.ts +4 -0
  89. package/tool/ui/ui-shared.d.ts.map +1 -1
  90. package/transport/flows/handle.mcp-20260728.flow.d.ts.map +1 -1
  91. package/transport/mcp-20260728/subscriptions.d.ts +5 -3
  92. package/transport/mcp-20260728/subscriptions.d.ts.map +1 -1
@@ -10,6 +10,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
10
10
 
11
11
  // libs/sdk/src/auth/instances/instance.local-primary-auth.ts
12
12
  import {
13
+ clientAuthMethodToRecord,
13
14
  createSecureStore,
14
15
  createTokenStorageAdapter,
15
16
  DcrClientRegistry,
@@ -18,11 +19,13 @@ import {
18
19
  InMemoryConsentStore,
19
20
  InMemoryFederatedAuthSessionStore,
20
21
  InMemoryOrchestratedTokenStore,
22
+ isGrantRedeemedError,
21
23
  isPersistentTokenStorage,
22
24
  isRedisTokenStorage,
23
25
  isSqliteTokenStorage,
24
26
  JwksService,
25
27
  LocalTokenKeys,
28
+ meetsRecordedClientAuth,
26
29
  resolveUpstreamClient,
27
30
  SessionCredentialVault,
28
31
  StorageAuthorizationStore,
@@ -435,8 +438,9 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
435
438
  * adapter-backed equivalents. For `'memory'` (or unset) this is a no-op, so
436
439
  * the default behavior is preserved exactly.
437
440
  *
438
- * The orchestrated-token store keeps using the JWT secret as its encryption
439
- * key, so upstream provider tokens stay encrypted at rest in every backend.
441
+ * The orchestrated-token and federated-session stores use the JWT secret as
442
+ * their encryption key, so upstream provider tokens stay encrypted at rest in
443
+ * every backend.
440
444
  */
441
445
  async initializeStores() {
442
446
  if (!isPersistentTokenStorage(this.tokenStorage)) {
@@ -448,10 +452,11 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
448
452
  this.storageClosers.push(() => adapter.disconnect());
449
453
  this.disposeInMemoryStores();
450
454
  this.authorizationStoreImpl = new StorageAuthorizationStore(adapter);
451
- this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter);
455
+ this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter, { encryptionKey: this.secret });
452
456
  this.orchestratedTokenStoreImpl = new StorageOrchestratedTokenStore(adapter, {
453
457
  encryptionKey: this.secret,
454
- refreshSkewMs: this.providerRefreshSkewMs()
458
+ refreshSkewMs: this.providerRefreshSkewMs(),
459
+ providerIssuer: (providerId) => this.providerAuthorizationServer(providerId)
455
460
  });
456
461
  this.consentStoreImpl = new StorageConsentStore(adapter);
457
462
  const backend = isSqliteTokenStorage(this.tokenStorage) ? "sqlite" : isRedisTokenStorage(this.tokenStorage) ? "redis" : "unknown";
@@ -820,6 +825,10 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
820
825
  error_description: "Client ID does not match"
821
826
  };
822
827
  }
828
+ if (!meetsRecordedClientAuth(codeRecord.clientAuthMethod, declared.authMethod)) {
829
+ this.logger.warn("Authorization code needs client authentication this client did not provide");
830
+ return { error: "invalid_client", error_description: "Client authentication failed" };
831
+ }
823
832
  if (codeRecord.redirectUri !== redirectUri) {
824
833
  this.logger.warn(`Redirect URI mismatch`);
825
834
  return {
@@ -834,7 +843,13 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
834
843
  error_description: "PKCE verification failed"
835
844
  };
836
845
  }
837
- await this.authorizationStore.markCodeUsed(code);
846
+ try {
847
+ await this.authorizationStore.markCodeUsed(code);
848
+ } catch (err) {
849
+ if (!isGrantRedeemedError(err)) throw err;
850
+ this.logger.warn("Authorization code was redeemed by a concurrent request");
851
+ return { error: "invalid_grant", error_description: "Authorization code has already been used" };
852
+ }
838
853
  const user = {
839
854
  sub: codeRecord.userSub,
840
855
  email: codeRecord.userEmail,
@@ -879,7 +894,8 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
879
894
  federatedLoginUsed: codeRecord.federatedLoginUsed,
880
895
  selectedProviderIds: codeRecord.selectedProviderIds,
881
896
  skippedProviderIds: codeRecord.skippedProviderIds,
882
- providerTokensId
897
+ providerTokensId,
898
+ clientAuthMethod: clientAuthMethodToRecord(codeRecord.clientAuthMethod, declared.authMethod)
883
899
  });
884
900
  await this.authorizationStore.storeRefreshToken(refreshTokenRecord);
885
901
  await this.authorizationStore.markCodeUsed(code, refreshTokenRecord.token);
@@ -888,11 +904,13 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
888
904
  /**
889
905
  * Refuse a grant the client did not declare in its `grant_types` (RFC 7591): in its registration, its
890
906
  * `dcr.clients` entry or its client ID metadata document. A client that declared nothing (an unregistered
891
- * id under `requireRegisteredClients: false`) is not limited, and gets `grantTypes: undefined`. A CIMD client
892
- * whose document declares `private_key_jwt` must also present a valid client assertion.
907
+ * id under `requireRegisteredClients: false`, or one registered on another instance or before a restart)
908
+ * is not limited, and gets `grantTypes: undefined` and `authMethod: undefined`. A CIMD client whose document
909
+ * declares `private_key_jwt` must also present a valid client assertion.
893
910
  */
894
911
  async checkDeclaredGrant(clientId, grantType, clientAssertion) {
895
912
  let grantTypes;
913
+ let authMethod;
896
914
  try {
897
915
  const cimd = this.cimdService;
898
916
  if (cimd?.enabled && cimd.isCimdClientId(clientId)) {
@@ -906,8 +924,11 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
906
924
  });
907
925
  }
908
926
  grantTypes = metadata?.grant_types;
927
+ authMethod = metadata?.token_endpoint_auth_method ?? "none";
909
928
  } else {
910
- grantTypes = this.dcrClientRegistryImpl.get(clientId)?.grant_types;
929
+ const registered = this.dcrClientRegistryImpl.get(clientId);
930
+ grantTypes = registered?.grant_types;
931
+ authMethod = registered?.token_endpoint_auth_method;
911
932
  }
912
933
  } catch (err) {
913
934
  this.logger.warn(`Client metadata refused at token endpoint (${grantType}): ${err.message}`);
@@ -917,7 +938,7 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
917
938
  this.logger.warn(`Client did not declare the ${grantType} grant`);
918
939
  return { error: "unauthorized_client", error_description: `This client may not use the ${grantType} grant` };
919
940
  }
920
- return { grantTypes };
941
+ return { grantTypes, authMethod };
921
942
  }
922
943
  /**
923
944
  * Move the upstream provider tokens stored under `fromAuthorizationId` to the authorization id of
@@ -989,6 +1010,10 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
989
1010
  error_description: "Client ID does not match"
990
1011
  };
991
1012
  }
1013
+ if (!meetsRecordedClientAuth(tokenRecord.clientAuthMethod, declared.authMethod)) {
1014
+ this.logger.warn("Refresh token needs client authentication this client did not provide");
1015
+ return { error: "invalid_client", error_description: "Client authentication failed" };
1016
+ }
992
1017
  const user = {
993
1018
  sub: tokenRecord.userSub,
994
1019
  email: tokenRecord.userEmail,
@@ -1028,13 +1053,16 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1028
1053
  federatedLoginUsed: tokenRecord.federatedLoginUsed,
1029
1054
  selectedProviderIds: tokenRecord.selectedProviderIds,
1030
1055
  skippedProviderIds: tokenRecord.skippedProviderIds,
1031
- providerTokensId: copiedTo ?? sourceId
1056
+ providerTokensId: copiedTo ?? sourceId,
1057
+ clientAuthMethod: clientAuthMethodToRecord(tokenRecord.clientAuthMethod, declared.authMethod)
1032
1058
  });
1033
1059
  try {
1034
1060
  await this.authorizationStore.rotateRefreshToken(refreshToken, newRefreshRecord);
1035
1061
  } catch (err) {
1036
1062
  if (copiedTo) await this.discardProviderTokens(copiedTo);
1037
- throw err;
1063
+ if (!isGrantRedeemedError(err)) throw err;
1064
+ this.logger.warn("Refresh token was redeemed by a concurrent request");
1065
+ return { error: "invalid_grant", error_description: "Refresh token is invalid or expired" };
1038
1066
  }
1039
1067
  if (sourceId && copiedTo) await this.discardProviderTokens(sourceId);
1040
1068
  if (sourceId && !this.orchestratedTokenStore.copyTokens) {
@@ -1077,7 +1105,8 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1077
1105
  // Progressive/Incremental authorization: granted app-id set.
1078
1106
  authorizedAppIds: params.authorizedAppIds,
1079
1107
  // Custom claims from a local authenticate() verifier (Checkpoint 3a)
1080
- customClaims: params.customClaims
1108
+ customClaims: params.customClaims,
1109
+ clientAuthMethod: params.clientAuthMethod
1081
1110
  });
1082
1111
  await this.authorizationStore.storeAuthorizationCode(codeRecord);
1083
1112
  this.logger.info(`Authorization code created for user: ${params.userSub}`);
@@ -1149,6 +1178,14 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1149
1178
  this.providerConfigs.set(config.id, config);
1150
1179
  this.logger.info(`Registered upstream provider: ${config.id}`);
1151
1180
  }
1181
+ /** The authorization server a provider's tokens come from: its issuer, else its token endpoint. */
1182
+ providerAuthorizationServer(providerId) {
1183
+ const config = this.providerConfigs.get(providerId);
1184
+ if (!config) {
1185
+ return void 0;
1186
+ }
1187
+ return config.issuer ? normalizeIssuer(config.issuer) : config.tokenEndpoint;
1188
+ }
1152
1189
  /**
1153
1190
  * Drop every stored credential for a provider whose authorization server changed.
1154
1191
  *
@@ -1550,6 +1587,7 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1550
1587
  };
1551
1588
  }
1552
1589
  async renewProviderToken(providerId, refreshToken) {
1590
+ const issuer = this.providerAuthorizationServer(providerId);
1553
1591
  const result = await this.refreshProviderToken(providerId, refreshToken);
1554
1592
  if ("error" in result || typeof result.access_token !== "string" || !result.access_token) {
1555
1593
  this.logger.warn(
@@ -1559,7 +1597,12 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1559
1597
  `Provider "${providerId}" did not refresh its token; the user has to sign in again`
1560
1598
  );
1561
1599
  }
1562
- return { accessToken: result.access_token, refreshToken: result.refresh_token, expiresIn: result.expires_in };
1600
+ return {
1601
+ accessToken: result.access_token,
1602
+ refreshToken: result.refresh_token,
1603
+ expiresIn: result.expires_in,
1604
+ issuer
1605
+ };
1563
1606
  }
1564
1607
  /** How long before its expiry a provider token is renewed: `refresh.skewSeconds` (default 60), none with `refresh` off. */
1565
1608
  providerRefreshSkewMs() {
@@ -1,6 +1,6 @@
1
1
  // libs/sdk/src/auth/instances/instance.remote-primary-auth.ts
2
2
  import { JwksService } from "@frontmcp/auth";
3
- import { FrontMcpAuth, ProviderScope } from "../../common/index.mjs";
3
+ import { FrontMcpAuth, isPublicUrlPinned, ProviderScope } from "../../common/index.mjs";
4
4
  import SessionVerifyFlow from "../flows/session.verify.flow.mjs";
5
5
  import WellKnownJwksFlow from "../flows/well-known.jwks.flow.mjs";
6
6
  import WellKnownAsFlow from "../flows/well-known.oauth-authorization-server.flow.mjs";
@@ -36,8 +36,20 @@ var RemotePrimaryAuth = class extends FrontMcpAuth {
36
36
  provide: JwksService
37
37
  });
38
38
  await this.registerAuthFlows(scope);
39
+ this.warnWithoutConfiguredAudience(scope);
39
40
  return Promise.resolve();
40
41
  }
42
+ /** Warn once at startup when nothing configures the token audience, so the request host decides it. */
43
+ warnWithoutConfiguredAudience(scope) {
44
+ const protection = scope.metadata.http?.security?.dnsRebindingProtection;
45
+ const checkedHosts = protection?.enabled === false ? void 0 : protection?.allowedHosts;
46
+ if (this.options.expectedAudience || isPublicUrlPinned() || checkedHosts?.length) {
47
+ return;
48
+ }
49
+ scope.logger.warn(
50
+ "Transparent auth has no configured token audience, so each token is checked against the host the request names. Set auth.expectedAudience to the audience your identity provider puts in tokens (or set FRONTMCP_PUBLIC_URL, or list the server host in security.dnsRebindingProtection.allowedHosts with that protection on). FrontMCP 1.13 will refuse tokens that carry an aud claim when none of these is set."
51
+ );
52
+ }
41
53
  async registerAuthFlows(scope) {
42
54
  await scope.registryFlows(
43
55
  WellKnownPrmFlow,
@@ -8,7 +8,12 @@ function sessionScopeIdentity(ctx) {
8
8
  const principal = [authInfo.user?.sub, extraUser?.sub, authInfo.clientId].find(
9
9
  (candidate) => !isAnonymousSubject(candidate)
10
10
  );
11
- return principal ? `principal:${principal}` : void 0;
11
+ if (!principal) return void 0;
12
+ const principalIssuer = authInfo.extra?.["principalIssuer"];
13
+ if (typeof principalIssuer === "string") {
14
+ return `issuer-principal:${encodeURIComponent(principalIssuer)}:${principal}`;
15
+ }
16
+ return `principal:${principal}`;
12
17
  }
13
18
  export {
14
19
  sessionScopeIdentity
@@ -50,12 +50,13 @@ var FlowControl = class _FlowControl extends Error {
50
50
  };
51
51
  brandClass(FlowControl, "@frontmcp/sdk:FlowControl");
52
52
  var FlowBase = class {
53
- constructor(metadata, rawInput, scope, appendContextHooks, deps = /* @__PURE__ */ new Map()) {
53
+ constructor(metadata, rawInput, scope, appendContextHooks, deps = /* @__PURE__ */ new Map(), retargetEntryHooks) {
54
54
  this.metadata = metadata;
55
55
  this.rawInput = rawInput;
56
56
  this.scope = scope;
57
57
  this.appendContextHooks = appendContextHooks;
58
58
  this.deps = deps;
59
+ this.retargetEntryHooks = retargetEntryHooks;
59
60
  this.input = metadata.inputSchema?.parse?.(rawInput);
60
61
  this.scopeLogger = scope.logger;
61
62
  }
@@ -64,6 +65,7 @@ var FlowBase = class {
64
65
  scope;
65
66
  appendContextHooks;
66
67
  deps;
68
+ retargetEntryHooks;
67
69
  /**
68
70
  * The id of the app that owns the entry a run targets, read from the raw input before hooks load.
69
71
  * Entries an app's adapters and plugins provide belong to that app. App-scoped hooks run only when it matches their app.
@@ -118,6 +120,10 @@ var FlowBase = class {
118
120
  set error(value) {
119
121
  shadowWithOwnValue(this, "error", value);
120
122
  }
123
+ /** Hand the stages still to come to the app and `static` hooks of the entry a hook switched to, in place of the first's. */
124
+ async useEntryHooks(ownerId, entryClass) {
125
+ await this.retargetEntryHooks?.(ownerId, entryClass);
126
+ }
121
127
  respond(output) {
122
128
  throw FlowControl.respond(this.metadata.outputSchema.parse(output));
123
129
  }
@@ -13,7 +13,8 @@ var sessionIdSchema = z.object({
13
13
  var authorizationSchema = z.object({
14
14
  token: z.string(),
15
15
  session: sessionIdSchema.optional(),
16
- user: userClaimSchema
16
+ user: userClaimSchema,
17
+ principalIssuer: z.string().optional()
17
18
  });
18
19
  export {
19
20
  aiPlatformTypeSchema,
@@ -7,7 +7,7 @@ function sessionIdPresentedBy(request) {
7
7
  return typeof query === "string" && query.length > 0 ? query : void 0;
8
8
  }
9
9
  function authInfoFromAuthorization(authorization, presentedSessionId) {
10
- const { token, user, session } = authorization;
10
+ const { token, user, session, principalIssuer } = authorization;
11
11
  const verifiedSession = session !== void 0 && presentedSessionId !== void 0 && session.id === presentedSessionId ? session : void 0;
12
12
  return {
13
13
  token,
@@ -18,7 +18,8 @@ function authInfoFromAuthorization(authorization, presentedSessionId) {
18
18
  extra: {
19
19
  user,
20
20
  sessionId: verifiedSession?.id,
21
- sessionPayload: verifiedSession?.payload
21
+ sessionPayload: verifiedSession?.payload,
22
+ principalIssuer
22
23
  }
23
24
  };
24
25
  }
@@ -117,11 +117,28 @@ var EventPublishHttpFlow = class extends FlowBase {
117
117
  this.state.set("flowError", new PublicMcpError(`HTTP ${status}: ${error}`, "EVENT_PUBLISH_REFUSED", status));
118
118
  return FlowControl.respond(httpRespond.json({ error, ...details }, { status, headers }));
119
119
  }
120
+ /** Run a guard that answers its own refusals, and keep such a refusal as the run's failure, as `refuse()` does. */
121
+ async recordingRefusal(guard) {
122
+ try {
123
+ await guard();
124
+ } catch (signal) {
125
+ const refusal = signal instanceof FlowControl && signal.type === "respond" ? signal.output : void 0;
126
+ if (refusal?.kind === "json") {
127
+ const reason = Array.isArray(refusal.body) ? void 0 : refusal.body["error"];
128
+ const error = typeof reason === "string" ? reason : "Refused";
129
+ this.state.set(
130
+ "flowError",
131
+ new PublicMcpError(`HTTP ${refusal.status}: ${error}`, "EVENT_PUBLISH_REFUSED", refusal.status)
132
+ );
133
+ }
134
+ throw signal;
135
+ }
136
+ }
120
137
  async checkIpFilter() {
121
- enforceIpFilter(this.scope, this.tryGetContext()?.metadata.clientIp);
138
+ await this.recordingRefusal(() => enforceIpFilter(this.scope, this.tryGetContext()?.metadata.clientIp));
122
139
  }
123
140
  async acquireQuota() {
124
- await enforceGlobalRateLimit(this.scope, this.tryGetContext());
141
+ await this.recordingRefusal(() => enforceGlobalRateLimit(this.scope, this.tryGetContext()));
125
142
  }
126
143
  async readBody() {
127
144
  const request = this.httpRequest;
@@ -20,7 +20,7 @@ import {
20
20
  withHookTrace
21
21
  } from "../hooks/hook-observers.mjs";
22
22
  import { hookOwnerName } from "../hooks/hook-order.mjs";
23
- import { bindContextHookTargets, staticHooksFor } from "../hooks/hooks.utils.mjs";
23
+ import { bindContextHookTargets, sourceMetadataOf, staticHooksFor } from "../hooks/hooks.utils.mjs";
24
24
  import { writeHttpResponse } from "../server/server.validation.mjs";
25
25
  import { flowErrorToHttpOutput } from "../transport/flow-error-output.mjs";
26
26
  import { deferredFlowLoader } from "./deferred-flow.mjs";
@@ -33,6 +33,7 @@ import {
33
33
  } from "./flow.stages.mjs";
34
34
  import { collectFlowMetadata } from "./flow.utils.mjs";
35
35
  var FAILED_OUTCOMES = /* @__PURE__ */ new Set(["fail", "abort", "unknown_error"]);
36
+ var REGISTRY_HOOK_ORDER_START = -1e6;
36
37
  var CAP = (s) => s ? s[0].toUpperCase() + s.slice(1) : s;
37
38
  var stageKeysByName = /* @__PURE__ */ new Map();
38
39
  function stageKeysOf(stage) {
@@ -377,9 +378,12 @@ var FlowInstance = class extends FlowEntry {
377
378
  const hookOwnerId = await FlowClass.resolveHookOwnerId?.(input, scope);
378
379
  const entryClass = await FlowClass.resolveHookEntryClass?.(input, scope);
379
380
  const entryStaticHooks = entryClass ? staticHooksFor(this.hooks.getClsHooks(entryClass), name) : [];
381
+ const bindRun = { sessionKey, contextProviders: mergedDeps, contextSource: this.globalProviders };
382
+ const ownerHooks = this.hooks.getFlowHooksForOwner(name, hookOwnerId) ?? [];
383
+ let registryHookOrder = REGISTRY_HOOK_ORDER_START + ownerHooks.length;
380
384
  const initialInjectedHooks = await bindContextHookTargets(
381
- this.hooks.getFlowHooksForOwner(name, hookOwnerId) ?? [],
382
- { sessionKey, contextProviders: mergedDeps, contextSource: this.globalProviders }
385
+ ownerHooks,
386
+ bindRun
383
387
  );
384
388
  let contextReady = false;
385
389
  const trace = this.tracesHooks ? [] : void 0;
@@ -426,9 +430,43 @@ var FlowInstance = class extends FlowEntry {
426
430
  const appendContextHooks = async (hooks) => {
427
431
  await materializeAndMerge(hooks);
428
432
  };
429
- const context = new FlowClass(this.metadata, input, scope, appendContextHooks, mergedDeps);
433
+ let entryHooks = [...ownerHooks, ...entryStaticHooks];
434
+ let entryTarget = { ownerId: hookOwnerId, entryClass };
435
+ const retargetEntryHooks = async (ownerId, nextEntryClass) => {
436
+ if (ownerId === entryTarget.ownerId && nextEntryClass === entryTarget.entryClass) return;
437
+ entryTarget = { ownerId, entryClass: nextEntryClass };
438
+ const nextStaticHooks = nextEntryClass ? staticHooksFor(this.hooks.getClsHooks(nextEntryClass), name) : [];
439
+ const nextOwnerHooks = this.hooks.getFlowHooksForOwner(name, ownerId) ?? [];
440
+ const nextHooks = [...nextOwnerHooks, ...nextStaticHooks];
441
+ const leaving = new Set(entryHooks.filter((hook) => !nextHooks.includes(hook)).map((hook) => hook.metadata));
442
+ const joining = nextHooks.filter((hook) => !entryHooks.includes(hook));
443
+ entryHooks = nextHooks;
444
+ if (leaving.size > 0) {
445
+ if (!ownsStages) {
446
+ stages = cloneStageMap(baseStages);
447
+ ownsStages = true;
448
+ }
449
+ for (const key of Object.keys(stages)) {
450
+ stages[key] = stages[key].filter((entry) => !leaving.has(sourceMetadataOf(entry.hook)));
451
+ }
452
+ }
453
+ const joiningOwnerHooks = joining.filter((hook) => nextOwnerHooks.includes(hook));
454
+ await materializeAndMerge(await bindContextHookTargets(joiningOwnerHooks, bindRun), {
455
+ orderStart: registryHookOrder
456
+ });
457
+ registryHookOrder += joiningOwnerHooks.length;
458
+ await materializeAndMerge(joining.filter((hook) => !nextOwnerHooks.includes(hook)));
459
+ };
460
+ const context = new FlowClass(
461
+ this.metadata,
462
+ input,
463
+ scope,
464
+ appendContextHooks,
465
+ mergedDeps,
466
+ retargetEntryHooks
467
+ );
430
468
  contextReady = true;
431
- await materializeAndMerge(initialInjectedHooks, { orderStart: -1e6 });
469
+ await materializeAndMerge(initialInjectedHooks, { orderStart: REGISTRY_HOOK_ORDER_START });
432
470
  if (ownsStages) orderBase = nextStageOrder(stages);
433
471
  await materializeAndMerge(entryStaticHooks);
434
472
  if (this.loggedHookOrders) this.logHookOrderOnce(this.loggedHookOrders, stages, hookOwnerId, entryClass);
@@ -56,6 +56,10 @@ function contextInstanceOf(providers, token) {
56
56
  return typeof instance === "object" && instance !== null ? instance : void 0;
57
57
  };
58
58
  }
59
+ var boundFrom = /* @__PURE__ */ new WeakMap();
60
+ function sourceMetadataOf(metadata) {
61
+ return boundFrom.get(metadata) ?? metadata;
62
+ }
59
63
  async function bindContextHookTargets(hooks, run) {
60
64
  if (!hooks.some((hook) => hook.metadata.contextTarget)) return [...hooks];
61
65
  const bound = [];
@@ -66,10 +70,11 @@ async function bindContextHookTargets(hooks, run) {
66
70
  continue;
67
71
  }
68
72
  const target = await contextTarget(run);
69
- if (target)
70
- bound.push({
71
- metadata: { ...hook.metadata, target, contextTarget: void 0 }
72
- });
73
+ if (target) {
74
+ const metadata = { ...hook.metadata, target, contextTarget: void 0 };
75
+ boundFrom.set(metadata, hook.metadata);
76
+ bound.push({ metadata });
77
+ }
73
78
  }
74
79
  return bound;
75
80
  }
@@ -87,5 +92,6 @@ export {
87
92
  normalizeHooksFromCls,
88
93
  normalizeHooksFromProviders,
89
94
  serverProviderHooks,
95
+ sourceMetadataOf,
90
96
  staticHooksFor
91
97
  };