@zuplo/runtime 6.70.48 → 6.70.49

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.
@@ -1418,6 +1418,72 @@ export declare interface McpTokenExchangeInboundPolicyOptions {
1418
1418
  };
1419
1419
  }
1420
1420
 
1421
+ /**
1422
+ * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
1423
+ * with browser login delegated to WorkOS.
1424
+ *
1425
+ * WorkOS-friendly wrapper around `McpOAuthInboundPolicy`. Provide `clientId`
1426
+ * and `clientSecret`; the constructor derives the WorkOS OIDC issuer, JWKS URL,
1427
+ * authorize URL, and token URL automatically and runs the resulting shape
1428
+ * through the same Zod schema as the generic policy.
1429
+ *
1430
+ * @title MCP WorkOS OAuth
1431
+ * @public
1432
+ * @product mcp-gateway
1433
+ */
1434
+ export declare class McpWorkosOAuthInboundPolicy extends InboundPolicy<McpWorkosOAuthInboundPolicyOptions> {
1435
+ #private;
1436
+ constructor(rawOptions: unknown, policyName: string);
1437
+ handler(
1438
+ request: ZuploRequest,
1439
+ context: ZuploContext
1440
+ ): Promise<ZuploRequest | Response>;
1441
+ }
1442
+
1443
+ /**
1444
+ * The options for this policy.
1445
+ * @public
1446
+ */
1447
+ export declare interface McpWorkosOAuthInboundPolicyOptions {
1448
+ /**
1449
+ * The WorkOS client_id registered for the gateway's browser login flow. The OIDC issuer and JWKS URL are derived from this client ID.
1450
+ */
1451
+ clientId: string;
1452
+ /**
1453
+ * The WorkOS client_secret. Use $env(...) to source from a secret environment variable.
1454
+ */
1455
+ clientSecret: string;
1456
+ /**
1457
+ * OIDC scopes requested during browser login.
1458
+ */
1459
+ scope?: string;
1460
+ /**
1461
+ * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
1462
+ */
1463
+ gateway?: {
1464
+ /**
1465
+ * Lifetime of access tokens issued by /oauth/token.
1466
+ */
1467
+ accessTokenTtlSeconds?: number;
1468
+ /**
1469
+ * Lifetime of refresh tokens issued by /oauth/token.
1470
+ */
1471
+ refreshTokenTtlSeconds?: number;
1472
+ /**
1473
+ * Whether to advertise client_id_metadata_document_supported in AS metadata.
1474
+ */
1475
+ cimdEnabled?: boolean;
1476
+ };
1477
+ /**
1478
+ * Optional overrides for the derived browser-login settings.
1479
+ */
1480
+ browserLoginOverrides?: {
1481
+ remoteTimeoutMs?: number;
1482
+ stateTtlSeconds?: number;
1483
+ sessionTtlSeconds?: number;
1484
+ };
1485
+ }
1486
+
1421
1487
  /**
1422
1488
  * Arbitrary MCP _meta fields to expose downstream.
1423
1489
  * @public
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.70.48",
4
+ "version": "6.70.49",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
@@ -1,30 +0,0 @@
1
-
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Zuplo, Inc. All rights reserved.
4
- *
5
- * This software and associated documentation files (the "Software") is intended to be used
6
- * only by Zuplo customers solely to develop and test applications that will be deployed
7
- * to Zuplo hosted services. You and others in your organization may use these files on your
8
- * Development Devices solely for the above stated purpose.
9
- *
10
- * Outside of uses stated above, no license is granted for any other purpose including
11
- * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
- * sublicense, host, and/or sell copies of the Software.
13
- *
14
- * The software may include third party components with separate legal notices or governed by
15
- * other agreements, as described in licenses either embedded in or accompanying the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
- * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
- * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
- * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
- * DEALINGS IN THE SOFTWARE.
23
- *--------------------------------------------------------------------------------------------*/
24
-
25
- import{$ as C,A as dt,B as je,K as lo,L as a,N as g,O as I,P as ho,R as _,S as h,T as u,U as E,V as R,W as pt,X as mt,Y as S,Z as M,_ as p,a as Me,aa as fo,b as po,ba as lt,ea as n,fa as O,ga as go,j as we,m as mo,s as He,x as ut}from"./chunk-J7JE2DD5.js";import{d as ue}from"./chunk-JRXZBVXH.js";import{a as U}from"./chunk-4SACVMDH.js";import{$ as ct,a as r,aa as A,ba as f,ca as Ue}from"./chunk-ZIKV2LUM.js";O();var Gr=new Set(["localhost","::1"]);function te(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}r(te,"normalizeHostname");function j(e){let t=te(e.hostname);return e.protocol==="http:"&&(Gr.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}r(j,"isLoopbackHttpUrl");var So=new je("gateway-route");function Ro(e,t){So.set(e,t)}r(Ro,"setGatewayRouteContext");function qe(e){return So.get(e)}r(qe,"readGatewayRouteContext");var yo=new je("mcp-oauth-runtime-config");function De(e,t){yo.set(e,t)}r(De,"setMcpOAuthRuntimeConfig");function bo(e){let t=yo.get(e);if(!t)throw new f("MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}r(bo,"requireMcpOAuthRuntimeConfig");var Ae=n.string().trim().min(1),Br=60,Fr=24*60*60,$r=15*Br,Zr=10*365*Fr,_e={accessTokenTtlSeconds:$r,refreshTokenTtlSeconds:Zr,cimdEnabled:!0},Vr=n.object({issuer:n.url(),jwksUrl:n.url(),audience:Ae.optional()}),Wr=n.object({url:n.url(),tokenUrl:n.url().optional(),clientId:Ae.optional(),clientSecret:Ae.optional(),scope:Ae.default("openid profile email"),audience:Ae.optional(),remoteTimeoutMs:n.coerce.number().int().positive().default(1e4),stateTtlSeconds:n.coerce.number().int().positive().default(900),sessionTtlSeconds:n.coerce.number().int().positive().default(28800)}).strict().superRefine((e,t)=>{if(!wo(e.url))for(let o of["tokenUrl","clientId","clientSecret"])e[o]||t.addIssue({code:n.ZodIssueCode.custom,message:`${o} is required for federated browser login`,path:[o]})}),Kr=n.object({accessTokenTtlSeconds:n.coerce.number().int().positive().default(_e.accessTokenTtlSeconds),refreshTokenTtlSeconds:n.coerce.number().int().positive().default(_e.refreshTokenTtlSeconds),cimdEnabled:n.boolean().default(_e.cimdEnabled)}).strict().default(_e),ht=n.object({oidc:Vr,browserLogin:Wr,gateway:Kr.optional().default(_e)}).strict();function Co(e){return wo(e.browserLogin.url)?"local_dev":"federated_oidc"}r(Co,"readBrowserLoginKind");function wo(e){let t;try{t=new URL(e)}catch{return!1}return j(t)&&t.pathname==="/oauth/dev-login"}r(wo,"isLoopbackDevLoginUrl");function Ao(e){return ht.parse(e)}r(Ao,"parseMcpOAuthRuntimeConfig");function Le(){let e;try{e=ut()}catch(t){throw new ct("MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",{cause:t})}return bo(e)}r(Le,"getGatewayOAuthConfig");O();function Ge(e,t,o){let i=e.safeParse(t);if(i.success)return i.data;throw new f(`${o} is misconfigured. Validation failed:
26
- ${Yr(i.error)}`,{cause:i.error})}r(Ge,"parseConfigOrThrow");function Yr(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
27
- `)}r(Yr,"formatZodIssues");var Jr=n.string({error:"auth0Domain is required and must be a string"}).trim().min(1,"auth0Domain is required (commonly set via $env(AUTH0_DOMAIN))").refine(e=>!/[:/]/.test(e),{message:'auth0Domain must be a bare hostname (e.g. "tenant.us.auth0.com"); drop the "https://" prefix and any trailing path'}).refine(e=>e.includes("."),{message:'auth0Domain must be a fully-qualified domain name with at least one dot (e.g. "tenant.us.auth0.com"). If the value looks like "undefined" or is empty, the configured environment variable is likely unset.'}),Xr=n.object({auth0Domain:Jr,audience:n.string().trim().min(1).optional(),clientId:n.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(AUTH0_CLIENT_ID))"),clientSecret:n.string({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(AUTH0_CLIENT_SECRET))"),scope:n.string().trim().min(1).optional(),gateway:n.object({accessTokenTtlSeconds:n.number().int().positive().optional(),refreshTokenTtlSeconds:n.number().int().positive().optional(),cimdEnabled:n.boolean().optional()}).strict().optional(),browserLoginOverrides:n.object({remoteTimeoutMs:n.number().int().positive().optional(),stateTtlSeconds:n.number().int().positive().optional(),sessionTtlSeconds:n.number().int().positive().optional()}).strict().optional()}).strict(),_o=class extends He{static{r(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,o){let i=xo(t,o);super(i,o),this.#t=Io(i,o)}async handler(t,o){return Me("policy.inbound.mcp-auth0-oauth"),De(o,this.#t),xe(t,o)}};function xo(e,t){return Ge(Xr,e,`MCP Auth0 OAuth policy "${t}"`)}r(xo,"parseAuth0OAuthOptions");function zo(e,t="mcp-auth0-oauth-inbound"){let o=xo(e,t);return Io(o,t)}r(zo,"auth0OptionsToMcpOAuthRuntimeConfig");function Io(e,t){let o=`https://${e.auth0Domain}/`,i=`https://${e.auth0Domain}/.well-known/jwks.json`,s=`https://${e.auth0Domain}/authorize`,d=`https://${e.auth0Domain}/oauth/token`;try{return Ao({oidc:{issuer:o,jwksUrl:i,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:s,tokenUrl:d,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",...e.audience===void 0?{}:{audience:e.audience},...e.browserLoginOverrides??{}},gateway:e.gateway})}catch(c){let l=c instanceof Error?` Validation failed: ${c.message}`:"";throw new f(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${l}`,c instanceof Error?{cause:c}:void 0)}}r(Io,"buildAuth0McpOAuthRuntimeConfig");var Qr=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],To={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function ei(e,t,o){switch(e){case"mcp-oauth-inbound":return ft(o,t);case"mcp-auth0-oauth-inbound":return zo(o,t);default:return}}r(ei,"parseMcpOAuthPolicyConfig");function ko(e){return e!==void 0&&Qr.some(t=>t===e)}r(ko,"isMcpOAuthInboundPolicyType");function ti(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===To["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===To["mcp-auth0-oauth-inbound"];default:return!1}}r(ti,"isMcpOAuthRuntimeConfigPolicy");function Sd(e){if(!e)return;let t=e.filter(ti);if(t.length>1){let s=t.map(d=>`"${d.name}" (${d.policyType})`).join(", ");throw new f(`MCP gateway found multiple OAuth policies in policies.json: ${s}. Use exactly one MCP OAuth policy for the gateway so internal OAuth routes resolve a single runtime config.`)}let o=t[0];if(!o)return;let i=ei(o.policyType,o.name,o.handler.options);if(!i)throw new f(`MCP gateway: policy '${o.name}' has unsupported MCP OAuth policy type '${o.policyType}'.`);return{policyName:o.name,config:i}}r(Sd,"resolveMcpOAuthRuntimeConfigFromPolicies");var w="gatewayCode",Cd="upstreamErrorContentType",wd="upstreamErrorHtml",Ad="upstreamErrorStatus",_d="upstreamErrorUrl",de={runtime:{invalid_request:{code:"invalid_request",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},too_many_requests:{code:"too_many_requests",status:429,title:"Too Many Requests",publicDetail:"The request exceeded the allowed rate.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{mcp_route_not_enabled:{code:"mcp_route_not_enabled",status:404,title:"Not Found",publicDetail:"The requested MCP route is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_mcp_route:{code:"unknown_mcp_route",status:400,title:"Bad Request",publicDetail:"The requested MCP route is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},mcp_route_upstream_mismatch:{code:"mcp_route_upstream_mismatch",status:400,title:"Bad Request",publicDetail:"The requested MCP route does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_oauth_discovery_unavailable:{code:"upstream_oauth_discovery_unavailable",status:400,title:"Upstream OAuth discovery unavailable",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,oauthError:"invalid_request"},upstream_provider_access_denied:{code:"upstream_provider_access_denied",status:400,title:"Upstream provider access denied",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",status:400,title:"Upstream OAuth client registration required",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_capability_unavailable:{code:"upstream_capability_unavailable",status:503,title:"Service Unavailable",publicDetail:"The upstream capability is unavailable. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},Ne={...de.runtime,...de.config,...de.downstream_auth,...de.downstream_oauth,...de.upstream_auth,...de.upstream_mcp};function oe(e){return typeof e=="string"&&Object.hasOwn(Ne,e)}r(oe,"isGatewayProblemCode");function xd(e){return oe(e)&&ne(e).callbackFailure===!0}r(xd,"isGatewayCallbackFailureCode");function ne(e){return Ne[e]}r(ne,"readGatewayProblemDefinition");function vo(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";default:return"internal_server_error"}}r(vo,"readDefaultGatewayProblemCodeForStatus");var oi=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Po(e,t){let o;try{o=new URL(e)}catch{throw new f(`${t} must be an absolute URL.`)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw new f(`${t} must be an HTTP(S) URL.`);return e}r(Po,"assertHttpUrl");function Eo(e){return e.options??{}}r(Eo,"readHandlerOptions");function ni(e){let t=oi.exec(e);if(t){let o=t[1],i=ue[o];if(typeof i!="string"||i==="")throw new f(`MCP route handler rewritePattern references env.${o}, but that environment variable is not set.`);return Po(i,`env.${o}`)}if(e.includes("${"))throw new f("MCP token exchange requires a static route handler rewritePattern. Dynamic request-based rewrite patterns are not supported for MCP upstream OAuth.");return Po(e,"MCP route handler rewritePattern")}r(ni,"readRewritePatternUrl");function gt(e){let t=Eo(e);if(typeof t.rewritePattern=="string"&&t.rewritePattern!=="")return ni(t.rewritePattern);throw new f("MCP route must configure handler.options.rewritePattern.")}r(gt,"readMcpRouteUpstreamUrl");function vd(e){let t=Eo(e.handler),o=new URL(gt(e.handler));if(t.forwardSearch!==!1)for(let[s,d]of new URL(e.request.url).searchParams)o.searchParams.append(s,d);let i={method:e.request.method,body:e.body,headers:e.headers,redirect:t.followRedirects===!0?"follow":"manual",zuplo:typeof t.mtlsCertificate=="string"&&t.mtlsCertificate.length>0?{mtlsCertificate:t.mtlsCertificate}:void 0};return{url:o.toString(),init:i}}r(vd,"buildMcpRouteUpstreamFetch");O();var ri=["shared-oauth","user-oauth"],ii=["none","client_secret_basic","client_secret_post"],q=n.string().min(1).brand(),D=n.string().min(1),B=n.string().min(1).brand(),St=n.enum(ri),Rt=n.enum(ii);O();var Oo="2025-11-25";var ai="io.modelcontextprotocol/related-task",$e="2.0",z=fo(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Uo=R([a(),g().int()]),Mo=a(),Hd=E({ttl:g().optional(),pollInterval:g().optional()}),si=u({ttl:g().optional()}),ci=u({taskId:a()}),Ct=E({progressToken:Uo.optional(),[ai]:ci.optional()}),H=u({_meta:Ct.optional()}),Ze=H.extend({task:si.optional()});var v=u({method:a(),params:H.loose().optional()}),L=u({_meta:Ct.optional()}),G=u({method:a(),params:L.loose().optional()}),P=E({_meta:Ct.optional()}),Ve=R([a(),g().int()]),ui=u({jsonrpc:p($e),id:Ve,...v.shape}).strict();var di=u({jsonrpc:p($e),...G.shape}).strict();var Ho=u({jsonrpc:p($e),id:Ve,result:P}).strict();var Be;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Be||(Be={}));var jo=u({jsonrpc:p($e),id:Ve.optional(),error:u({code:g().int(),message:a(),data:_().optional()})}).strict();var jd=R([ui,di,Ho,jo]),qd=R([Ho,jo]),qo=P.strict(),pi=L.extend({requestId:Ve.optional(),reason:a().optional()}),Do=G.extend({method:p("notifications/cancelled"),params:pi}),mi=u({src:a(),mimeType:a().optional(),sizes:h(a()).optional(),theme:M(["light","dark"]).optional()}),ze=u({icons:h(mi).optional()}),pe=u({name:a(),title:a().optional()}),me=pe.extend({...pe.shape,...ze.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),li=mt(u({applyDefaults:I().optional()}),S(a(),_())),hi=lt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,mt(u({form:li.optional(),url:z.optional()}),S(a(),_()).optional())),fi=E({list:z.optional(),cancel:z.optional(),requests:E({sampling:E({createMessage:z.optional()}).optional(),elicitation:E({create:z.optional()}).optional()}).optional()}),gi=E({list:z.optional(),cancel:z.optional(),requests:E({tools:E({call:z.optional()}).optional()}).optional()}),Si=u({experimental:S(a(),z).optional(),sampling:u({context:z.optional(),tools:z.optional()}).optional(),elicitation:hi.optional(),roots:u({listChanged:I().optional()}).optional(),tasks:fi.optional(),extensions:S(a(),z).optional()}),Ri=H.extend({protocolVersion:a(),capabilities:Si,clientInfo:me}),yi=v.extend({method:p("initialize"),params:Ri});var bi=u({experimental:S(a(),z).optional(),logging:z.optional(),completions:z.optional(),prompts:u({listChanged:I().optional()}).optional(),resources:u({subscribe:I().optional(),listChanged:I().optional()}).optional(),tools:u({listChanged:I().optional()}).optional(),tasks:gi.optional(),extensions:S(a(),z).optional()}),Ci=P.extend({protocolVersion:a(),capabilities:bi,serverInfo:me,instructions:a().optional()}),wi=G.extend({method:p("notifications/initialized"),params:L.optional()});var Lo=v.extend({method:p("ping"),params:H.optional()}),Ai=u({progress:g(),total:C(g()),message:C(a())}),_i=u({...L.shape,...Ai.shape,progressToken:Uo}),Go=G.extend({method:p("notifications/progress"),params:_i}),xi=H.extend({cursor:Mo.optional()}),Ie=v.extend({params:xi.optional()}),Te=P.extend({nextCursor:Mo.optional()}),zi=M(["working","input_required","completed","failed","cancelled"]),ke=u({taskId:a(),status:zi,ttl:R([g(),ho()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:C(g()),statusMessage:C(a())}),No=P.extend({task:ke}),Ii=L.merge(ke),Bo=G.extend({method:p("notifications/tasks/status"),params:Ii}),Fo=v.extend({method:p("tasks/get"),params:H.extend({taskId:a()})}),$o=P.merge(ke),Zo=v.extend({method:p("tasks/result"),params:H.extend({taskId:a()})}),Dd=P.loose(),Vo=Ie.extend({method:p("tasks/list")}),Wo=Te.extend({tasks:h(ke)}),Ko=v.extend({method:p("tasks/cancel"),params:H.extend({taskId:a()})}),Ld=P.merge(ke),Yo=u({uri:a(),mimeType:C(a()),_meta:S(a(),_()).optional()}),Jo=Yo.extend({text:a()}),wt=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Xo=Yo.extend({blob:wt}),ve=M(["user","assistant"]),le=u({audience:h(ve).optional(),priority:g().min(0).max(1).optional(),lastModified:lo.datetime({offset:!0}).optional()}),Qo=u({...pe.shape,...ze.shape,uri:a(),description:C(a()),mimeType:C(a()),size:C(g()),annotations:le.optional(),_meta:C(E({}))}),Ti=u({...pe.shape,...ze.shape,uriTemplate:a(),description:C(a()),mimeType:C(a()),annotations:le.optional(),_meta:C(E({}))}),ki=Ie.extend({method:p("resources/list")}),vi=Te.extend({resources:h(Qo)}),Pi=Ie.extend({method:p("resources/templates/list")}),Ei=Te.extend({resourceTemplates:h(Ti)}),At=H.extend({uri:a()}),Oi=At,Ui=v.extend({method:p("resources/read"),params:Oi}),Mi=P.extend({contents:h(R([Jo,Xo]))}),Hi=G.extend({method:p("notifications/resources/list_changed"),params:L.optional()}),ji=At,qi=v.extend({method:p("resources/subscribe"),params:ji}),Di=At,Li=v.extend({method:p("resources/unsubscribe"),params:Di}),Gi=L.extend({uri:a()}),Ni=G.extend({method:p("notifications/resources/updated"),params:Gi}),Bi=u({name:a(),description:C(a()),required:C(I())}),Fi=u({...pe.shape,...ze.shape,description:C(a()),arguments:C(h(Bi)),_meta:C(E({}))}),$i=Ie.extend({method:p("prompts/list")}),Zi=Te.extend({prompts:h(Fi)}),Vi=H.extend({name:a(),arguments:S(a(),a()).optional()}),Wi=v.extend({method:p("prompts/get"),params:Vi}),_t=u({type:p("text"),text:a(),annotations:le.optional(),_meta:S(a(),_()).optional()}),xt=u({type:p("image"),data:wt,mimeType:a(),annotations:le.optional(),_meta:S(a(),_()).optional()}),zt=u({type:p("audio"),data:wt,mimeType:a(),annotations:le.optional(),_meta:S(a(),_()).optional()}),Ki=u({type:p("tool_use"),name:a(),id:a(),input:S(a(),_()),_meta:S(a(),_()).optional()}),Yi=u({type:p("resource"),resource:R([Jo,Xo]),annotations:le.optional(),_meta:S(a(),_()).optional()}),Ji=Qo.extend({type:p("resource_link")}),It=R([_t,xt,zt,Ji,Yi]),Xi=u({role:ve,content:It}),Qi=P.extend({description:a().optional(),messages:h(Xi)}),ea=G.extend({method:p("notifications/prompts/list_changed"),params:L.optional()}),ta=u({title:a().optional(),readOnlyHint:I().optional(),destructiveHint:I().optional(),idempotentHint:I().optional(),openWorldHint:I().optional()}),oa=u({taskSupport:M(["required","optional","forbidden"]).optional()}),en=u({...pe.shape,...ze.shape,description:a().optional(),inputSchema:u({type:p("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(_()),outputSchema:u({type:p("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(_()).optional(),annotations:ta.optional(),execution:oa.optional(),_meta:S(a(),_()).optional()}),na=Ie.extend({method:p("tools/list")}),ra=Te.extend({tools:h(en)}),tn=P.extend({content:h(It).default([]),structuredContent:S(a(),_()).optional(),isError:I().optional()}),Gd=tn.or(P.extend({toolResult:_()})),ia=Ze.extend({name:a(),arguments:S(a(),_()).optional()}),aa=v.extend({method:p("tools/call"),params:ia}),sa=G.extend({method:p("notifications/tools/list_changed"),params:L.optional()}),Nd=u({autoRefresh:I().default(!0),debounceMs:g().int().nonnegative().default(300)}),on=M(["debug","info","notice","warning","error","critical","alert","emergency"]),ca=H.extend({level:on}),ua=v.extend({method:p("logging/setLevel"),params:ca}),da=L.extend({level:on,logger:a().optional(),data:_()}),pa=G.extend({method:p("notifications/message"),params:da}),ma=u({name:a().optional()}),la=u({hints:h(ma).optional(),costPriority:g().min(0).max(1).optional(),speedPriority:g().min(0).max(1).optional(),intelligencePriority:g().min(0).max(1).optional()}),ha=u({mode:M(["auto","required","none"]).optional()}),fa=u({type:p("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:h(It).default([]),structuredContent:u({}).loose().optional(),isError:I().optional(),_meta:S(a(),_()).optional()}),ga=pt("type",[_t,xt,zt]),Fe=pt("type",[_t,xt,zt,Ki,fa]),Sa=u({role:ve,content:R([Fe,h(Fe)]),_meta:S(a(),_()).optional()}),Ra=Ze.extend({messages:h(Sa),modelPreferences:la.optional(),systemPrompt:a().optional(),includeContext:M(["none","thisServer","allServers"]).optional(),temperature:g().optional(),maxTokens:g().int(),stopSequences:h(a()).optional(),metadata:z.optional(),tools:h(en).optional(),toolChoice:ha.optional()}),ya=v.extend({method:p("sampling/createMessage"),params:Ra}),ba=P.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens"]).or(a())),role:ve,content:ga}),Ca=P.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:ve,content:R([Fe,h(Fe)])}),wa=u({type:p("boolean"),title:a().optional(),description:a().optional(),default:I().optional()}),Aa=u({type:p("string"),title:a().optional(),description:a().optional(),minLength:g().optional(),maxLength:g().optional(),format:M(["email","uri","date","date-time"]).optional(),default:a().optional()}),_a=u({type:M(["number","integer"]),title:a().optional(),description:a().optional(),minimum:g().optional(),maximum:g().optional(),default:g().optional()}),xa=u({type:p("string"),title:a().optional(),description:a().optional(),enum:h(a()),default:a().optional()}),za=u({type:p("string"),title:a().optional(),description:a().optional(),oneOf:h(u({const:a(),title:a()})),default:a().optional()}),Ia=u({type:p("string"),title:a().optional(),description:a().optional(),enum:h(a()),enumNames:h(a()).optional(),default:a().optional()}),Ta=R([xa,za]),ka=u({type:p("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:u({type:p("string"),enum:h(a())}),default:h(a()).optional()}),va=u({type:p("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:u({anyOf:h(u({const:a(),title:a()}))}),default:h(a()).optional()}),Pa=R([ka,va]),Ea=R([Ia,Ta,Pa]),Oa=R([Ea,wa,Aa,_a]),Ua=Ze.extend({mode:p("form").optional(),message:a(),requestedSchema:u({type:p("object"),properties:S(a(),Oa),required:h(a()).optional()})}),Ma=Ze.extend({mode:p("url"),message:a(),elicitationId:a(),url:a().url()}),Ha=R([Ua,Ma]),ja=v.extend({method:p("elicitation/create"),params:Ha}),qa=L.extend({elicitationId:a()}),Da=G.extend({method:p("notifications/elicitation/complete"),params:qa}),La=P.extend({action:M(["accept","decline","cancel"]),content:lt(e=>e===null?void 0:e,S(a(),R([a(),g(),I(),h(a())])).optional())}),Ga=u({type:p("ref/resource"),uri:a()});var Na=u({type:p("ref/prompt"),name:a()}),Ba=H.extend({ref:R([Na,Ga]),argument:u({name:a(),value:a()}),context:u({arguments:S(a(),a()).optional()}).optional()}),Fa=v.extend({method:p("completion/complete"),params:Ba});var $a=P.extend({completion:E({values:h(a()).max(100),total:C(g().int()),hasMore:C(I())})}),Za=u({uri:a().startsWith("file://"),name:a().optional(),_meta:S(a(),_()).optional()}),Va=v.extend({method:p("roots/list"),params:H.optional()}),Wa=P.extend({roots:h(Za)}),Ka=G.extend({method:p("notifications/roots/list_changed"),params:L.optional()}),Bd=R([Lo,yi,Fa,ua,Wi,$i,ki,Pi,Ui,qi,Li,aa,na,Fo,Zo,Vo,Ko]),Fd=R([Do,Go,wi,Ka,Bo]),$d=R([qo,ba,Ca,La,Wa,$o,Wo,No]),Zd=R([Lo,ya,ja,Va,Fo,Zo,Vo,Ko]),Vd=R([Do,Go,pa,Ni,Hi,sa,ea,Bo,Da]),Wd=R([qo,Ci,$a,Qi,Zi,vi,Ei,Mi,tn,ra,$o,Wo,No]),yt=class e extends Error{static{r(this,"McpError")}constructor(t,o,i){super(`MCP error ${t}: ${o}`),this.code=t,this.data=i,this.name="McpError"}static fromError(t,o,i){if(t===Be.UrlElicitationRequired&&i){let s=i;if(s.elicitations)return new bt(s.elicitations,o)}return new e(t,o,i)}},bt=class extends yt{static{r(this,"UrlElicitationRequiredError")}constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(Be.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};O();var rn=q,Ya=n.object({mode:n.literal("auto")}).strict(),Ja=n.object({mode:n.literal("manual"),clientId:n.string().trim().min(1),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:Rt.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:n.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),an=n.discriminatedUnion("mode",[Ya,Ja]),Xa=an.default({mode:"auto"}),Qa=n.object({scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:Xa}).strict(),nn=Qa.extend({redirectPath:n.string().startsWith("/auth/connections/")}).strict(),es=n.discriminatedUnion("mode",[n.object({mode:n.literal("shared-oauth"),oauth:nn}).strict(),n.object({mode:n.literal("user-oauth"),oauth:nn}).strict()]),ts=n.object({baseUrl:n.url(),resourceMetadataUrl:n.url()}).strict(),tp=n.object({displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:me.optional(),transport:ts}).strict(),os=n.object({id:rn,displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:me.optional(),protectedResourceMetadataUrl:n.url().optional(),authMode:St,authConfig:es}).strict().refine(e=>e.authMode===e.authConfig.mode,{message:"authMode must match authConfig.mode",path:["authConfig","mode"]}),ns={id:rn.optional(),displayName:n.string().min(1),summary:n.string().min(1).optional(),serverInfo:me.optional(),protectedResourceMetadataUrl:n.url().optional()},rs=n.object({...ns,authMode:St,scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:an.optional(),clientId:n.string().trim().min(1).optional(),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:Rt.optional()}).strict();function is(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
28
- `)}r(is,"formatZodIssues");function as(e){let t="mcp-token-exchange-";if(!e.startsWith(t))throw new f(`MCP token exchange policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`);return q.parse(e.slice(t.length))}r(as,"inferUpstreamConnectionIdFromPolicyName");function sn(e){let t=new URL(e),o=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${o}`}r(sn,"buildDefaultProtectedResourceMetadataUrl");function cn(e,t){return B.parse(`${e}:${t}`)}r(cn,"buildUpstreamAuthProfileId");function ss(e,t){let o=e.clientRegistration??(e.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:e.clientId,tokenEndpointAuthMethod:e.tokenEndpointAuthMethod??"client_secret_basic",...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret}});return{mode:e.authMode,oauth:{scopes:e.scopes,scopeDelimiter:e.scopeDelimiter,redirectPath:`/auth/connections/${encodeURIComponent(t)}/callback`,clientRegistration:o}}}r(ss,"resolveAuthConfig");function un(e,t){try{let o=rs.parse(e),i=o.id??(t===void 0?void 0:as(t));if(i===void 0)throw new f("MCP token exchange policy options must include id when policy name is unavailable.");return os.parse({id:i,displayName:o.displayName,...o.summary===void 0?{}:{description:o.summary},...o.serverInfo===void 0?{}:{serverInfo:o.serverInfo},...o.protectedResourceMetadataUrl===void 0?{}:{protectedResourceMetadataUrl:o.protectedResourceMetadataUrl},authMode:o.authMode,authConfig:ss(o,i)})}catch(o){if(o instanceof n.ZodError){let i=t===void 0?"MCP token exchange policy":`Policy "${t}"`;throw new f(`${i} is misconfigured. Missing/invalid options in policies.json:
29
- ${is(o)}`,{cause:o})}throw o}}r(un,"parseUpstreamTokenExchangePolicyOptions");function op(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}r(op,"isUpstreamOAuthAuthConfig");var cs="mcp-token-exchange-inbound";function dn(e,t,o){let i=new f(t,o===void 0?void 0:{cause:o});return i.extensionMembers={[w]:e},i}r(dn,"configurationProblem");function pn(e){return e===cs}r(pn,"isMcpTokenExchangePolicyType");function us(e){let t=cn(e.connection.id,e.connection.authMode);return{policyName:e.policyName,upstreamServerId:e.connection.id,displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},mcpUrl:e.mcpUrl,protectedResourceMetadataUrl:e.connection.protectedResourceMetadataUrl??sn(e.mcpUrl),authMode:e.connection.authMode,authProfileId:t,authConfig:e.connection.authConfig}}r(us,"buildRegisteredConnection");function ds(e){let t=new Map;for(let o of e){if(t.has(o.name))throw new f(`Duplicate policy name ${o.name} in policies.json.`);t.set(o.name,{name:o.name,policyType:o.policyType,handler:{options:o.handler.options}})}return t}r(ds,"buildPolicyMap");function ps(e){if(typeof e.raw!="function")throw new f(`MCP route ${e.path} must declare operationId in routes.oas.json. The operationId is used as the stable MCP route identity for OAuth tokens, storage, upstream auth state, and analytics.`);let t=e.raw();if(!t||typeof t.operationId!="string"||t.operationId==="")throw new f(`MCP route ${e.path} must declare operationId in routes.oas.json. The operationId is used as the stable MCP route identity for OAuth tokens, storage, upstream auth state, and analytics.`);return D.parse(t.operationId)}r(ps,"readOperationId");function ms(e){let t=[];for(let o of e.route.policies?.inbound??[]){let i=e.policyByName.get(o);i&&pn(i.policyType)&&t.push(i)}if(t.length>1)throw new f(`MCP route ${e.route.path} must bind at most one MCP token exchange policy; found ${t.length}.`);if(t.length!==0)return e.readConnectionForPolicy(t[0],gt(e.route.handler))}r(ms,"readRouteUpstreamConnection");function ls(e){let t=new Map,o=new Map,i=new Map,s=new Set;function d(c,l){let y=i.get(c.name);if(y)return y;let x=un(c.handler.options,c.name);if(s.has(x.id))throw new f(`Duplicate upstream MCP connection id ${x.id} in policies.json.`);s.add(x.id);let F=us({policyName:c.name,connection:x,mcpUrl:l});return i.set(c.name,F),F}r(d,"readConnectionForPolicy");for(let c of e.routes){let l=c.policies?.inbound??[];if(l.length===0||!l.map(K=>e.policyByName.get(K)).filter(K=>K!==void 0).some(K=>ko(K.policyType)||pn(K.policyType)))continue;let x=ps(c);if(t.has(x))throw new f(`Duplicate MCP route operationId ${x} across routes.`);if(o.has(c.path))throw new f(`Duplicate MCP route path ${c.path} across routes.`);let F=ms({route:c,policyByName:e.policyByName,readConnectionForPolicy:d}),ye={operationId:x,routePath:c.path,...F===void 0?{}:{connection:F}};t.set(x,ye),o.set(c.path,ye)}return{byOperationId:t,byRoutePath:o,connectionsByPolicyName:i}}r(ls,"buildMcpRoutes");function hs(e){let t=ds(e.policies),{byOperationId:o,byRoutePath:i,connectionsByPolicyName:s}=ls({routes:e.routes,policyByName:t}),d=new Map;for(let c of s.values())d.set(c.upstreamServerId,c);return{byOperationId:o,byRoutePath:i,connectionsById:d}}r(hs,"buildGatewayConnectionRegistry");var re,Tt;function pp(e){Tt=e,re=void 0}r(pp,"configureGatewayConnectionRegistrySource");function mp(e){re=e}r(mp,"setGatewayConnectionRegistry");function mn(){if(!re&&Tt&&(re=hs(Tt)),!re)throw new f("MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one OAuth-protected MCP route and policies.json registers the matching MCP OAuth and upstream connection policies.");return re}r(mn,"getGatewayConnectionRegistry");function ie(e){let o=mn().byOperationId.get(e);if(!o)throw dn("unknown_mcp_route",`Unknown MCP route: ${e}`,new Error(`Unknown MCP route "${e}". Ensure routes.oas.json declares this operationId and policies.json registers the matching MCP upstream connection policy.`));return o}r(ie,"getRegisteredMcpRoute");function We(e){let o=mn().byRoutePath.get(e);if(!o)throw dn("unknown_mcp_route",`Unknown MCP route: ${e}`,new Error(`Unknown MCP route path "${e}". Ensure routes.oas.json declares this path with operationId and policies.json registers the matching MCP OAuth or MCP token exchange policy.`));return o}r(We,"getRegisteredMcpRouteByRoutePath");function lp(){return re}r(lp,"tryGetGatewayConnectionRegistry");O();var m=n.string().datetime({offset:!0}).brand();function ln(e){return m.parse(e.toISOString())}r(ln,"toIsoTimestamp");function Sp(e,t){return new Date(e.getTime()+t*1e3)}r(Sp,"addSeconds");O();function Ke(e,t){return e?.get(t)?.split(",",1)[0]?.trim()??""}r(Ke,"readHeaderValue");function fs(e){if(e===void 0)return"";let t=e.trim();return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}r(fs,"unquoteForwardedValue");function gs(e){let t=Ke(e,"forwarded");if(t){let s=Object.fromEntries(t.split(";").map(l=>l.trim().split("=",2)).filter(l=>l.length===2).map(([l,y])=>[l.toLowerCase(),fs(y)])),d=s.proto,c=s.host;if(d||c)return{...d===void 0?{}:{proto:d},...c===void 0?{}:{host:c}}}let o=Ke(e,"x-forwarded-proto"),i=Ke(e,"x-forwarded-host");return!o&&!i?{}:{...o?{proto:o}:{},...i?{host:i}:{}}}r(gs,"readForwardedOriginHints");function kt(e,t){let o=e.toLowerCase();if(!(o!=="https"&&o!=="http"))try{let i=new URL(`${o}://${t}`);return i.username||i.password||i.pathname!=="/"?void 0:i.origin}catch{return}}r(kt,"parseHttpOrigin");function Ss(e,t){let o=Ke(t,"host");if(!o)return;let i=gs(t);if(i.host!==void 0){let s=kt(i.proto??e.protocol.replace(/:$/u,""),i.host),d=kt(i.proto??e.protocol.replace(/:$/u,""),o);if(s!==void 0&&d!==void 0&&new URL(s).host!==new URL(d).host)return}return kt(i.proto??e.protocol.replace(/:$/u,""),o)}r(Ss,"readHostOrigin");function J(e,t){let o=new URL(e),i=Ss(o,t);return i!==void 0?i:o.origin}r(J,"readGatewayRequestOrigin");function Pe(e,t){return J(e,t)}r(Pe,"readGatewayOAuthIssuer");function vt(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}r(vt,"truncate");function hn(e){return"cause"in e?e.cause:void 0}r(hn,"readCause");function Pt(e,t,o){if(!(o instanceof Error)){o!=null&&(e[`${t}Message`]=vt(String(o)));return}e[`${t}Name`]=o.name,e[`${t}Message`]=vt(o.message);let i=hn(o);for(let s=1;s<=4&&i instanceof Error;s+=1){let d=s===1?"cause":`cause${s}`;e[`${d}Name`]=i.name,e[`${d}Message`]=vt(i.message),i=hn(i)}}r(Pt,"addErrorLogFields");function X(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}r(X,"safeHost");function fn(e,t){let o=Object.entries(t).filter(i=>i[1]!==void 0);o.length!==0&&e.log.setLogProperties?.(Object.fromEntries(o))}r(fn,"setLogProperties");function Et(e,t){fn(e,{subjectId:t.subjectId})}r(Et,"applyGatewayUserLogProperties");function gn(e,t){fn(e,{upstreamServerId:t.upstreamServerId,operationId:t.operationId})}r(gn,"applyGatewayRouteLogProperties");function Op(e){let t=ne(e);return{title:t.title,body:t.publicDetail}}r(Op,"readGatewayCallbackFailureContent");function Ye(e){if(!(e instanceof A))return;let t=e.extensionMembers?.[w];return oe(t)?t:void 0}r(Ye,"readGatewayProblemCode");function ae(e,t,o){let i=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...o===void 0?{}:{cause:o}}:e,s=ne(i.code),d=i.privateDetail??(Je(i.code)?i.publicDetail??s.publicDetail:s.publicDetail),c=Rs(i);return new A({message:d,extensionMembers:{[w]:i.code}},c===void 0?void 0:{cause:c})}r(ae,"createGatewayRuntimeError");async function he(e,t,o){let i=ne(o.code),s=ys(o.code,o.detail),d=Je(o.code)?o.title??i.title:i.title,l={problem:{...we.getProblemFromStatus(i.status,{detail:s,instance:o.instance,type:o.type}),...o.extensions??{},status:i.status,title:d,detail:s,code:o.code}};return o.headers!==void 0&&(l.additionalHeaders=o.headers),we.format(l,e,t)}r(he,"gatewayProblemResponse");function Je(e){return ne(e).status<500}r(Je,"canExposeGatewayProblemDetail");function Rs(e){return!e.privateDetail||Je(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}r(Rs,"readRuntimeErrorCause");function ys(e,t){let o=ne(e);return Je(e)&&t||o.publicDetail}r(ys,"readSafeGatewayProblemDetail");var bs=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function Cs(e){return e.protocol.replace(/:$/u,"").toLowerCase()}r(Cs,"readScheme");function ws(e){return e.protocol==="https:"}r(ws,"isSpecCompliantRedirectUri");function As(e){let t=Cs(e);return t.length>0&&t!=="http"&&t!=="https"&&!bs.has(t)}r(As,"isNativeAppCustomSchemeRedirectUri");var Rn=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:r(e=>ws(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:r(e=>j(e),"accepts"),matches:r((e,t)=>j(e)&&j(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:r(e=>As(e),"accepts")}];function jp(e){let t=Rn.find(o=>o.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}r(jp,"evaluateBuiltInRedirectUriCompatibility");function Sn(e){try{return new URL(e)}catch{return}}r(Sn,"parseUrl");function yn(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=Sn(e.registeredRedirectUri),o=Sn(e.requestedRedirectUri);if(t===void 0||o===void 0)return!1;let i=e.context??{source:"registration_match"};return Rn.some(s=>s.matches?.(t,o,i))}r(yn,"redirectUriMatchesBuiltInCompatibility");O();var _s=43,xs=128,zs=/^[A-Za-z0-9._~-]+$/,Ot="S256",Gp=n.literal(Ot),Np=n.string().min(_s).max(xs).regex(zs);function Xe(e){return e.replace(/^\/+/,"").split("/").map(t=>encodeURIComponent(t)).join("/")}r(Xe,"encodeMcpRoutePathForScopedOAuthRoute");function bn(e){let t=typeof e=="string"?e:"";return t===""?"":`/${t.replace(/^\/+/,"")}`}r(bn,"decodeMcpRoutePathFromScopedOAuthParam");O();var Cn=["none","client_secret_post","client_secret_basic","private_key_jwt"],Ut=[...Cn],Is=["awaiting_login","awaiting_setup"],Ts=n.string().min(1).brand(),Z=n.string().min(1).brand(),Ee=n.uuid().brand(),Y=n.uuid().brand(),ks=n.uuid().brand(),vs=n.enum(Cn),Ps=n.enum(Ut),Kp=n.enum(Is),Yp=n.object({client_id:Z,client_name:n.string().min(1),redirect_uris:n.array(n.string().min(1)).min(1),jwks_uri:n.string().min(1).optional(),token_endpoint_auth_method:Ps}).superRefine((e,t)=>{e.token_endpoint_auth_method==="private_key_jwt"&&e.jwks_uri===void 0&&t.addIssue({code:"custom",path:["jwks_uri"],message:"jwks_uri is required for private_key_jwt clients."})}),Mt=n.object({clientId:Z,clientName:n.string().min(1),redirectUris:n.array(n.string().min(1)),tokenEndpointAuthMethod:vs,jwksUri:n.string().min(1).optional(),hashedClientSecret:n.string().optional(),clientSecretExpiresAt:m.optional(),clientExpiresAt:m,revokedAt:m.optional(),createdAt:m}),wn=n.object({clientId:Z,resource:n.string(),operationId:D,subjectId:Ts,scope:n.string(),roles:n.array(n.string()),createdAt:m,expiresAt:m}),Ht=wn.extend({id:Ee,currentRefreshTokenHash:n.string().optional(),previousRefreshTokenHash:n.string().optional(),previousRefreshTokenRotatedAt:m.optional(),revokedAt:m.optional(),revokedReason:n.string().optional()}),Qe=wn.extend({tokenHash:n.string(),grantId:Ee,revokedAt:m.optional()});function Jp(){return Y.parse(crypto.randomUUID())}r(Jp,"createDownstreamAuthorizationTransactionId");function Xp(){return ks.parse(crypto.randomUUID())}r(Xp,"createDownstreamBrowserLoginStateId");function Qp(){return Ee.parse(crypto.randomUUID())}r(Qp,"createDownstreamGrantId");var V="mcp:tools";function mm(e,t){return yn({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}r(mm,"redirectUriMatchesRegistration");function lm(e){return j(e)&&e.pathname==="/oauth/dev-login"}r(lm,"isLoopbackDevLoginUrl");function et(e,t,o){return new URL(e,Pe(t,o)).toString()}r(et,"buildGatewayOAuthUrl");function jt(e){let t=ie(D.parse(e.operationId));return new URL(t.routePath,J(e.requestUrl,e.requestHeaders)).toString()}r(jt,"buildScopedAuthorizationServerIssuer");function Es(e){let t=ie(D.parse(e.operationId));return new URL(`/oauth/authorize/${Xe(t.routePath)}`,J(e.requestUrl,e.requestHeaders)).toString()}r(Es,"buildScopedAuthorizationEndpoint");function Os(e,t){let o=Le();return{issuer:Pe(e,t),authorization_endpoint:et("/oauth/authorize",e,t),token_endpoint:et("/oauth/token",e,t),registration_endpoint:et("/oauth/register",e,t),revocation_endpoint:et("/oauth/revoke",e,t),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[V],code_challenge_methods_supported:[Ot],token_endpoint_auth_methods_supported:Ut,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","private_key_jwt","none"],client_id_metadata_document_supported:o.gateway.cimdEnabled,"x-zuplo-browser-login-kind":Co(o)}}r(Os,"buildAuthorizationServerMetadata");function hm(e){let t=jt(e);return{...Os(e.requestUrl,e.requestHeaders),issuer:t,authorization_endpoint:Es(e)}}r(hm,"buildScopedAuthorizationServerMetadata");var An=Oo;async function xm(e,t){try{let o=Ms(e.params.routePath);return Response.json(Us(o.operationId,e.url,e.headers))}catch(o){let i=Ye(o);return he(e,t,{code:i==="unknown_mcp_route"?i:"not_found",detail:(o instanceof Error?o.message:void 0)??"The requested protected resource metadata document was not found."})}}r(xm,"protectedResourceMetadataHandler");function Us(e,t,o){let i=ie(e);return{resource:qt(i.operationId,t,o),resource_name:i.routePath,authorization_servers:[jt({operationId:i.operationId,requestUrl:t,requestHeaders:o})],bearer_methods_supported:["header"],scopes_supported:[V],mcp_protocol_version:An}}r(Us,"buildProtectedResourceMetadataResponseBody");function qt(e,t,o){let i=ie(e);return new URL(i.routePath,J(t,o)).toString()}r(qt,"buildCanonicalMcpResourceForRoute");function _n(e,t,o){let i=ie(e);return new URL(`/.well-known/oauth-protected-resource/${Xe(i.routePath)}`,J(t,o)).toString()}r(_n,"buildProtectedResourceMetadataUrlForRoute");function Ms(e){return We(bn(e))}r(Ms,"getRegisteredMcpRouteByExternalPathParam");O();var T=n.string().min(1).brand();var Hs=n.record(n.string(),n.unknown()),xn=n.string().min(1),js=n.union([xn.transform(e=>[e]),n.array(xn)]);var qs=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Ds=["https://zuplo.com/roles","roles","role","permissions","groups"];function Ls(e){let t=Hs.safeParse(e);return t.success?t.data:{}}r(Ls,"toClaimRecord");function Gs(e){return e.issues[0]?.message??"Gateway request user is invalid"}r(Gs,"readValidationFailureDetail");function Ns(e,t,o,i){for(let c of qs){let l=T.safeParse(t[c]);if(l.success)return l.data}let s=T.safeParse(e?.sub);if(!s.success)throw ae("identity_context_missing",Gs(s.error));let d=typeof t.iss=="string"?t.iss:void 0;return!d||d===Pe(o,i)?s.data:T.parse(`${d}|${s.data}`)}r(Ns,"readNormalizedSubjectId");function Bs(e){let t=new Set;for(let o of Ds){let i=js.safeParse(e[o]);if(i.success)for(let s of i.data)t.add(s)}return t.size>0?[...t]:void 0}r(Bs,"readRoles");function Fs(e,t,o){let i=Ls(e?.data),s={subjectId:Ns(e,i,t,o)},d=Bs(i);return d&&(s.roles=d),s}r(Fs,"parseGatewayRequestUser");function zn(e,t,o){try{return Fs(e,t,o)}catch{return}}r(zn,"tryParseGatewayRequestUser");function tt(e){let o=['realm="OAuth"',`resource_metadata="${Dt(_n(e.operationId,e.requestUrl,e.requestHeaders))}"`];return e.error!==void 0&&o.push(`error="${e.error}"`),e.errorDescription!==void 0&&o.push(`error_description="${Dt(e.errorDescription)}"`),e.scope!==void 0&&o.push(`scope="${Dt(e.scope)}"`),`Bearer ${o.join(", ")}`}r(tt,"buildGatewayBearerChallenge");function Dt(e){let t="";for(let o=0;o<e.length;o+=1){let i=e.charCodeAt(o);i<=31||i===127||(t+=e[o])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}r(Dt,"sanitizeQuotedHeaderParameter");O();O();function In(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(In,"invalidReturnTo");function Tn(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw In("returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw In("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}r(Tn,"parseSafeRelativeReturnTo");O();var $s=["user","shared"],fe=n.enum($s);function kn(e){return{mode:"user",subjectId:e}}r(kn,"buildUserUpstreamConnectionOwner");function vn(){return{mode:"shared"}}r(vn,"buildSharedUpstreamConnectionOwner");var Pn=n.object({ownerMode:fe,initiatedBySubjectId:T,ownerSubjectId:T.optional(),upstreamServerId:q,authProfileId:B,operationId:D,returnTo:n.string().min(1).transform(e=>Tn(e)).optional()});function En(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:n.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:n.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}r(En,"validateUpstreamOwnerState");var Lt=Pn.superRefine(En),Qm=Pn.omit({returnTo:!0}).superRefine(En);function el(e){return Lt.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo})}r(el,"buildUpstreamOwnerState");function tl(e){if(e.ownerMode==="shared")return vn();if(!e.ownerSubjectId)throw new A({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[w]:"oauth_state_invalid"}});return kn(e.ownerSubjectId)}r(tl,"resolveUpstreamConnectionOwnerFromState");var Zs=["active","not_connected","reconsent_required"],Vs=["basic_auth_app_password","bearer_token"],On=n.string().trim().min(1).brand(),ot=n.uuid().brand(),Gt=n.uuid().brand(),Nt=n.enum(Zs),Ws=n.enum(Vs),Un=n.object({encryptedClientInformation:n.string().optional(),encryptedDiscoveryState:n.string().optional(),connectedBySubjectId:T.optional()}),Ks=Un.extend({encryptedStaticSecret:n.string().optional(),staticSecretKind:Ws.optional(),staticSecretLabel:n.string().min(1).optional(),staticSecretUsername:n.string().min(1).optional()}).strict(),Ys=n.object({id:On,subjectId:T.optional(),ownerMode:fe,upstreamServerId:q,authProfileId:B,status:Nt,encryptedAccessToken:n.string().min(1).optional(),encryptedRefreshToken:n.string().min(1).optional(),scopes:n.array(n.string()),expiresAt:m.optional(),metadata:Ks.optional(),createdAt:m,updatedAt:m});function Bt(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:n.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:n.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}r(Bt,"validateUpstreamConnectionOwnerShape");var ge=Ys.superRefine(Bt);function Mn(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}r(Mn,"readUpstreamConnectionLookupKey");var Ft=Lt.extend({id:ot,callbackPath:n.string().min(1),expiresAt:m,codeVerifier:n.string().optional(),redirectUri:n.url(),returnOrigin:n.url().optional()}).extend(Un.shape);function dl(e){let t=e?.status??"not_connected",o={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(o.updatedAt=e.updatedAt),o}r(dl,"readUpstreamConnectionStatus");function pl(){return On.parse(`mcpgw2uc_${crypto.randomUUID()}`)}r(pl,"createUpstreamConnectionId");function ml(){return ot.parse(crypto.randomUUID())}r(ml,"createOAuthStateId");function ll(){return Gt.parse(crypto.randomUUID())}r(ll,"createBrowserConnectTicketId");O();var Zt=n.discriminatedUnion("mode",[n.object({mode:n.literal("user"),subjectId:T}).strict(),n.object({mode:n.literal("shared")}).strict()]),jn=n.object({owner:Zt,upstreamServerId:q,authProfileId:B}).strict(),qn=n.object({items:n.array(jn).min(1).max(100)}).strict(),Vt=n.object({items:n.array(n.object({key:n.object({ownerMode:fe,subjectId:T.optional(),upstreamServerId:q,authProfileId:B}).strict(),connection:ge.strict().optional()}).strict())}).strict(),Dn=ge.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Bt),Ln=ge.strict(),Gn=n.object({owner:Zt,upstreamServerId:q,authProfileId:B}).strict(),Nn=n.object({owner:Zt,upstreamServerId:q,authProfileId:B,connection:ge.strict().optional(),connectionStatus:n.object({connected:n.boolean(),status:Nt,updatedAt:ge.shape.updatedAt.optional()}).strict()}).strict(),Js=n.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),se=n.object({clientId:Z,clientName:n.string().min(1),tokenEndpointAuthMethod:Js}).strict(),Wt=n.discriminatedUnion("method",[n.object({method:n.literal("none"),clientId:Z}).strict(),n.object({method:n.enum(["client_secret_basic","client_secret_post"]),clientId:Z,clientSecretHashInput:n.string().min(1)}).strict(),n.object({method:n.literal("private_key_jwt"),clientId:Z}).strict()]),Kt=n.object({id:Y,currentStateHash:n.string().min(1),clientId:Z,redirectUri:n.string().min(1),resource:n.string().min(1),operationId:D,clientState:n.string().optional(),scope:n.string(),codeChallenge:n.string().min(1),codeChallengeMethod:n.literal("S256"),setupApprovedAt:m.optional(),createdAt:m,expiresAt:m,consumedAt:m.optional()}).strict(),Hn=Kt.omit({id:!0,consumedAt:!0}).extend({transactionId:Y,client:se.optional()}).strict(),Yt=n.object({subjectId:T,roles:n.array(n.string()).optional()}).strict(),Xs=Kt.extend({phase:n.literal("awaiting_login")}).strict(),$t=Kt.extend({phase:n.literal("awaiting_setup"),principal:Yt}).strict(),Qs=n.discriminatedUnion("phase",[Xs,$t]),nt=n.object({transaction:Qs,client:se}).strict(),Bn=Mt.omit({revokedAt:!0}).strict(),Fn=n.discriminatedUnion("kind",[n.object({kind:n.literal("registered"),client:se}).strict(),n.object({kind:n.literal("already_exists")}).strict()]),$n=n.object({clientId:Z}).strict(),Zn=n.discriminatedUnion("kind",[n.object({kind:n.literal("found"),client:Mt.strict()}).strict(),n.object({kind:n.literal("missing")}).strict()]),Vn=n.discriminatedUnion("phase",[Hn.extend({phase:n.literal("awaiting_login")}).strict(),Hn.extend({phase:n.literal("awaiting_setup"),principal:Yt}).strict()]),Wn=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("started")}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("redirect_uri_mismatch")}).strict(),n.object({kind:n.literal("already_exists")}).strict()]),Kn=n.object({transactionId:Y,currentStateHash:n.string().min(1),now:m}).strict(),Yn=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("available")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),Jn=n.object({transactionId:Y,expectedPhase:n.literal("awaiting_login"),currentStateHash:n.string().min(1),nextStateHash:n.string().min(1),nextPhase:n.literal("awaiting_setup"),principal:Yt,now:m}).strict(),Xn=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("advanced")}).strict(),n.object({kind:n.literal("wrong_phase"),current:n.enum(["awaiting_login","awaiting_setup"])}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),Qn=n.object({transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict(),er=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("marked")}).strict(),n.object({kind:n.literal("wrong_phase"),current:n.enum(["awaiting_login","awaiting_setup"])}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),tr=n.discriminatedUnion("decision",[n.object({decision:n.literal("approve"),transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),authorizationCodeHash:n.string().min(1),authorizationCodeExpiresAt:m,grantId:Ee,now:m}).strict(),n.object({decision:n.literal("cancel"),transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict()]),or=n.discriminatedUnion("kind",[n.object({kind:n.literal("approved"),transaction:$t,client:se}).strict(),n.object({kind:n.literal("cancelled"),transaction:$t,client:se}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed_already")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),nr=n.object({clientAuth:Wt,codeHash:n.string().min(1),redirectUri:n.string().min(1),resource:n.string().min(1).optional(),codeChallenge:n.string().min(1),currentRefreshTokenHash:n.string().min(1),accessTokenHash:n.string().min(1),grantExpiresAt:m,accessTokenExpiresAt:m,now:m}).strict(),rr=n.discriminatedUnion("kind",[n.object({kind:n.literal("exchanged"),client:se,grant:Ht.strict()}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("binding_mismatch")}).strict()]),ir=n.object({clientAuth:Wt,currentRefreshTokenHash:n.string().min(1),nextRefreshTokenHash:n.string().min(1),accessTokenHash:n.string().min(1),resource:n.string().min(1).optional(),accessTokenExpiresAt:m,now:m}).strict(),ar=n.discriminatedUnion("kind",[n.object({kind:n.literal("rotated"),client:se,grant:Ht.strict(),accessToken:Qe.strict(),matched:n.literal("current")}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("previous_token_grace")}).strict(),n.object({kind:n.literal("revoked")}).strict()]),sr=n.object({clientAuth:Wt,tokenHash:n.string().min(1),now:m}).strict(),cr=n.discriminatedUnion("kind",[n.object({kind:n.literal("revoked_access_token")}).strict(),n.object({kind:n.literal("revoked_grant")}).strict(),n.object({kind:n.literal("client_mismatch")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("invalid_client")}).strict()]),ur=n.object({tokenHash:n.string().min(1),now:m}).strict(),dr=n.discriminatedUnion("kind",[n.object({kind:n.literal("valid"),record:Qe.strict()}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("revoked")}).strict()]),pr=n.object({accessTokenHash:n.string().min(1),resource:n.string().min(1),operationId:D,upstreamConnectionKeys:n.array(jn).max(100),now:m}).strict(),mr=n.discriminatedUnion("kind",[n.object({kind:n.literal("authorized"),principal:n.object({subjectId:T,roles:n.array(n.string())}).strict(),accessToken:Qe.strict(),upstreamConnections:Vt.shape.items.optional().default([])}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("revoked")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict()]),lr=n.object({record:Ft}).strict(),hr=n.object({kind:n.literal("saved")}).strict(),fr=n.object({id:ot,now:m}).strict(),gr=n.discriminatedUnion("kind",[n.object({kind:n.literal("available"),record:Ft}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("missing")}).strict()]),Sr=n.object({id:Gt,expiresAt:m,now:m}).strict(),Rr=n.discriminatedUnion("kind",[n.object({kind:n.literal("available")}).strict(),n.object({kind:n.literal("consumed")}).strict()]);var yr=100,ec=new Set(["undefined","null","nan"]);function br(e){return e!==null&&typeof e=="object"}r(br,"isProblemDetailsShape");var Cr="bckt_";function k(e){let t=Ue.instance.runtime.ZUPLO_SERVICE_BUCKET_ID;if(!t)throw ce("internal_server_error","MCP Gateway runtime storage requires ZUPLO_SERVICE_BUCKET_ID.");if(!t.startsWith(Cr))throw ce("internal_server_error",`MCP Gateway runtime storage bucket ID must start with "${Cr}".`);return`/zups/v2/buckets/${encodeURIComponent(t)}/mcp/storage/${e}`}r(k,"buildStoragePath");function tc(){return k("upstream-connections/batch-get")}r(tc,"buildBatchGetUpstreamConnectionsPath");function oc(){return k("upstream-connections/upsert")}r(oc,"buildUpsertUpstreamConnectionPath");function nc(){return k("authorization/read-setup")}r(nc,"buildReadAuthorizationSetupPath");function rc(){return k("oauth/register-client")}r(rc,"buildRegisterClientPath");function ic(){return k("oauth/read-client")}r(ic,"buildReadClientPath");function ac(){return k("authorization/start")}r(ac,"buildStartAuthorizationPath");function sc(){return k("authorization/read-pending")}r(sc,"buildReadPendingAuthorizationPath");function cc(){return k("authorization/advance-pending")}r(cc,"buildAdvancePendingAuthorizationPath");function uc(){return k("authorization/mark-setup-approved")}r(uc,"buildMarkAuthorizationSetupApprovedPath");function dc(){return k("authorization/decide-setup")}r(dc,"buildDecideAuthorizationSetupPath");function pc(){return k("token/exchange-authorization-code")}r(pc,"buildExchangeAuthorizationCodePath");function mc(){return k("token/refresh")}r(mc,"buildRefreshTokenPath");function lc(){return k("token/revoke")}r(lc,"buildRevokeOAuthTokenPath");function hc(){return k("token/validate-access-token")}r(hc,"buildValidateAccessTokenPath");function fc(){return k("mcp/authorize-and-load-connections")}r(fc,"buildAuthorizeAndLoadConnectionsPath");function gc(){return k("upstream-oauth-state/save")}r(gc,"buildSaveUpstreamOAuthStatePath");function Sc(){return k("upstream-oauth-state/consume")}r(Sc,"buildConsumeUpstreamOAuthStatePath");function Rc(){return k("browser-connect-ticket/consume")}r(Rc,"buildConsumeBrowserConnectTicketPath");function yc(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}r(yc,"responseKeyMatchesLookup");function bc(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}r(bc,"authorizationSetupMatchesLookup");function _r(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}r(_r,"connectionMatchesLookup");function Cc(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&Qt(e.scopes,t.scopes)&&Xt(e.expiresAt,t.expiresAt)&&wc(e.metadata,t.metadata)}r(Cc,"connectionMatchesUpsertRecord");function Xt(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}r(Xt,"optionalTimestampInstantsMatch");function wr(e,t){return Date.parse(e)<=Date.parse(t)}r(wr,"timestampInstantIsAtOrBefore");function Qt(e,t){return e.length===t.length&&e.every((o,i)=>o===t[i])}r(Qt,"stringArraysMatch");function wc(e,t){let o=Ar(e),i=Ar(t),s=Object.fromEntries(i);return o.length===i.length&&o.every(([d,c])=>s[d]===c)}r(wc,"metadataMatches");function Ar(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}r(Ar,"definedMetadataEntries");function b(e,t){throw ce("internal_server_error",e,t)}r(b,"throwInvalidStorageResponse");function ce(e,t,o){let i=Ne[e],s=i.status<500,d=s?o:new Error(t,o===void 0?void 0:{cause:o});return new A({message:s?t:i.publicDetail,extensionMembers:{[w]:e}},d===void 0?void 0:{cause:d})}r(ce,"storageRuntimeError");async function Ac(e,t){try{let o=await e.json();return o&&typeof o=="object"&&!Array.isArray(o)&&delete o.$schema,t.parse(o)}catch(o){b("Gateway Service storage response did not match the runtime storage contract.",o)}}r(Ac,"parseRuntimeHttpStorageResponse");function xr(e,t){e.length!==t.length&&b("Gateway Service storage response item count did not match the request.");for(let[o,i]of e.entries()){let s=t[o];yc(i.key,s)||b("Gateway Service storage response key did not match the request."),i.connection!==void 0&&!_r(i.connection,s)&&b("Gateway Service storage response connection did not match the response key.")}}r(xr,"validateUpstreamConnectionItemsMatchLookups");function _c(e,t){bc(e,t)||b("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!_r(e.connection,t)&&b("Gateway Service storage response authorization setup connection did not match the request.");let o=e.connection?.status==="active",i=e.connection?.status??"not_connected",s=e.connection?.updatedAt;(e.connectionStatus.connected!==o||e.connectionStatus.status!==i||!Xt(e.connectionStatus.updatedAt,s))&&b("Gateway Service storage response authorization setup status did not match the connection.")}r(_c,"validateAuthorizationSetupResponseMatchesLookup");function xc(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&b("Gateway Service storage response registered client did not match the request.")}r(xc,"validateRegisterClientResponseMatchesRequest");function zc(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&b("Gateway Service storage response client did not match the request.")}r(zc,"validateReadClientResponseMatchesRequest");function Ic(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.operationId!==t.operationId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&b("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&b("Gateway Service storage response started authorization principal did not match the request."))}r(Ic,"validateStartAuthorizationResponseMatchesRequest");function Jt(e,t){e.kind!=="available"&&e.kind!=="advanced"&&e.kind!=="marked"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&b("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&b("Gateway Service storage response advanced authorization did not match the request."),"currentPrincipal"in t&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&b("Gateway Service storage response marked authorization principal did not match the request."),e.kind==="marked"&&"currentPrincipal"in t&&e.transaction.setupApprovedAt!==t.now&&b("Gateway Service storage response marked authorization setup approval timestamp did not match the request."))}r(Jt,"validatePendingAuthorizationResponseMatchesRequest");function Tc(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&b("Gateway Service storage response authorization setup transaction did not match the request.")}r(Tc,"validateAuthorizationSetupDecisionResponseMatchesRequest");function kc(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!Xt(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&b("Gateway Service storage response authorization-code exchange did not match the request.")}r(kc,"validateExchangeAuthorizationCodeResponseMatchesRequest");function vc(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&b("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!wr(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!wr(e.accessToken.expiresAt,e.grant.expiresAt)||!Oc(e.accessToken,e.grant))&&b("Gateway Service storage response token refresh access token did not match the request."))}r(vc,"validateRefreshTokenResponseMatchesRequest");function Pc(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&b("Gateway Service storage response access token did not match the request.")}r(Pc,"validateAccessTokenValidationResponseMatchesRequest");function Ec(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.operationId!==t.operationId||e.principal.subjectId!==e.accessToken.subjectId||!Qt(e.principal.roles,e.accessToken.roles))&&b("Gateway Service storage response MCP authorization did not match the request."),xr(e.upstreamConnections,t.upstreamConnectionKeys))}r(Ec,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Oc(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.operationId===t.operationId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Qt(e.roles,t.roles)}r(Oc,"accessTokenMatchesGrant");async function Uc(e){try{return await e.clone().json()}catch{return}}r(Uc,"readProblemDetails");async function Mc(e){let t=await Uc(e),o=br(t)&&typeof t.status=="number"?t.status:e.status,i=br(t)&&oe(t.code)?t.code:vo(o);throw ce(i,`Gateway Service storage request failed with HTTP ${o}.`)}r(Mc,"throwRuntimeHttpStorageError");var rt=class{static{r(this,"RuntimeHttpStorageClient")}#t;#o;constructor(t){this.#t=t.baseUrl??Ue.instance.zuploEdgeApiUrl,this.#o=t.fetch??fetch}#n(t){let o;try{o=new URL(t,this.#t)}catch(i){throw ce("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,i)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw ce("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${o.protocol}" from ${JSON.stringify(this.#t)}.`);if(!o.hostname||ec.has(o.hostname))throw ce("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${o.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return o}async#e(t){let o=t.requestSchema.parse(t.input),i=this.#n(t.path),s=new Headers({"Content-Type":"application/json"});po(s);let d=await this.#o(i,{method:"POST",headers:s,body:JSON.stringify(o)});return d.ok||await Mc(d),{request:o,response:await Ac(d,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let o=[],i=new Map,s=t.map(c=>{let l=Mn(c),y=i.get(l);if(y!==void 0)return y;let x=o.length;return o.push(c),i.set(l,x),x}),d=[];for(let c=0;c<o.length;c+=yr){let l=o.slice(c,c+yr);d.push(...await this.#r(l))}return s.map(c=>d[c])}async upsertUpstreamConnection(t){let{request:o,response:i}=await this.#e({input:t,path:oc(),requestSchema:Dn,responseSchema:Ln});return Cc(i,o)||b("Gateway Service storage response connection did not match the request."),i}async readAuthorizationSetup(t){let{request:o,response:i}=await this.#e({input:t,path:nc(),requestSchema:Gn,responseSchema:Nn});return _c(i,o),i}async registerClient(t){let{request:o,response:i}=await this.#e({input:t,path:rc(),requestSchema:Bn,responseSchema:Fn});return xc(i,o),i}async readClient(t){let{request:o,response:i}=await this.#e({input:t,path:ic(),requestSchema:$n,responseSchema:Zn});return zc(i,o),i}async startAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:ac(),requestSchema:Vn,responseSchema:Wn});return Ic(i,o),i}async readPendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:sc(),requestSchema:Kn,responseSchema:Yn});return Jt(i,o),i}async advancePendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:cc(),requestSchema:Jn,responseSchema:Xn});return Jt(i,o),i}async markAuthorizationSetupApproved(t){let{request:o,response:i}=await this.#e({input:t,path:uc(),requestSchema:Qn,responseSchema:er});return Jt(i,o),i}async decideAuthorizationSetup(t){let{request:o,response:i}=await this.#e({input:t,path:dc(),requestSchema:tr,responseSchema:or});return Tc(i,o),i}async saveUpstreamOAuthState(t){let{response:o}=await this.#e({input:t,path:gc(),requestSchema:lr,responseSchema:hr});return o}async consumeUpstreamOAuthState(t){let{request:o,response:i}=await this.#e({input:t,path:Sc(),requestSchema:fr,responseSchema:gr});return i.kind==="available"&&i.record.id!==o.id&&b("Gateway Service storage response upstream OAuth state did not match the request."),i}async consumeBrowserConnectTicket(t){let{response:o}=await this.#e({input:t,path:Rc(),requestSchema:Sr,responseSchema:Rr});return o}async exchangeAuthorizationCode(t){let{request:o,response:i}=await this.#e({input:t,path:pc(),requestSchema:nr,responseSchema:rr});return kc(i,o),i}async refreshToken(t){let{request:o,response:i}=await this.#e({input:t,path:mc(),requestSchema:ir,responseSchema:ar});return vc(i,o),i}async revokeOAuthToken(t){let{response:o}=await this.#e({input:t,path:lc(),requestSchema:sr,responseSchema:cr});return o}async validateAccessToken(t){let{request:o,response:i}=await this.#e({input:t,path:hc(),requestSchema:ur,responseSchema:dr});return Pc(i,o),i}async authorizeAndLoadConnections(t){let{request:o,response:i}=await this.#e({input:t,path:fc(),requestSchema:pr,responseSchema:mr});return Ec(i,o),i}async#r(t){let o={items:[...t]},{response:i}=await this.#e({input:o,path:tc(),requestSchema:qn,responseSchema:Vt});return xr(i.items,t),i.items.map(s=>s.connection)}};var Hc="__zuploMcpGatewayStorageBackend",eo;function jc(){return new rt({})}r(jc,"buildProductionStorageBackend");function zr(){let e=globalThis[Hc];return e||(eo||(eo=jc()),eo)}r(zr,"getStorage");function qc(e,t){let o=qe(e),i=t.ownerMode??t.routeBinding?.ownerMode,s=t.upstreamAuthMode??t.routeBinding?.authMode,d=t.virtualServerName??t.routeBinding?.operationId??o?.operationId,c=t.upstreamServerName??t.routeBinding?.upstreamServerId??o?.upstreamServerId,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName,y=t.authProfileId??t.routeBinding?.authProfileId??o?.authProfileId;return go(e,{...t,subjectId:t.subjectId??t.routeBinding?.initiatedBySubjectId,ownerMode:i,upstreamAuthMode:s,virtualServerName:d,upstreamServerName:c,upstreamServerTitle:l,authProfileId:y})}r(qc,"buildMcpAnalyticsMetadata");function N(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,qc(e,t),t.unit)}catch(o){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:o instanceof Error?o.name:"unknown"})}}r(N,"emitMcpAnalyticsEvent");import{base64url as to}from"jose";var Dc="sha256:",Lc=32;function Ir(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}r(Ir,"copyToArrayBuffer");function Ql(){let e=crypto.getRandomValues(new Uint8Array(Lc));return to.encode(e)}r(Ql,"createOpaqueToken");async function Tr(e){let t=await crypto.subtle.digest("SHA-256",Ir(new TextEncoder().encode(e)));return`${Dc}${to.encode(new Uint8Array(t))}`}r(Tr,"hashOpaqueValue");async function eh(e){let t=await crypto.subtle.digest("SHA-256",Ir(new TextEncoder().encode(e)));return to.encode(new Uint8Array(t))}r(eh,"calculatePkceS256Challenge");function Gc(e){let t=e.headers.get("authorization"),[o,i]=t?.split(/\s+/,2)??[];if(!(o?.toLowerCase()!=="bearer"||!i))return i}r(Gc,"readBearerToken");function Nc(e,t,o){return he(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":o}})}r(Nc,"gatewayAuthenticationRequiredResponse");function Bc(e){switch(e){case"expired":return"expired_token";case"revoked":return"revoked_token";case"missing":return"invalid_token";default:{let t=e;return"invalid_token"}}}r(Bc,"tokenValidationReasonCode");async function Fc(e,t,o){let i=await zr().validateAccessToken({tokenHash:await Tr(e),now:ln(new Date)});if(i.kind!=="valid"){t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:i.kind,operationId:o},"Gateway access token validation failed");let s=Bc(i.kind);throw N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:o,reasonClass:"auth",reasonCode:s,attributes:{validationKind:i.kind}}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o,httpStatusCode:401,reasonClass:"auth",reasonCode:s}),ae("authentication_required","Gateway access token is expired, revoked, or invalid.")}return i.record}r(Fc,"validateGatewayAccessToken");function $c(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.operationId!==e.operationId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedOperationId:e.operationId,tokenOperationId:e.accessToken.operationId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.operationId,reasonClass:"auth",reasonCode:"invalid_audience"}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),ae("authentication_required","Gateway access token was not issued for this MCP resource.")}r($c,"assertAccessTokenResource");function Zc(e,t,o){return he(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":tt({operationId:o,requestUrl:e.url,requestHeaders:e.headers,error:"insufficient_scope",errorDescription:`The access token is missing the ${V} scope required by this MCP resource.`,scope:V})}})}r(Zc,"insufficientScopeResponse");function Vc(e){return{zuploSubjectId:e.subjectId,roles:e.roles,clientId:e.clientId,scope:e.scope,resource:e.resource,operationId:e.operationId,grantId:e.grantId,createdAt:e.createdAt,expiresAt:e.expiresAt}}r(Vc,"userDataFromAccessToken");function Wc(e){let t=new Headers(e.headers);return t.delete("authorization"),new mo(e,{headers:t,...e.user===void 0?{}:{user:e.user}})}r(Wc,"stripDownstreamAuthorizationHeader");function Kc(e){let t=Ye(e.error),o={event:"gateway_access_token_rejected",code:t??"authentication_required",operationId:e.operationId};return e.error instanceof Error?(o.errorName=e.error.name,o.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(o.errorMessage=String(e.error)),e.context.log.warn(o,"Gateway access token rejected; MCP request denied"),he(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":tt({operationId:e.operationId,requestUrl:e.request.url,requestHeaders:e.request.headers,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}r(Kc,"gatewayTokenRejectedResponse");async function oo(e,t,o){let i=qt(o.operationId,e.url,e.headers),s=Gc(e),d=tt({operationId:o.operationId,requestUrl:e.url,requestHeaders:e.headers,scope:V});if(!s)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",operationId:o.operationId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),Nc(e,t,d);try{let c=await Fc(s,t,o.operationId);return $c({accessToken:c,resource:i,operationId:o.operationId},t),c.scope!==V?(t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:c.scope,requiredScope:V,operationId:o.operationId,clientId:c.clientId},"Gateway access token does not have the required MCP scope"),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:o.operationId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:c.scope,requiredScope:V,clientId:c.clientId}}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o.operationId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),Zc(e,t,o.operationId)):(e.user={sub:c.subjectId,data:Vc(c)},Et(t,{subjectId:c.subjectId}),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:o.operationId,subjectId:c.subjectId,attributes:{clientId:c.clientId}}),Wc(e))}catch(c){return Kc({request:e,context:t,error:c,operationId:o.operationId})}}r(oo,"gatewayTokenInbound");var Se={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},Yc="oauth-protected-resource-metadata",Jc="/.well-known/oauth-protected-resource/";function Xc(e){let o=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof o=="string"?o:void 0}r(Xc,"readRouteOperationId");function Qc(e){return e.hasGatewayRouteContext?Se.VIRTUAL_MCP_SERVER:e.routeOperationId===Yc||e.routeOperationId===void 0&&e.routePath.startsWith(Jc)?Se.OAUTH_PROTECTED_RESOURCE_METADATA:Se.OTHER}r(Qc,"classifyAnalyticsRouteSurface");function eu(e){let t=e.route.path;return{routePath:t,routeSurface:Qc({routePath:t,routeOperationId:Xc(e),hasGatewayRouteContext:qe(e)!==void 0})}}r(eu,"readAnalyticsRequestContext");function tu(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Se.VIRTUAL_MCP_SERVER}r(tu,"isIntentionalMethodRejection");function ou(e){return tu(e)||e.response.status===401&&e.routeSurface===Se.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}r(ou,"classifyRequestCompletedOutcome");function kr(e){return zn(e.user,e.url,e.headers)?.subjectId}r(kr,"readRequestSubjectId");async function no(e,t){let o=Date.now(),i=eu(t);return N(t,{eventType:U.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:i.routeSurface,httpMethod:e.method,subjectId:kr(e)}),dt.getContextExtensions(t).addHandlerResponseHook((s,d)=>{let c=ou({response:s,routeSurface:i.routeSurface});N(t,{eventType:U.MCP_REQUEST_COMPLETED,outcome:c,routeSurface:i.routeSurface,httpStatusCode:s.status,httpMethod:e.method,latencyMs:Date.now()-o,subjectId:kr(d)})}),e}r(no,"analyticsContextInbound");function nu(e){return e instanceof Response}r(nu,"isResponse");async function xe(e,t){let o=We(t.route.path),i={operationId:o.operationId};Ro(t,i),gn(t,i);let s=await no(e,t);return nu(s)?s:oo(s,t,{operationId:o.operationId})}r(xe,"mcpOAuthInboundPolicy");var vr=class extends He{static{r(this,"McpOAuthInboundPolicy")}constructor(t,o){let i=ft(t,o);super(i,o)}async handler(t,o){return Me("policy.inbound.mcp-oauth"),De(o,this.options),xe(t,o)}};function ft(e,t="mcp-oauth-inbound"){return Ge(ht,e,`MCP OAuth policy "${t}"`)}r(ft,"mcpOAuthOptionsToRuntimeConfig");function W(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(W,"invalidOutboundUrl");function ru(){let e=ue.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}r(ru,"isTestOnlyAllowHttpLoopbackIdpEnabled");function iu(){let e=ue.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}r(iu,"isTestOnlyAllowHttpLoopbackCimdEnabled");var au=new Set(["undefined","null","nan"]);function io(e,t){if(!e.hostname)throw W(`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(au.has(e.hostname.toLowerCase()))throw W(`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}r(io,"assertSafeOutboundHostname");var su=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),cu=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function Pr(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(o=>Number(o));if(!(t.length!==4||t.some(o=>Number.isNaN(o)||o<0||o>255)))return t}r(Pr,"parseIpv4Octets");function uu([e,t],o){let i=o.firstMax??o.first;return e<o.first||e>i?!1:o.secondMin===void 0||o.secondMax===void 0?!0:t>=o.secondMin&&t<=o.secondMax}r(uu,"ipv4RangeMatches");function Er(e){let t=Pr(e);return t!==void 0&&cu.some(o=>uu(t,o))}r(Er,"isPrivateIpv4");function ro(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}r(ro,"parseIpv6Word");function du(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}r(du,"formatIpv4FromWords");function pu(e){let t=e.slice(7),o=Pr(t);if(o!==void 0)return o.join(".");let[i,s,d]=t.split(":"),c=ro(i),l=ro(s);return d===void 0&&c!==void 0&&l!==void 0?du(c,l):void 0}r(pu,"parseIpv6MappedIpv4");function mu(e){return ro(e.split(":").find(Boolean))}r(mu,"readFirstIpv6Hextet");function lu(e){let t=te(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let i=pu(t);return i===void 0||Er(i)}let o=mu(t);return o===void 0?!1:(o&65024)===64512||(o&65472)===65152}r(lu,"isPrivateIpv6");function ao(e){let t=te(e);return su.has(t)||t.endsWith(".internal")||Er(t)||lu(t)}r(ao,"isBlockedOutboundHostname");function Or(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw W(`Unsupported outbound protocol: ${t.protocol}`);io(t,e);let o=j(t);if(t.protocol==="http:"&&!o)throw W("Configured outbound HTTP URLs must target loopback hosts.");let i=te(t.hostname);if(!o&&ao(i))throw W(`Blocked outbound host: ${i}`);return t}r(Or,"validateConfiguredOutboundUrl");function Ur(e){let t=new URL(e),o=j(t),i=o&&ru();if(t.protocol!=="https:"&&!i)throw W("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw W("Identity provider URLs must not include credentials, query params, or fragments.");io(t,e);let s=te(t.hostname);if(!o&&ao(s))throw W(`Blocked identity provider host: ${s}`);return t}r(Ur,"validateIdentityProviderUrl");function Mr(e,t){let o=new URL(e),i=o.protocol==="http:"&&j(o)&&iu();if(o.protocol!=="https:"&&!i||o.pathname==="/"||o.username||o.password||o.search||o.hash)throw W(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(io(o,e),!i&&ao(o.hostname))throw W(`CIMD ${t} points at a blocked host.`);return o}r(Mr,"validateCimdUrl");function Hr(e){return Mr(e,"client_id")}r(Hr,"validateCimdClientMetadataUrl");function jr(e){return Mr(e,"jwks_uri")}r(jr,"validateCimdClientJwksUrl");function qr(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let o=r(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",o,{once:!0}),()=>t.removeEventListener("abort",o)}r(qr,"mergeAbortSignals");async function hu(e){try{await e.cancel()}catch{}}r(hu,"cancelReader");async function Dr(e,t){if(!e)return new Uint8Array;let o=e.getReader(),i=[],s=0,d=await o.read();for(;!d.done;){let y=d.value;if(s+=y.byteLength,s>t.maxBytes)throw await hu(o),t.createLimitError();i.push(y),d=await o.read()}let c=new Uint8Array(s),l=0;for(let y of i)c.set(y,l),l+=y.byteLength;return c}r(Dr,"readBoundedByteStream");var fu=2,gu=1024*1024,Su=1e4,Ru=new Set([301,302,303,307,308]),yu=["authorization","proxy-authorization","cookie","cookie2"];function so(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}r(so,"readRequestUrl");function Re(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}r(Re,"readRequestMethod");function bu(e,t,o){let i=e.headers.get("content-length");if(!i)return;let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s>t)throw new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[w]:o}})}r(bu,"assertContentLengthWithinLimit");async function Cu(e,t,o){return bu(e,t,o),Dr(e.body,{maxBytes:t,createLimitError:r(()=>new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[w]:o}}),"createLimitError")})}r(Cu,"readBoundedResponseBody");function wu(e,t){let o=new ArrayBuffer(t.byteLength);return new Uint8Array(o).set(t),new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}r(wu,"responseFromBufferedBody");function Au(e,t){if(!Ru.has(e.status))return;let o=e.headers.get("location");if(o)return new URL(o,t).toString()}r(Au,"resolveRedirectUrl");function Lr(e,t){try{return t.validateUrl(e)}catch(o){throw new A({message:"Outbound URL was not allowed.",extensionMembers:{[w]:t.problemCode}},{cause:o})}}r(Lr,"validateOutboundUrl");function _u(e,t){throw e instanceof A&&oe(e.extensionMembers?.[w])?e:new A({message:"Outbound fetch failed.",extensionMembers:{[w]:t}},{cause:e})}r(_u,"normalizeFetchError");function Oe(e,t){if(e===void 0)return;let o={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(o.host=t.host),t.extra!==void 0)for(let[i,s]of Object.entries(t.extra))s!==void 0&&(o[i]=s);t.error!==void 0&&Pt(o,"error",t.error),e.log.warn(o,"Outbound HTTP exchange rejected")}r(Oe,"logOutboundFailure");async function xu(e,t,o,i,s,d,c){let l=Re(o,i);try{return await t(o,i)}catch(y){let x=y instanceof DOMException&&y.name==="AbortError";Oe(e,{event:x?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:l,host:X(d),error:y,extra:{abortReason:c()}}),_u(y,s)}}r(xu,"fetchWithNormalizedError");function zu(e){if(e.redirects>=e.maxRedirects)throw new A({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[w]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new A({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[w]:e.problemCode}})}r(zu,"assertRedirectAllowed");function Iu(e,t){let o=new Headers(e);for(let i of yu)o.delete(i);for(let i of t)o.delete(i);return o}r(Iu,"stripCrossOriginHeaders");function Tu(e,t,o,i,s){let d={...e,method:t,redirect:"manual",signal:o};return i&&(d.headers=Iu(e.headers,s)),d}r(Tu,"buildRedirectInit");function ku(e,t,o){let i={...t,redirect:"manual",signal:o};return i.headers===void 0&&e instanceof Request&&(i.headers=e.headers),i}r(ku,"buildInitialRequestInit");function vu(e){let t=Re(e.currentInput,e.currentInit);zu({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let o=Lr(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),i=new URL(e.currentUrl),s=o.origin!==i.origin,d=o.toString();return{currentInput:d,currentUrl:d,currentInit:Tu(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}r(vu,"followRedirect");async function co(e,t,o){let i=o.problemCode??"invalid_request",s=o.maxRedirects??fu,d=o.maxResponseBytes??gu,c=o.timeoutMs??Su,l=o.fetchImpl??fetch,y=o.additionalCrossOriginStrippedHeaders??[],x=o.context,F=new AbortController,ye=qr(F,t.signal),K=!1,uo=setTimeout(()=>{K=!0,F.abort()},c),be=e,Ce=ku(e,t,F.signal),Q;try{Q=Lr(so(e),{problemCode:i,validateUrl:o.validateUrl}).toString()}catch(ee){throw Oe(x,{event:"outbound_url_blocked",problemCode:i,method:Re(e,t),host:X(so(e)),error:ee}),clearTimeout(uo),ye?.(),ee}let at=0;try{for(;;){let ee=await xu(x,l,be,Ce,i,Q,()=>K?`timeout_after_${c}ms`:void 0),st=Au(ee,Q);if(st!==void 0)try{let $=vu({currentInput:be,currentInit:Ce,currentUrl:Q,redirectUrl:st,redirects:at,maxRedirects:s,problemCode:i,validateUrl:o.validateUrl,signal:F.signal,additionalCrossOriginStrippedHeaders:y});be=$.currentInput,Ce=$.currentInit,Q=$.currentUrl,at=$.redirects;continue}catch($){throw Oe(x,{event:"outbound_redirect_blocked",problemCode:i,method:Re(be,Ce),host:X(Q),error:$,extra:{redirects:at,maxRedirects:s,redirectTargetHost:X(st)}}),$}try{return wu(ee,await Cu(ee,d,i))}catch($){throw Oe(x,{event:"outbound_response_size_exceeded",problemCode:i,method:Re(be,Ce),host:X(Q),error:$,extra:{maxResponseBytes:d,status:ee.status}}),$}}}finally{clearTimeout(uo),ye?.()}}r(co,"runSafeOutboundExchange");async function it(e,t,o){let i=await co(e,t,o);try{return{response:i,json:await i.clone().json()}}catch(s){throw Oe(o.context,{event:"outbound_json_parse_failed",problemCode:o.problemCode??"invalid_request",method:Re(e,t),host:X(so(e)),error:s,extra:{status:i.status,contentType:i.headers.get("content-type")??void 0}}),new A({message:"Outbound JSON response could not be parsed.",extensionMembers:{[w]:o.problemCode??"invalid_request"}},{cause:s})}}r(it,"runSafeOutboundJsonExchange");function tf(e,t={},o={}){return co(e,t,{...o,validateUrl:Or})}r(tf,"fetchConfiguredOutbound");function of(e,t={},o={}){return it(e,t,{...o,validateUrl:Ur})}r(of,"fetchIdentityProviderJson");function nf(e,t={},o={}){return it(e,t,{...o,validateUrl:Hr})}r(nf,"fetchCimdClientMetadataJson");function rf(e,t={},o={}){return it(e,t,{...o,validateUrl:jr})}r(rf,"fetchCimdClientJwksJson");function df(e){let t=Le().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw ae("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}r(df,"requireBrowserLoginField");export{te as a,j as b,De as c,Le as d,Ge as e,vr as f,Qr as g,ti as h,Sd as i,w as j,Cd as k,wd as l,Ad as m,_d as n,oe as o,xd as p,ne as q,gt as r,vd as s,q as t,D as u,B as v,Oo as w,$e as x,ui as y,Be as z,jo as A,Ma as B,bt as C,cn as D,un as E,op as F,pn as G,hs as H,pp as I,mp as J,mn as K,We as L,lp as M,ln as N,Sp as O,J as P,Pe as Q,Pt as R,X as S,Et as T,Op as U,Ye as V,ae as W,he as X,jp as Y,Gp as Z,Np as _,Z as $,Y as aa,ks as ba,vs as ca,Yp as da,Jp as ea,Xp as fa,Qp as ga,V as ha,mm as ia,lm as ja,Os as ka,hm as la,An as ma,xm as na,qt as oa,Ms as pa,T as qa,Fs as ra,zn as sa,Tn as ta,kn as ua,vn as va,Lt as wa,Qm as xa,el as ya,tl as za,ot as Aa,Gt as Ba,dl as Ca,pl as Da,ml as Ea,ll as Fa,zr as Ga,N as Ha,Ql as Ia,Tr as Ja,eh as Ka,_o as La,Or as Ma,Hr as Na,jr as Oa,Dr as Pa,tf as Qa,of as Ra,nf as Sa,rf as Ta,df as Ua};
30
- //# sourceMappingURL=chunk-WU5PDK6Z.js.map