@frontmcp/sdk 1.13.0-rc.1 → 1.13.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/index.cjs +5 -0
- package/browser/transport/adapters/transport.streamable-http.adapter.mjs +5 -0
- package/esm/index.mjs +1 -1
- package/index.js +1 -1
- package/package.json +10 -10
- package/transport/adapters/transport.streamable-http.adapter.d.ts +2 -0
- package/transport/adapters/transport.streamable-http.adapter.d.ts.map +1 -1
package/browser/index.cjs
CHANGED
|
@@ -63069,6 +63069,11 @@ var init_transport_streamable_http_adapter = __esm({
|
|
|
63069
63069
|
return this.transport.handleRequest(req, res, req.body);
|
|
63070
63070
|
}
|
|
63071
63071
|
}
|
|
63072
|
+
/** A destroy without a reason is the client's DELETE: closing the transport aborts the session's in-flight calls. */
|
|
63073
|
+
async destroy(reason) {
|
|
63074
|
+
if (reason === void 0) await this.transport.close().catch(() => void 0);
|
|
63075
|
+
return super.destroy(reason);
|
|
63076
|
+
}
|
|
63072
63077
|
/**
|
|
63073
63078
|
* Send an elicitation request to the client.
|
|
63074
63079
|
*
|
|
@@ -95,6 +95,11 @@ var TransportStreamableHttpAdapter = class extends LocalTransportAdapter {
|
|
|
95
95
|
return this.transport.handleRequest(req, res, req.body);
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
+
/** A destroy without a reason is the client's DELETE: closing the transport aborts the session's in-flight calls. */
|
|
99
|
+
async destroy(reason) {
|
|
100
|
+
if (reason === void 0) await this.transport.close().catch(() => void 0);
|
|
101
|
+
return super.destroy(reason);
|
|
102
|
+
}
|
|
98
103
|
/**
|
|
99
104
|
* Send an elicitation request to the client.
|
|
100
105
|
*
|
package/esm/index.mjs
CHANGED
|
@@ -291,7 +291,7 @@ data: ${relativeUrlWithSession}
|
|
|
291
291
|
event: message
|
|
292
292
|
data: ${JSON.stringify(message)}
|
|
293
293
|
|
|
294
|
-
`)}get sessionId(){return this._sessionId}get lastEventId(){return this._eventIdCounter}setEventIdCounter(eventId){this._eventIdCounter=eventId}}}});var init_node_sse_transport=__esm({"libs/sdk/src/transport/adapters/polyfills/node-sse-transport.ts"(){"use strict";init_base_sse_transport()}});var sse_transport_exports={};__export(sse_transport_exports,{RecreateableSSEServerTransport:()=>RecreateableSSEServerTransport});var RecreateableSSEServerTransport;var init_sse_transport=__esm({"libs/sdk/src/transport/adapters/sse-transport.ts"(){"use strict";init_node_sse_transport();RecreateableSSEServerTransport=class extends SSEServerTransport{_isRecreatedSession=false;constructor(endpoint,res,options){super(endpoint,res,options);if(options?.initialEventId!==void 0&&this.isValidEventId(options.initialEventId)){this.setEventIdCounter(options.initialEventId);this._isRecreatedSession=true}}isValidEventId(eventId){return Number.isInteger(eventId)&&eventId>=0&&eventId<=Number.MAX_SAFE_INTEGER}get isRecreatedSession(){return this._isRecreatedSession}get eventIdCounter(){return this.lastEventId}setEventIdCounter(eventId){if(!this.isValidEventId(eventId)){console.warn(`[RecreateableSSEServerTransport] Invalid eventId: ${eventId}. Must be a non-negative integer. Ignoring.`);return}super.setEventIdCounter(eventId)}setSessionState(sessionId,lastEventId){if(this.sessionId!==sessionId){const redact=id=>`${id.slice(0,8)}\u2026`;console.warn(`RecreateableSSEServerTransport: session ID mismatch. Expected ${redact(this.sessionId)}, got ${redact(sessionId)}. Using constructor value.`)}if(lastEventId!==void 0){this.setEventIdCounter(lastEventId)}this._isRecreatedSession=true}}}});import{toJSONSchema as toJSONSchema6}from"@frontmcp/lazy-zod";async function loadSseTransport(){RecreateableTransport??=(await Promise.resolve().then(()=>(init_sse_transport(),sse_transport_exports))).RecreateableSSEServerTransport}function sseTransportClass(){if(!RecreateableTransport){throw new InternalMcpError("The SSE transport was used before loadSseTransport() loaded it")}return RecreateableTransport}var RecreateableTransport,TransportSSEAdapter;var init_transport_sse_adapter=__esm({"libs/sdk/src/transport/adapters/transport.sse.adapter.ts"(){"use strict";init_elicitation_types();init_errors();init_transport_error();init_transport_local_adapter();TransportSSEAdapter=class extends LocalTransportAdapter{sessionId;configureTransportHandlers(transport){transport.onerror=error=>{console.error("SSE error:",error instanceof Error?error.message:"Unknown error")};transport.onclose=this.destroy.bind(this)}createTransport(sessionId,res){this.sessionId=sessionId;this.logger.info(`new transport session: ${sessionId.slice(0,40)}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId});this.configureTransportHandlers(transport);return transport}createTransportFromSession(sessionId,res,lastEventId){this.sessionId=sessionId;this.logger.info(`recreating transport session: ${sessionId.slice(0,40)}, lastEventId: ${lastEventId??"none"}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId,initialEventId:lastEventId});this.configureTransportHandlers(transport);return transport}initialize(req,res){this.logger.verbose(`[${this.sessionId}] handle initialize request`);this.ensureAuthInfo(req,this);return Promise.resolve()}async handleRequest(req,res){await this.ready;const authInfo=this.ensureAuthInfo(req,this);if(this.handleIfElicitResult(req)){this.logger.verbose(`[${this.sessionId}] handled elicitation result`);res.writeHead(202,{"Content-Type":"application/json"});res.end(JSON.stringify({jsonrpc:"2.0",id:null,result:{}}));return}if(req.method==="GET"){this.logger.verbose(`[${this.sessionId}] handle get request`);return this.transport.handleMessage(req.body,{requestInfo:{headers:req.headers},authInfo})}else{this.logger.verbose(`[${this.sessionId}] handle post request`);return this.transport.handlePostMessage(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=options??{};if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}await this.cancelPendingElicit();const elicitId=elicitationId||`elicit-${this.newRequestId}`;const sessionId=this.key.sessionId;const expiresAt=Date.now()+ttl;const store=this.requireElicitStore();await store.setPending({elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode});const params={mode,message,requestedSchema:toJSONSchema6(requestedSchema)};if(mode==="url"){params["elicitationId"]=elicitId;params["url"]=url}this.logger.info("sendElicitRequest",{relatedRequestId,elicitId,mode,ttl});await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",params));return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}}}});function createSessionScopedEventStore(store,sessionId){const prefix=`${sessionId}${SCOPE_SEPARATOR}`;const scope=streamId=>`${prefix}${streamId}`;const unscope=streamId=>{const value=String(streamId);return value.startsWith(prefix)?value.slice(prefix.length):value};const resolveOwnedStream=async eventId=>{const lookup=store.getStreamIdForEventId;if(lookup){const resolved=await lookup.call(store,eventId);return resolved!==void 0&&String(resolved).startsWith(prefix)?resolved:void 0}if(!String(eventId).startsWith(prefix))return void 0;const value=String(eventId);const lastColon=value.lastIndexOf(":");return lastColon===-1?void 0:value.slice(0,lastColon)};return{async storeEvent(streamId,message){return store.storeEvent(scope(streamId),message)},async getStreamIdForEventId(eventId){const owned=await resolveOwnedStream(eventId);return owned===void 0?void 0:unscope(owned)},async replayEventsAfter(lastEventId,options){const owned=await resolveOwnedStream(lastEventId);if(owned===void 0){return"default-stream"}return unscope(await store.replayEventsAfter(lastEventId,options))}}}var SCOPE_SEPARATOR;var init_session_scoped_event_store=__esm({"libs/sdk/src/transport/event-stores/session-scoped.event-store.ts"(){"use strict";SCOPE_SEPARATOR=" "}});var streamable_http_transport_exports={};__export(streamable_http_transport_exports,{RecreateableStreamableHTTPServerTransport:()=>RecreateableStreamableHTTPServerTransport});import{StreamableHTTPServerTransport,WebStandardStreamableHTTPServerTransport as WebStandardStreamableHTTPServerTransport2}from"@frontmcp/protocol";var RecreateableStreamableHTTPServerTransport;var init_streamable_http_transport=__esm({"libs/sdk/src/transport/adapters/streamable-http-transport.ts"(){"use strict";init_transport_errors();RecreateableStreamableHTTPServerTransport=class extends StreamableHTTPServerTransport{_pendingInitState;_constructorOptions;_isStateless;constructor(options={}){super(options);this._constructorOptions=options;this._isStateless=options.isStateless??false}get isInitialized(){return this._webStandardTransport?._initialized??false}get hasPendingInitState(){return this._pendingInitState!==void 0}setInitializationState(sessionId){if(!sessionId||typeof sessionId!=="string"||sessionId.trim()===""){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] sessionId cannot be empty")}const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=sessionId;return}this._applyInitState(webTransport,sessionId)}resetForReinitialization(){const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=void 0;return}if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=false;webTransport.sessionId=void 0;this._pendingInitState=void 0}_applyInitState(webTransport,sessionId){if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=true;webTransport.sessionId=sessionId}async handleRequest(req,res,body){const oldWebTransport=this._webStandardTransport;if(oldWebTransport&&this._isStateless&&oldWebTransport._hasHandledRequest){const fresh=new WebStandardStreamableHTTPServerTransport2(this._constructorOptions);fresh.onmessage=oldWebTransport.onmessage;fresh.onclose=oldWebTransport.onclose;fresh.onerror=oldWebTransport.onerror;await fresh.start();this._webStandardTransport=fresh}if(this._pendingInitState){const webTransport=this._webStandardTransport;if(webTransport){this._applyInitState(webTransport,this._pendingInitState);this._pendingInitState=void 0}}if(!res.headersSent)res.removeHeader?.("Content-Type");return super.handleRequest(req,res,body)}}}});import{toJSONSchema as toJSONSchema7}from"@frontmcp/lazy-zod";async function loadStreamableHttpTransport(){RecreateableTransport2??=(await Promise.resolve().then(()=>(init_streamable_http_transport(),streamable_http_transport_exports))).RecreateableStreamableHTTPServerTransport}var RecreateableTransport2,resolveSessionIdGenerator,TransportStreamableHttpAdapter;var init_transport_streamable_http_adapter=__esm({"libs/sdk/src/transport/adapters/transport.streamable-http.adapter.ts"(){"use strict";init_errors();init_session_scoped_event_store();init_transport_error();init_transport_types();init_transport_local_adapter();resolveSessionIdGenerator=(transportType,sessionId)=>{return transportType==="stateless-http"?()=>STATELESS_SESSION_ID:()=>sessionId};TransportStreamableHttpAdapter=class extends LocalTransportAdapter{createTransport(sessionId,response){const sessionIdGenerator=resolveSessionIdGenerator(this.key.type,sessionId);const sharedEventStore=this.scope.eventStore;const eventStore=sharedEventStore?createSessionScopedEventStore(sharedEventStore,sessionId):void 0;const isStateless=this.key.type==="stateless-http";if(!RecreateableTransport2){throw new InternalMcpError("The Streamable HTTP transport was used before loadStreamableHttpTransport() loaded it")}return new RecreateableTransport2({sessionIdGenerator,isStateless,onsessionclosed:()=>{},onsessioninitialized:sessionId2=>{if(sessionId2){this.logger.verbose("[StreamableHttpAdapter] session initialized",{sessionId:sessionId2.slice(0,40)})}else{this.logger.verbose("[StreamableHttpAdapter] stateless session initialized")}},eventStore})}async initialize(req,res){this.ensureAuthInfo(req,this);this.logger.verbose("[StreamableHttpAdapter] initialize() called",{method:req.method,sessionId:this.key.sessionId.slice(0,30),bodyMethod:req.body?.method,bodyJsonrpc:req.body?.jsonrpc,bodyId:req.body?.id,bodyType:typeof req.body,bodyKeys:req.body&&typeof req.body==="object"?Object.keys(req.body):[]});await this.ready;this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest",{isRecreatable:RecreateableTransport2!==void 0&&this.transport instanceof RecreateableTransport2,hasWebTransport:!!this.transport._webStandardTransport,webTransportInitialized:this.transport._webStandardTransport?._initialized,webTransportStarted:this.transport._webStandardTransport?._started,hasSessionIdGenerator:this.transport._webStandardTransport?.sessionIdGenerator!==void 0});const originalWrite=res.write.bind(res);const originalEnd=res.end.bind(res);let responseBody="";res.write=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}return originalWrite.call(this,chunk,encodingOrCb,cb)};const adapter=this;res.end=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}adapter.logger.verbose("[StreamableHttpAdapter] initialize response",{statusCode:res.statusCode,headers:res.getHeaders?.()??{},bodyLength:responseBody.length});return originalEnd.call(this,chunk,encodingOrCb,cb)};return this.transport.handleRequest(req,res,req.body)}async handleRequest(req,res){this.ensureAuthInfo(req,this);if(req.method==="GET"){return this.transport.handleRequest(req,res)}else{if(this.handleIfElicitResult(req)){return}return this.transport.handleRequest(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){await this.cancelPendingElicit();const store=this.requireElicitStore();const sessionId=this.key.sessionId;const flowOutput=await this.scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:toJSONSchema7(requestedSchema),options});const{elicitId,expiresAt,requestParams,pendingRecord}=flowOutput;const ttl=expiresAt-Date.now();this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create",{relatedRequestId,elicitId,mode:pendingRecord.mode,message:message.slice(0,100)});try{await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",requestParams),{relatedRequestId});this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed")}catch(error){this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed",error);try{await store.deletePending(sessionId);this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: cleaned up pending record after send failure")}catch(cleanupError){this.logger.warn("[StreamableHttpAdapter] sendElicitRequest: failed to clean up pending record",cleanupError)}throw error}return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}get isInitialized(){return this.transport.isInitialized||this.transport.hasPendingInitState}resetForReinitialization(){this.transport.resetForReinitialization();this.logger.info("[StreamableHttpAdapter] Reset transport for re-initialization",{sessionId:this.key.sessionId?.slice(0,20)})}markAsInitialized(){this.transport.setInitializationState(this.key.sessionId);this.logger.info("[StreamableHttpAdapter] Marked transport as pre-initialized for session recreation",{sessionId:this.key.sessionId?.slice(0,20),isInitialized:this.transport.isInitialized})}}}});import{isAnonymousSubject as isAnonymousSubject8}from"@frontmcp/auth";import{internalZ as z113}from"@frontmcp/lazy-zod";import{MCP_20260728_META as MCP_20260728_META8,StreamEventsRequestSchema as StreamEventsRequestSchema2}from"@frontmcp/protocol";import{runRequestExclusive as runRequestExclusive5}from"@frontmcp/utils";function frame3(message){return encoder8.encode(`event: message
|
|
294
|
+
`)}get sessionId(){return this._sessionId}get lastEventId(){return this._eventIdCounter}setEventIdCounter(eventId){this._eventIdCounter=eventId}}}});var init_node_sse_transport=__esm({"libs/sdk/src/transport/adapters/polyfills/node-sse-transport.ts"(){"use strict";init_base_sse_transport()}});var sse_transport_exports={};__export(sse_transport_exports,{RecreateableSSEServerTransport:()=>RecreateableSSEServerTransport});var RecreateableSSEServerTransport;var init_sse_transport=__esm({"libs/sdk/src/transport/adapters/sse-transport.ts"(){"use strict";init_node_sse_transport();RecreateableSSEServerTransport=class extends SSEServerTransport{_isRecreatedSession=false;constructor(endpoint,res,options){super(endpoint,res,options);if(options?.initialEventId!==void 0&&this.isValidEventId(options.initialEventId)){this.setEventIdCounter(options.initialEventId);this._isRecreatedSession=true}}isValidEventId(eventId){return Number.isInteger(eventId)&&eventId>=0&&eventId<=Number.MAX_SAFE_INTEGER}get isRecreatedSession(){return this._isRecreatedSession}get eventIdCounter(){return this.lastEventId}setEventIdCounter(eventId){if(!this.isValidEventId(eventId)){console.warn(`[RecreateableSSEServerTransport] Invalid eventId: ${eventId}. Must be a non-negative integer. Ignoring.`);return}super.setEventIdCounter(eventId)}setSessionState(sessionId,lastEventId){if(this.sessionId!==sessionId){const redact=id=>`${id.slice(0,8)}\u2026`;console.warn(`RecreateableSSEServerTransport: session ID mismatch. Expected ${redact(this.sessionId)}, got ${redact(sessionId)}. Using constructor value.`)}if(lastEventId!==void 0){this.setEventIdCounter(lastEventId)}this._isRecreatedSession=true}}}});import{toJSONSchema as toJSONSchema6}from"@frontmcp/lazy-zod";async function loadSseTransport(){RecreateableTransport??=(await Promise.resolve().then(()=>(init_sse_transport(),sse_transport_exports))).RecreateableSSEServerTransport}function sseTransportClass(){if(!RecreateableTransport){throw new InternalMcpError("The SSE transport was used before loadSseTransport() loaded it")}return RecreateableTransport}var RecreateableTransport,TransportSSEAdapter;var init_transport_sse_adapter=__esm({"libs/sdk/src/transport/adapters/transport.sse.adapter.ts"(){"use strict";init_elicitation_types();init_errors();init_transport_error();init_transport_local_adapter();TransportSSEAdapter=class extends LocalTransportAdapter{sessionId;configureTransportHandlers(transport){transport.onerror=error=>{console.error("SSE error:",error instanceof Error?error.message:"Unknown error")};transport.onclose=this.destroy.bind(this)}createTransport(sessionId,res){this.sessionId=sessionId;this.logger.info(`new transport session: ${sessionId.slice(0,40)}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId});this.configureTransportHandlers(transport);return transport}createTransportFromSession(sessionId,res,lastEventId){this.sessionId=sessionId;this.logger.info(`recreating transport session: ${sessionId.slice(0,40)}, lastEventId: ${lastEventId??"none"}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId,initialEventId:lastEventId});this.configureTransportHandlers(transport);return transport}initialize(req,res){this.logger.verbose(`[${this.sessionId}] handle initialize request`);this.ensureAuthInfo(req,this);return Promise.resolve()}async handleRequest(req,res){await this.ready;const authInfo=this.ensureAuthInfo(req,this);if(this.handleIfElicitResult(req)){this.logger.verbose(`[${this.sessionId}] handled elicitation result`);res.writeHead(202,{"Content-Type":"application/json"});res.end(JSON.stringify({jsonrpc:"2.0",id:null,result:{}}));return}if(req.method==="GET"){this.logger.verbose(`[${this.sessionId}] handle get request`);return this.transport.handleMessage(req.body,{requestInfo:{headers:req.headers},authInfo})}else{this.logger.verbose(`[${this.sessionId}] handle post request`);return this.transport.handlePostMessage(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=options??{};if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}await this.cancelPendingElicit();const elicitId=elicitationId||`elicit-${this.newRequestId}`;const sessionId=this.key.sessionId;const expiresAt=Date.now()+ttl;const store=this.requireElicitStore();await store.setPending({elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode});const params={mode,message,requestedSchema:toJSONSchema6(requestedSchema)};if(mode==="url"){params["elicitationId"]=elicitId;params["url"]=url}this.logger.info("sendElicitRequest",{relatedRequestId,elicitId,mode,ttl});await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",params));return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}}}});function createSessionScopedEventStore(store,sessionId){const prefix=`${sessionId}${SCOPE_SEPARATOR}`;const scope=streamId=>`${prefix}${streamId}`;const unscope=streamId=>{const value=String(streamId);return value.startsWith(prefix)?value.slice(prefix.length):value};const resolveOwnedStream=async eventId=>{const lookup=store.getStreamIdForEventId;if(lookup){const resolved=await lookup.call(store,eventId);return resolved!==void 0&&String(resolved).startsWith(prefix)?resolved:void 0}if(!String(eventId).startsWith(prefix))return void 0;const value=String(eventId);const lastColon=value.lastIndexOf(":");return lastColon===-1?void 0:value.slice(0,lastColon)};return{async storeEvent(streamId,message){return store.storeEvent(scope(streamId),message)},async getStreamIdForEventId(eventId){const owned=await resolveOwnedStream(eventId);return owned===void 0?void 0:unscope(owned)},async replayEventsAfter(lastEventId,options){const owned=await resolveOwnedStream(lastEventId);if(owned===void 0){return"default-stream"}return unscope(await store.replayEventsAfter(lastEventId,options))}}}var SCOPE_SEPARATOR;var init_session_scoped_event_store=__esm({"libs/sdk/src/transport/event-stores/session-scoped.event-store.ts"(){"use strict";SCOPE_SEPARATOR=" "}});var streamable_http_transport_exports={};__export(streamable_http_transport_exports,{RecreateableStreamableHTTPServerTransport:()=>RecreateableStreamableHTTPServerTransport});import{StreamableHTTPServerTransport,WebStandardStreamableHTTPServerTransport as WebStandardStreamableHTTPServerTransport2}from"@frontmcp/protocol";var RecreateableStreamableHTTPServerTransport;var init_streamable_http_transport=__esm({"libs/sdk/src/transport/adapters/streamable-http-transport.ts"(){"use strict";init_transport_errors();RecreateableStreamableHTTPServerTransport=class extends StreamableHTTPServerTransport{_pendingInitState;_constructorOptions;_isStateless;constructor(options={}){super(options);this._constructorOptions=options;this._isStateless=options.isStateless??false}get isInitialized(){return this._webStandardTransport?._initialized??false}get hasPendingInitState(){return this._pendingInitState!==void 0}setInitializationState(sessionId){if(!sessionId||typeof sessionId!=="string"||sessionId.trim()===""){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] sessionId cannot be empty")}const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=sessionId;return}this._applyInitState(webTransport,sessionId)}resetForReinitialization(){const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=void 0;return}if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=false;webTransport.sessionId=void 0;this._pendingInitState=void 0}_applyInitState(webTransport,sessionId){if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=true;webTransport.sessionId=sessionId}async handleRequest(req,res,body){const oldWebTransport=this._webStandardTransport;if(oldWebTransport&&this._isStateless&&oldWebTransport._hasHandledRequest){const fresh=new WebStandardStreamableHTTPServerTransport2(this._constructorOptions);fresh.onmessage=oldWebTransport.onmessage;fresh.onclose=oldWebTransport.onclose;fresh.onerror=oldWebTransport.onerror;await fresh.start();this._webStandardTransport=fresh}if(this._pendingInitState){const webTransport=this._webStandardTransport;if(webTransport){this._applyInitState(webTransport,this._pendingInitState);this._pendingInitState=void 0}}if(!res.headersSent)res.removeHeader?.("Content-Type");return super.handleRequest(req,res,body)}}}});import{toJSONSchema as toJSONSchema7}from"@frontmcp/lazy-zod";async function loadStreamableHttpTransport(){RecreateableTransport2??=(await Promise.resolve().then(()=>(init_streamable_http_transport(),streamable_http_transport_exports))).RecreateableStreamableHTTPServerTransport}var RecreateableTransport2,resolveSessionIdGenerator,TransportStreamableHttpAdapter;var init_transport_streamable_http_adapter=__esm({"libs/sdk/src/transport/adapters/transport.streamable-http.adapter.ts"(){"use strict";init_errors();init_session_scoped_event_store();init_transport_error();init_transport_types();init_transport_local_adapter();resolveSessionIdGenerator=(transportType,sessionId)=>{return transportType==="stateless-http"?()=>STATELESS_SESSION_ID:()=>sessionId};TransportStreamableHttpAdapter=class extends LocalTransportAdapter{createTransport(sessionId,response){const sessionIdGenerator=resolveSessionIdGenerator(this.key.type,sessionId);const sharedEventStore=this.scope.eventStore;const eventStore=sharedEventStore?createSessionScopedEventStore(sharedEventStore,sessionId):void 0;const isStateless=this.key.type==="stateless-http";if(!RecreateableTransport2){throw new InternalMcpError("The Streamable HTTP transport was used before loadStreamableHttpTransport() loaded it")}return new RecreateableTransport2({sessionIdGenerator,isStateless,onsessionclosed:()=>{},onsessioninitialized:sessionId2=>{if(sessionId2){this.logger.verbose("[StreamableHttpAdapter] session initialized",{sessionId:sessionId2.slice(0,40)})}else{this.logger.verbose("[StreamableHttpAdapter] stateless session initialized")}},eventStore})}async initialize(req,res){this.ensureAuthInfo(req,this);this.logger.verbose("[StreamableHttpAdapter] initialize() called",{method:req.method,sessionId:this.key.sessionId.slice(0,30),bodyMethod:req.body?.method,bodyJsonrpc:req.body?.jsonrpc,bodyId:req.body?.id,bodyType:typeof req.body,bodyKeys:req.body&&typeof req.body==="object"?Object.keys(req.body):[]});await this.ready;this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest",{isRecreatable:RecreateableTransport2!==void 0&&this.transport instanceof RecreateableTransport2,hasWebTransport:!!this.transport._webStandardTransport,webTransportInitialized:this.transport._webStandardTransport?._initialized,webTransportStarted:this.transport._webStandardTransport?._started,hasSessionIdGenerator:this.transport._webStandardTransport?.sessionIdGenerator!==void 0});const originalWrite=res.write.bind(res);const originalEnd=res.end.bind(res);let responseBody="";res.write=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}return originalWrite.call(this,chunk,encodingOrCb,cb)};const adapter=this;res.end=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}adapter.logger.verbose("[StreamableHttpAdapter] initialize response",{statusCode:res.statusCode,headers:res.getHeaders?.()??{},bodyLength:responseBody.length});return originalEnd.call(this,chunk,encodingOrCb,cb)};return this.transport.handleRequest(req,res,req.body)}async handleRequest(req,res){this.ensureAuthInfo(req,this);if(req.method==="GET"){return this.transport.handleRequest(req,res)}else{if(this.handleIfElicitResult(req)){return}return this.transport.handleRequest(req,res,req.body)}}async destroy(reason){if(reason===void 0)await this.transport.close().catch(()=>void 0);return super.destroy(reason)}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){await this.cancelPendingElicit();const store=this.requireElicitStore();const sessionId=this.key.sessionId;const flowOutput=await this.scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:toJSONSchema7(requestedSchema),options});const{elicitId,expiresAt,requestParams,pendingRecord}=flowOutput;const ttl=expiresAt-Date.now();this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create",{relatedRequestId,elicitId,mode:pendingRecord.mode,message:message.slice(0,100)});try{await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",requestParams),{relatedRequestId});this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed")}catch(error){this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed",error);try{await store.deletePending(sessionId);this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: cleaned up pending record after send failure")}catch(cleanupError){this.logger.warn("[StreamableHttpAdapter] sendElicitRequest: failed to clean up pending record",cleanupError)}throw error}return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}get isInitialized(){return this.transport.isInitialized||this.transport.hasPendingInitState}resetForReinitialization(){this.transport.resetForReinitialization();this.logger.info("[StreamableHttpAdapter] Reset transport for re-initialization",{sessionId:this.key.sessionId?.slice(0,20)})}markAsInitialized(){this.transport.setInitializationState(this.key.sessionId);this.logger.info("[StreamableHttpAdapter] Marked transport as pre-initialized for session recreation",{sessionId:this.key.sessionId?.slice(0,20),isInitialized:this.transport.isInitialized})}}}});import{isAnonymousSubject as isAnonymousSubject8}from"@frontmcp/auth";import{internalZ as z113}from"@frontmcp/lazy-zod";import{MCP_20260728_META as MCP_20260728_META8,StreamEventsRequestSchema as StreamEventsRequestSchema2}from"@frontmcp/protocol";import{runRequestExclusive as runRequestExclusive5}from"@frontmcp/utils";function frame3(message){return encoder8.encode(`event: message
|
|
295
295
|
data: ${JSON.stringify(message)}
|
|
296
296
|
|
|
297
297
|
`)}function acceptsEventStream(headers){const accept=readHeader(headers,"accept");return typeof accept==="string"&&accept.includes("text/event-stream")}function extractTraceContext(meta){const out={};for(const key of TRACE_META_KEYS){if(typeof meta[key]==="string")out[key]=meta[key]}return Object.keys(out).length>0?out:void 0}async function*streamMessageResponse(options,sink,requestId,runInContext){let outcome;let failure;const running=runInContext(async()=>{try{outcome=await dispatch20260728(options)}catch(error){failure=error}}).finally(()=>sink.close());while(!sink.closed){await sink.waitForActivity();for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}}await running;for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}const id=requestId??null;if(failure!==void 0){const mapped=toJsonRpcError(failure);yield frame3({jsonrpc:"2.0",id,error:mapped.error});return}if(outcome?.kind==="error"){yield frame3({jsonrpc:"2.0",id,error:outcome.error});return}yield frame3({jsonrpc:"2.0",id,result:outcome?.result})}function isAnonymousCaller(auth){if(!auth)return true;if(!isAnonymousSubject8(auth.user?.sub))return false;return!auth.token||auth.session?.payload?.isPublic===true}function errorResponse(status,error,id){return httpRespond.json({jsonrpc:"2.0",id:id===void 0?null:id,error},{status})}function toClientInfo(value){if(typeof value!=="object"||value===null)return void 0;const{name:name59,version}=value;return typeof name59==="string"&&typeof version==="string"?{name:name59,version}:void 0}var plan24,MAX_RESOURCE_SUBSCRIPTIONS,subscriptionParamsSchema,requestIdSchema,stateSchema21,name24,Stage24,encoder8,TRACE_META_KEYS,HandleMcp20260728Flow;var init_handle_mcp_20260728_flow=__esm({"libs/sdk/src/transport/flows/handle.mcp-20260728.flow.ts"(){"use strict";init_common();init_tool_lookup_utils();init_context();init_notification();init_notification_service();init_skill_instructions_helper();init_mcp_20260728();init_mcp_surface();plan24={pre:["parseInput","validate","router"],execute:["handleNotification","handleSubscriptions","handleEventStream","handleMessage"],post:[],finalize:["cleanup"]};MAX_RESOURCE_SUBSCRIPTIONS=1e3;subscriptionParamsSchema=z113.object({notifications:z113.object({toolsListChanged:z113.boolean().optional(),promptsListChanged:z113.boolean().optional(),resourcesListChanged:z113.boolean().optional(),resourceSubscriptions:z113.array(z113.string()).max(MAX_RESOURCE_SUBSCRIPTIONS,{message:`subscriptions/listen takes at most ${MAX_RESOURCE_SUBSCRIPTIONS} resourceSubscriptions`}).optional()}).default({})});requestIdSchema=z113.union([z113.string(),z113.number()]);stateSchema21=z113.object({version:z113.string().optional(),requestType:z113.enum(["notification","subscriptions","eventStream","message"]).optional(),isAnonymous:z113.boolean().default(true),clientDeclaredRevision:z113.boolean().optional()});name24="handle:mcp-202607280728";({Stage:Stage24}=FlowHooksOf(name24));encoder8=new TextEncoder;TRACE_META_KEYS=["traceparent","tracestate","baggage"];HandleMcp20260728Flow=class extends FlowBase{name=name24;get log(){return this.scope.logger.child("HandleMcp20260728Flow")}async parseInput(){const{request:request2}=this.rawInput;const auth=request2[ServerRequestTokens.auth];this.state.set(stateSchema21.parse({isAnonymous:isAnonymousCaller(auth)}))}async validate(){const{request:request2}=this.rawInput;const method=request2.method.toUpperCase();if(method==="GET"||method==="DELETE"){this.respond({kind:"text",status:405,body:`HTTP ${method} is not supported by MCP protocol 2026-07-28`,contentType:"text/plain; charset=utf-8",headers:{Allow:"POST"}});return}const body=request2.body??{};const scope=this.scope;const clientDeclaredRevision=declaresProtocol20260728({headers:request2.headers,body});const result=validate20260728Request({headers:request2.headers,body,lookupToolSchema:toolName=>this.findToolSchema(scope,toolName),strictHeaders:clientDeclaredRevision&&!this.stdioOrigin});if(!result.ok){this.log.info("validate: rejected",{code:result.error.code,message:result.error.message});this.respond(errorResponse(result.status,result.error,body["id"]));return}this.state.set("version",result.version);this.state.set("clientDeclaredRevision",clientDeclaredRevision)}get stdioOrigin(){return this.rawInput.request[ServerRequestTokens.stdio]}buildContextRunner(){const context=this.tryGetContext();if(!context)return fn=>fn();const storage=this.scope.providers.get(FrontMcpContextStorage);return async fn=>{await runRequestExclusive5(()=>storage.runWithContext(context,fn))}}findToolSchema(scope,toolName){return lookupTool(scope,toolName)?.getInputJsonSchema()??null}async router(){const body=this.rawInput.request.body??{};const isNotification=body["id"]===void 0||body["id"]===null;if(isNotification){this.state.set("requestType","notification");return}if(body["method"]==="events/stream"&&this.scope.events?.performs("push")){this.state.set("requestType","eventStream");return}this.state.set("requestType",body["method"]==="subscriptions/listen"?"subscriptions":"message")}async handleNotification(){this.respond({kind:"text",status:202,body:"",contentType:"text/plain; charset=utf-8"})}async handleSubscriptions(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const subscriptionId=requestIdSchema.safeParse(body["id"]);if(!subscriptionId.success){this.respond(errorResponse(400,{code:-32602,message:"subscriptions/listen requires a string or number id"},null));return}const parsedParams=subscriptionParamsSchema.safeParse(body["params"]??{});if(!parsedParams.success){this.respond(errorResponse(400,{code:-32602,message:`Invalid subscriptions/listen params: ${parsedParams.error.issues[0]?.message??"not an object"}`},subscriptionId.data));return}const auth=request2[ServerRequestTokens.auth];const listenerAuthInfo=auth?authInfoFromAuthorization(auth):{};const mayRead=this.resourceReadCheck(listenerAuthInfo);const requested={...parsedParams.data.notifications,resourceSubscriptions:await this.readableUris(parsedParams.data.notifications.resourceSubscriptions,mayRead)};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});const{acknowledged,stream}=createSubscriptionStream({scope:this.scope,subscriptionId:subscriptionId.data,requested,channels:await this.listenedChannels(body["params"]?._meta),signal:controller.signal,mayReceiveUpdate:(uri,watchedUri)=>listenerMayReceive(()=>hasExpiredCaller({caller:sessionCallerOf(listenerAuthInfo)}),()=>mayRead(this.scope.resources.findResourceForUri(uri)?uri:watchedUri))});this.log.info("handleSubscriptions: stream opened",{subscriptionId:body["id"],acknowledged:Object.keys(acknowledged)});this.respond({kind:"sse",status:200,stream,contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}async handleEventStream(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const requestId=requestIdSchema.safeParse(body["id"]);if(!requestId.success){this.respond(errorResponse(400,{code:-32602,message:"events/stream requires a string or number id"},null));return}const streamRequest=StreamEventsRequestSchema2.safeParse({method:"events/stream",params:body["params"]});if(!streamRequest.success){const problem2=streamRequest.error.issues[0]?.message??"not an object";const error={code:-32602,message:`Invalid events/stream params: ${problem2}`};this.respond(errorResponse(400,error,requestId.data));return}const meta=body["params"]?._meta??{};const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const platformDetection=this.scope.metadata.transport?.platformDetection;this.tryGetContext()?.setClientInfo(clientInfo,resolvePlatformType(clientInfo,clientCapabilities,platformDetection));const auth=request2[ServerRequestTokens.auth];const authInfo=auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:{};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});let opened;try{opened=await this.scope.runFlowForOutput("events:stream",{request:streamRequest.data,ctx:{authInfo,surface:mcpRequestSurface(this.scope)},requestId:requestId.data,signal:controller.signal})}catch(failure){const mapped=toJsonRpcError(failure);this.respond(errorResponse(mapped.status,mapped.error,requestId.data));return}this.log.info("handleEventStream: stream opened",{subscriptionId:requestId.data});this.respond({kind:"sse",status:200,stream:eventStreamFrames(opened.stream,requestId.data),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}resourceReadCheck(authInfo){const runInRequest=this.buildContextRunner();const ctx={authInfo,surface:mcpRequestSurface(this.scope)};return async uri=>{let allowed=false;await runInRequest(async()=>{const request2={method:"resources/subscribe",params:{uri}};allowed=await this.scope.runFlow("resources:subscribe",{request:request2,ctx}).then(()=>true,()=>false)});return allowed}}async readableUris(uris,mayRead){if(!uris)return void 0;const unique=[...new Set(uris)];const allowed=await Promise.all(unique.map(mayRead));return unique.filter((_uri,index)=>allowed[index])}async listenedChannels(meta){const capabilities=meta?.[MCP_20260728_META8.clientCapabilities];if(!supportsChannels(capabilities)||!this.scope.channels)return[];const listed=await this.scope.runFlowForOutput("channels:list",{});return listed.channels.map(channel2=>channel2.name)}async handleMessage(){const{request:request2}=this.rawInput;const body=request2.body??{};const params=body["params"]??{};const meta=params["_meta"]??{};const auth=request2[ServerRequestTokens.auth];const stdio=this.stdioOrigin;const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const logLevel=typeof meta[MCP_20260728_META8.logLevel]==="string"?meta[MCP_20260728_META8.logLevel]:void 0;const rawProgressToken=meta["progressToken"];const progressToken=typeof rawProgressToken==="string"||typeof rawProgressToken==="number"?rawProgressToken:void 0;const sink=new RequestNotificationSink(logLevel,progressToken);const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const platformType=resolvePlatformType(clientInfo,clientCapabilities,this.scope.metadata.transport?.platformDetection);this.tryGetContext()?.setClientInfo(clientInfo,platformType);const dispatchOptions={scope:this.scope,body,clientCapabilities,frontmcpContext:this.tryGetContext(),authInfo:auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:stdio&&{sessionId:this.tryGetContext()?.sessionId},isAnonymous:this.state.required.isAnonymous,transportPrincipal:stdio?.principal,signal:stdio?.signal,clientDeclaredRevision:this.state.clientDeclaredRevision!==false,composeInstructions:(caller,clientName)=>composeCallerInstructions(this.scope,{ctx:caller,clientName:clientName??this.tryGetContext()?.clientInfo?.name,skillUriHints:true}),notificationSink:sink,traceContext:extractTraceContext(meta)};const streams=stdio!==void 0||acceptsEventStream(request2.headers);if(sink.active&&streams){this.respond({kind:"sse",status:200,stream:streamMessageResponse(dispatchOptions,sink,body["id"],this.buildContextRunner()),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}});return}const outcome=await dispatch20260728(dispatchOptions);sink.close();if(outcome.kind==="error"){this.respond(errorResponse(outcome.status,outcome.error,body["id"]));return}this.respond(httpRespond.json({jsonrpc:"2.0",id:body["id"]??null,result:outcome.result},{status:200}))}async cleanup(){}};__decorateClass([Stage24("parseInput")],HandleMcp20260728Flow.prototype,"parseInput",1);__decorateClass([Stage24("validate")],HandleMcp20260728Flow.prototype,"validate",1);__decorateClass([Stage24("router")],HandleMcp20260728Flow.prototype,"router",1);__decorateClass([Stage24("handleNotification",{filter:({state})=>state.required.requestType==="notification"})],HandleMcp20260728Flow.prototype,"handleNotification",1);__decorateClass([Stage24("handleSubscriptions",{filter:({state})=>state.required.requestType==="subscriptions"})],HandleMcp20260728Flow.prototype,"handleSubscriptions",1);__decorateClass([Stage24("handleEventStream",{filter:({state})=>state.required.requestType==="eventStream"})],HandleMcp20260728Flow.prototype,"handleEventStream",1);__decorateClass([Stage24("handleMessage",{filter:({state})=>state.required.requestType==="message"})],HandleMcp20260728Flow.prototype,"handleMessage",1);__decorateClass([Stage24("cleanup")],HandleMcp20260728Flow.prototype,"cleanup",1);HandleMcp20260728Flow=__decorateClass([FrontMcpFlow({name:name24,plan:plan24,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleMcp20260728Flow)}});import{internalZ as z114}from"@frontmcp/lazy-zod";function getQuerySessionId2(urlPath){if(!urlPath)return void 0;try{const u=new URL(String(urlPath),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function resolveLegacySseSession(params){const{rawHeader,requestUrl,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);const querySessionId=getQuerySessionId2(requestUrl);const validatedQuerySessionId=querySessionId?validateMcpSessionHeader(querySessionId):void 0;if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(querySessionId!==void 0&&!validatedQuerySessionId){return{responded404:true,createdNew:false}}const effectiveSessionId=mcpSessionHeader??validatedQuerySessionId;if(effectiveSessionId){if(authorizationSession?.id===effectiveSessionId){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}var plan25,stateSessionSchema,stateSchema22,name25,Stage25,HandleSseFlow;var init_handle_sse_flow=__esm({"libs/sdk/src/transport/flows/handle.sse.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ha_headers();init_skill_mode_utils();plan25={pre:["parseInput","router"],execute:["onInitialize","onMessage","onElicitResult"],post:[],finalize:["cleanup"]};stateSessionSchema=z114.object({id:z114.string(),payload:z114.object({nodeId:z114.string(),authSig:z114.string(),uuid:z114.string().uuid(),iat:z114.number(),protocol:z114.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z114.boolean().optional(),platformType:z114.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema22=z114.object({token:z114.string(),session:stateSessionSchema,requestType:z114.enum(["initialize","message","elicitResult"]).optional()});name25="handle:legacy-sse";({Stage:Stage25}=FlowHooksOf(name25));HandleSseFlow=class extends FlowBase{async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const anyReq=request2;const resolution=resolveLegacySseSession({rawHeader:request2.headers?.["mcp-session-id"],requestUrl:anyReq.url??anyReq.path,authorizationSession:authorization.session,createSession:()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("legacy-sse",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})}});if(resolution.responded404||!resolution.session){this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=resolution.session;this.state.set(stateSchema22.parse({token,session}))}async router(){const{request:request2}=this.rawInput;const requestPath=normalizeEntryPrefix(request2.path);const prefix=normalizeEntryPrefix(this.scope.entryPath);const scopePath=normalizeScopeBase(this.scope.routeBase);const basePath=`${prefix}${scopePath}`;if(requestPath===`${basePath}/sse`){this.state.set("requestType","initialize")}else if(requestPath===`${basePath}/message`){this.state.set("requestType","message")}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const authorization=request2[ServerRequestTokens.auth];authorization.session??=session;const transport=await transportService.createTransporter("sse",token,session.id,response);applyNodeAffinity(response,request2);await transport.initialize(request2,response);this.handled()}async onElicitResult(){this.fail(new Error("Not implemented"))}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:legacy-sse:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const transport=await transportService.getTransporter("sse",token,session.id);if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("sse",token,session.id);const body=request2.body;if(wasCreated){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"]});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}await transport.handleRequest(request2,response);this.handled()}};__decorateClass([Stage25("parseInput")],HandleSseFlow.prototype,"parseInput",1);__decorateClass([Stage25("router")],HandleSseFlow.prototype,"router",1);__decorateClass([Stage25("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleSseFlow.prototype,"onInitialize",1);__decorateClass([Stage25("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleSseFlow.prototype,"onElicitResult",1);__decorateClass([Stage25("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleSseFlow.prototype,"onMessage",1);HandleSseFlow=__decorateClass([FrontMcpFlow({name:name25,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,plan:plan25})],HandleSseFlow)}});import{internalZ as z115}from"@frontmcp/lazy-zod";import{RequestSchema}from"@frontmcp/protocol";var plan26,stateSchema23,name26,Stage26,HandleStatelessHttpFlow;var init_handle_stateless_http_flow=__esm({"libs/sdk/src/transport/flows/handle.stateless-http.flow.ts"(){"use strict";init_common();init_errors();init_ha_headers();init_transport_types();plan26={pre:["applyNodeHeaders","parseInput","router"],execute:["handleRequest"],post:[],finalize:["cleanup"]};stateSchema23=z115.object({token:z115.string().optional(),isAuthenticated:z115.boolean(),requestType:z115.enum(["initialize","message"]).optional()});name26="handle:stateless-http";({Stage:Stage26}=FlowHooksOf(name26));HandleStatelessHttpFlow=class extends FlowBase{name=name26;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const auth=request2[ServerRequestTokens.auth];const token=auth?.token;const isAuthenticated=!!token&&token.length>0;logger.verbose("parseInput",{isAuthenticated,hasToken:!!token});this.state.set(stateSchema23.parse({token:token||void 0,isAuthenticated}))}async router(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const body=request2.body;const method=body?.method;if(method==="initialize"){this.state.set("requestType","initialize");logger.verbose("router: requestType=initialize, method=POST")}else if(method&&RequestSchema.safeParse(request2.body).success){this.state.set("requestType","message");logger.verbose(`router: requestType=message, method=${method}`)}else{logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"))}}async handleRequest(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("HandleStatelessHttpFlow");const{request:request2,response}=this.rawInput;const{token,isAuthenticated,requestType}=this.state;logger.verbose(`handleRequest: using ${isAuthenticated?"authenticated":"anonymous"} stateless transport`);const transport=isAuthenticated&&token?await transportService.getOrCreateAuthenticatedStatelessTransport("stateless-http",token,response):await transportService.getOrCreateAnonymousStatelessTransport("stateless-http",response);if(!request2.headers["mcp-session-id"]){request2.headers["mcp-session-id"]=STATELESS_SESSION_ID;logger.verbose(`handleRequest: injected ${STATELESS_SESSION_ID} session ID`)}logger.verbose(`handleRequest: requestType=${requestType}, forwarding to transport`);try{if(requestType==="initialize"){await transport.initialize(request2,response)}else{await transport.handleRequest(request2,response)}}catch(error){logger.error("handleRequest: transport failed",{requestType,error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}this.handled()}};__decorateClass([Stage26("applyNodeHeaders")],HandleStatelessHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage26("parseInput")],HandleStatelessHttpFlow.prototype,"parseInput",1);__decorateClass([Stage26("router")],HandleStatelessHttpFlow.prototype,"router",1);__decorateClass([Stage26("handleRequest")],HandleStatelessHttpFlow.prototype,"handleRequest",1);HandleStatelessHttpFlow=__decorateClass([FrontMcpFlow({name:name26,plan:plan26,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStatelessHttpFlow)}});var EXT_APPS_ERROR_CODES;var init_ext_apps_types=__esm({"libs/sdk/src/ext-apps/ext-apps.types.ts"(){"use strict";EXT_APPS_ERROR_CODES={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TOOL_NOT_FOUND:-32001,TOOL_EXECUTION_FAILED:-32002,NOT_SUPPORTED:-32003,CANCELLED:-32004}}});import{escapeControlCharacters as escapeControlCharacters5,isDevelopment as isDevelopment5}from"@frontmcp/utils";function createExtAppsMessageHandler(options){return new ExtAppsMessageHandler(options)}var MCP_LOG_LEVELS,ExtAppsMessageHandler,ExtAppsError,ExtAppsMethodNotFoundError,ExtAppsInvalidParamsError,ExtAppsNotSupportedError,ExtAppsToolNotFoundError;var init_ext_apps_handler=__esm({"libs/sdk/src/ext-apps/ext-apps.handler.ts"(){"use strict";init_errors();init_ext_apps_types();MCP_LOG_LEVELS={debug:"debug",info:"info",notice:"info",warning:"warn",error:"error",critical:"error",alert:"error",emergency:"error"};ExtAppsMessageHandler=class{context;hostCapabilities;logger;constructor(options){this.context=options.context;this.hostCapabilities=options.hostCapabilities||{};this.logger=options.context.logger.child("ExtAppsMessageHandler")}getHostCapabilities(){return{...this.hostCapabilities}}async handleRequest(request2){const{id,method,params}=request2;this.logger.verbose(`handleRequest: method=${escapeControlCharacters5(method)}, id=${escapeControlCharacters5(id)}`);try{const result=await this.routeMethod(method,params);return{jsonrpc:"2.0",id,result:result===void 0?{}:result}}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);const errorCode2=this.getErrorCode(error);this.logger.warn(`handleRequest: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`);return{jsonrpc:"2.0",id,error:{code:errorCode2,message:this.widgetMessageOf(error),data:isDevelopment5()&&error instanceof Error?{stack:error.stack}:void 0}}}}async handleNotification(notification){const{method,params}=notification;if(method!=="notifications/message"&&method!=="ui/notifications/request-teardown"){this.logger.verbose(`handleNotification: ignoring method=${escapeControlCharacters5(method)}`);return}if(method==="ui/notifications/request-teardown"&&!this.context.close){this.logger.verbose("handleNotification: ignoring ui/notifications/request-teardown (no close callback)");return}try{await this.routeMethod(method,params)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.warn(`handleNotification: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`)}}async routeMethod(method,params){if(params!==void 0&&(params===null||typeof params!=="object"||Array.isArray(params))){throw new ExtAppsInvalidParamsError("Invalid params: expected object")}const normalizedParams=params??{};switch(method){case"ui/initialize":return this.handleInitialize(normalizedParams);case"ui/callServerTool":return this.handleCallServerTool(normalizedParams);case"ui/update-model-context":return this.handleSpecUpdateModelContext(normalizedParams);case"ui/updateModelContext":return this.handleUpdateModelContext(normalizedParams);case"ui/open-link":case"ui/openLink":return this.handleOpenLink(normalizedParams);case"ui/request-display-mode":case"ui/setDisplayMode":return this.handleSetDisplayMode(normalizedParams);case"ui/notifications/request-teardown":case"ui/close":return this.handleClose(normalizedParams);case"notifications/message":return this.handleLogMessage(normalizedParams);case"ui/log":return this.handleLog(normalizedParams);case"ui/registerTool":return this.handleRegisterTool(normalizedParams);case"ui/unregisterTool":return this.handleUnregisterTool(normalizedParams);default:throw new ExtAppsMethodNotFoundError(`Unknown ext-apps method: ${method}`)}}handleInitialize(params){const{appInfo,protocolVersion}=params;this.logger.verbose(`handleInitialize: app=${escapeControlCharacters5(appInfo?.name||"unknown")} v${escapeControlCharacters5(appInfo?.version||"unknown")}, protocol=${escapeControlCharacters5(protocolVersion)}`);return{hostCapabilities:this.hostCapabilities,protocolVersion:protocolVersion||"2024-11-05"}}async handleCallServerTool(params){if(!this.hostCapabilities.serverToolProxy){throw new ExtAppsNotSupportedError("Server tool proxy not supported by host")}const{name:name59,arguments:args={}}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleCallServerTool: tool=${escapeControlCharacters5(name59)}`);return this.context.callTool(name59,args)}async handleUpdateModelContext(params){if(!this.hostCapabilities.modelContextUpdate){throw new ExtAppsNotSupportedError("Model context update not advertised by host")}if(!this.context.updateModelContext){throw new ExtAppsNotSupportedError("Model context update not supported by host")}const{context,merge=true}=params;this.logger.verbose(`handleUpdateModelContext: merge=${merge}`);await this.context.updateModelContext(context,merge)}async handleSpecUpdateModelContext(params){const{content,structuredContent}=params;if(content!==void 0&&!Array.isArray(content)){throw new ExtAppsInvalidParamsError("content must be an array of content blocks")}if(structuredContent!==void 0&&(typeof structuredContent!=="object"||structuredContent===null||Array.isArray(structuredContent))){throw new ExtAppsInvalidParamsError("structuredContent must be an object")}const context={};if(content!==void 0)context.content=content;if(structuredContent!==void 0)context.structuredContent=structuredContent;await this.handleUpdateModelContext({context,merge:false})}async handleOpenLink(params){if(!this.hostCapabilities.openLink){throw new ExtAppsNotSupportedError("Open link not advertised by host")}if(!this.context.openLink){throw new ExtAppsNotSupportedError("Open link not supported by host")}const{url}=params;if(!url||typeof url!=="string"){throw new ExtAppsInvalidParamsError("URL is required")}let parsed;try{parsed=new URL(url)}catch{throw new ExtAppsInvalidParamsError("Invalid URL format")}const allowedSchemes=["http:","https:"];if(!allowedSchemes.includes(parsed.protocol)){throw new ExtAppsInvalidParamsError(`URL scheme '${parsed.protocol}' not allowed. Only http: and https: are permitted.`)}this.logger.verbose(`handleOpenLink: url=${escapeControlCharacters5(url)}`);await this.context.openLink(url)}async handleSetDisplayMode(params){const{mode}=params;if(!mode||!["inline","fullscreen","pip"].includes(mode)){throw new ExtAppsInvalidParamsError("Invalid display mode. Must be inline, fullscreen, or pip")}if(this.hostCapabilities.displayModes&&!this.hostCapabilities.displayModes.includes(mode)){throw new ExtAppsNotSupportedError(`Display mode '${mode}' not advertised by host`)}if(!this.context.setDisplayMode){throw new ExtAppsNotSupportedError("Display mode change not supported by host")}this.logger.verbose(`handleSetDisplayMode: mode=${escapeControlCharacters5(mode)}`);await this.context.setDisplayMode(mode);return{mode}}async handleClose(params){if(!this.context.close){throw new ExtAppsNotSupportedError("Widget close not supported by host")}const{reason}=params;this.logger.verbose(`handleClose: reason=${escapeControlCharacters5(reason||"none")}`);await this.context.close(reason)}async handleLog(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,message,data}=params;if(!message||typeof message!=="string"){throw new ExtAppsInvalidParamsError("Log message is required")}const validLevels=["debug","info","warn","error"];if(level&&!validLevels.includes(level)){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${validLevels.join(", ")}`)}this.writeWidgetLog(level??"info",message,data)}async handleLogMessage(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,logger,data}=params;const serverLevel=Object.hasOwn(MCP_LOG_LEVELS,level)?MCP_LOG_LEVELS[level]:void 0;if(!serverLevel){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${Object.keys(MCP_LOG_LEVELS).join(", ")}`)}if(typeof data==="string"){this.writeWidgetLog(serverLevel,data,void 0)}else{this.writeWidgetLog(serverLevel,logger??"widget log",data)}}writeWidgetLog(level,text,data){const widgetLogger=this.logger.child(`Widget:${this.context.sessionId}`);const message=escapeControlCharacters5(text);switch(level){case"debug":widgetLogger.verbose(message,data);break;case"info":widgetLogger.info(message,data);break;case"warn":widgetLogger.warn(message,data);break;case"error":widgetLogger.error(message,data);break;default:widgetLogger.info(message,data)}}async handleRegisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.registerTool){throw new ExtAppsNotSupportedError("Widget tool registration not supported by host")}const{name:name59,description,inputSchema:inputSchema53}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}if(!description||typeof description!=="string"){throw new ExtAppsInvalidParamsError("Tool description is required")}if(!inputSchema53||typeof inputSchema53!=="object"||Array.isArray(inputSchema53)){throw new ExtAppsInvalidParamsError("Tool input schema must be a non-null object")}this.logger.verbose(`handleRegisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.registerTool(name59,description,inputSchema53)}async handleUnregisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.unregisterTool){throw new ExtAppsNotSupportedError("Widget tool unregistration not supported by host")}const{name:name59}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleUnregisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.unregisterTool(name59)}widgetMessageOf(error){if(error instanceof ExtAppsError||isDevelopment5())return error instanceof Error?error.message:String(error);return toMcpError(error).getPublicMessage()}getErrorCode(error){if(error instanceof ExtAppsMethodNotFoundError){return EXT_APPS_ERROR_CODES.METHOD_NOT_FOUND}if(error instanceof ExtAppsInvalidParamsError){return EXT_APPS_ERROR_CODES.INVALID_PARAMS}if(error instanceof ExtAppsNotSupportedError){return EXT_APPS_ERROR_CODES.NOT_SUPPORTED}if(error instanceof ExtAppsToolNotFoundError){return EXT_APPS_ERROR_CODES.TOOL_NOT_FOUND}return EXT_APPS_ERROR_CODES.INTERNAL_ERROR}};ExtAppsError=class extends Error{constructor(message){super(message);this.name="ExtAppsError"}};ExtAppsMethodNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsMethodNotFoundError"}};ExtAppsInvalidParamsError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsInvalidParamsError"}};ExtAppsNotSupportedError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsNotSupportedError"}};ExtAppsToolNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsToolNotFoundError"}}}});var init_ext_apps2=__esm({"libs/sdk/src/ext-apps/index.ts"(){"use strict";init_ext_apps_types();init_ext_apps_handler()}});import{internalZ as z116}from"@frontmcp/lazy-zod";import{CallToolResultSchema as CallToolResultSchema4,ElicitResultSchema as ElicitResultSchema3,RequestSchema as RequestSchema2}from"@frontmcp/protocol";function resolveStreamableHttpSession(params){const{rawHeader,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(mcpSessionHeader){if(authorizationSession?.id===mcpSessionHeader){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}function classifyStreamableHttpRequest(params){const{method,body}=params;if(method.toUpperCase()==="GET"){return{requestType:"sseListener"}}const jsonRpcMethod=body?.method;if(jsonRpcMethod==="initialize"){return{requestType:"initialize"}}if(typeof jsonRpcMethod==="string"&&(jsonRpcMethod.startsWith("ui/")||jsonRpcMethod==="notifications/message")){return{requestType:"extApps"}}if(ElicitResultSchema3.safeParse(body?.result).success){return{requestType:"elicitResult"}}if(jsonRpcMethod&&RequestSchema2.safeParse(body).success){return{requestType:"message"}}return{error:"Invalid Request"}}function syncStreamableHttpAuthorizationSession(authorization,session){if(!authorization.session){authorization.session=session}}function resetInitializedTransportForReinit(transport){if(!transport.isInitialized){return true}transport.resetForReinitialization();transport.reregisterServer();return!transport.isInitialized}function buildReinitFailedResponse(sessionId,requestId){return httpRespond.rpcError(`Could not re-initialize session "${sessionId}". It is stuck in an initialized state \u2014 terminate it with an HTTP DELETE to the MCP endpoint (including the mcp-session-id header), or reconnect without the stored mcp-session-id to start a fresh session.`,requestId)}async function lookupStreamableHttpTransport(params){const{transportService,token,sessionId,response}=params;const inMemoryTransport=await transportService.getTransporter("streamable-http",token,sessionId);if(inMemoryTransport){return{kind:"transport",source:"memory",transport:inMemoryTransport}}let recreationError;try{const storedSession=await transportService.getStoredSession("streamable-http",token,sessionId);if(storedSession){const recreatedTransport=await transportService.recreateTransporter("streamable-http",token,sessionId,storedSession,response);if(recreatedTransport){return{kind:"transport",source:"redis",transport:recreatedTransport}}}}catch(error){recreationError=error}const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,sessionId);if(wasCreated){return{kind:"session-expired",recreationError}}return{kind:"session-not-initialized",recreationError}}function sessionIdForLog(sessionId){return typeof sessionId==="string"?sessionId.slice(0,20):void 0}function errorMessageForLog(error,sessionId){const message=error instanceof Error?error.message:String(error);return sessionId?message.replaceAll(sessionId,`${sessionIdForLog(sessionId)}...`):message}var plan27,stateSessionSchema2,stateSchema24,name27,Stage27,HandleStreamableHttpFlow;var init_handle_streamable_http_flow=__esm({"libs/sdk/src/transport/flows/handle.streamable-http.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ext_apps2();init_ha_headers();init_skill_mode_utils();init_mcp_surface();plan27={pre:["applyNodeHeaders","parseInput","router"],execute:["onInitialize","onMessage","onElicitResult","onSseListener","onExtApps"],post:[],finalize:["cleanup"]};stateSessionSchema2=z116.object({id:z116.string(),payload:z116.object({nodeId:z116.string(),authSig:z116.string(),uuid:z116.string().uuid(),iat:z116.number(),protocol:z116.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z116.boolean().optional(),platformType:z116.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema24=z116.object({token:z116.string(),session:stateSessionSchema2,requestType:z116.enum(["initialize","message","elicitResult","sseListener","extApps"]).optional()});name27="handle:streamable-http";({Stage:Stage27}=FlowHooksOf(name27));HandleStreamableHttpFlow=class extends FlowBase{name=name27;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const logger=this.scopeLogger.child("handle:streamable-http:parseInput");const body=request2.body;const isInitialize2=body?.method==="initialize";const createSession=()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("streamable-http",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})};let sessionResolution;if(isInitialize2){if(authorization.session?.id){sessionResolution={session:authorization.session,createdNew:false,responded404:false}}else{sessionResolution={session:createSession(),createdNew:true,responded404:false}}}else{sessionResolution=resolveStreamableHttpSession({rawHeader:request2.headers?.["mcp-session-id"],authorizationSession:authorization.session,createSession})}if(sessionResolution.responded404||!sessionResolution.session){logger.warn("parseInput: mcp-session-id is not a session this server verified");this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=sessionResolution.session;this.state.set(stateSchema24.parse({token,session}));logger.verbose("parseInput: session resolved",{sessionId:session.id?.slice(0,20)})}async router(){const{request:request2}=this.rawInput;const logger=this.scopeLogger.child("handle:streamable-http:router");const classification=classifyStreamableHttpRequest({method:request2.method,body:request2.body});if("error"in classification){logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"));return}this.state.set("requestType",classification.requestType);if(classification.requestType==="sseListener"){logger.verbose("router: requestType=sseListener, method=GET")}else if(classification.requestType==="initialize"){logger.verbose("router: requestType=initialize, method=POST")}else if(classification.requestType==="extApps"){const method=request2.body?.method;logger.verbose(`router: requestType=extApps, method=${method}`)}else if(classification.requestType==="elicitResult"){logger.verbose("router: requestType=elicitResult, method=POST")}else{const method=request2.body?.method;logger.verbose(`router: requestType=message, method=${method}`)}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("handle:streamable-http:onInitialize");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.info("onInitialize: creating transport",{sessionId:session.id?.slice(0,20),hasToken:!!token,tokenPrefix:token?.slice(0,10)});try{const authorization=request2[ServerRequestTokens.auth];syncStreamableHttpAuthorizationSession(authorization,session);const transport=await transportService.createTransporter("streamable-http",token,session.id,response);const isReinitialize=!!request2[ServerRequestTokens.reinitialize];if(transport.isInitialized){logger.info("onInitialize: transport already initialized, resetting for re-initialization",{sessionId:session.id?.slice(0,20),reinitialize:isReinitialize});if(!resetInitializedTransportForReinit(transport)){const requestId=request2.body?.id??null;logger.error("onInitialize: transport still initialized after reset \u2014 cannot re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(buildReinitFailedResponse(session.id,requestId));return}}applyNodeAffinity(response,request2);logger.info("onInitialize: transport created, calling initialize");await transport.initialize(request2,response);logger.info("onInitialize: completed successfully");this.handled()}catch(error){if(error instanceof FlowControl){throw error}logger.error("onInitialize: failed",{error:error instanceof Error?error.message:String(error),stack:error instanceof Error?error.stack:void 0});throw error}}async onElicitResult(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onElicitResult");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onElicitResult: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onElicitResult: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onElicitResult: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onElicitResult: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onElicitResult: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session not found"));return}await transport.handleRequest(request2,response);if(!response.writableEnded){response.status(202).json({jsonrpc:"2.0",result:{}})}this.handled()}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onMessage: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});const transportLookup=await lookupStreamableHttpTransport({transportService,token,sessionId:session.id,response});if(transportLookup.kind!=="transport"){const body=request2.body;if(transportLookup.recreationError){logger.warn("Failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(transportLookup.recreationError,session.id)})}if(transportLookup.kind==="session-expired"){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"])});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"]),userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const transport=transportLookup.transport;logger.verbose("onMessage: transport resolved",{source:transportLookup.source});try{await transport.handleRequest(request2,response);this.handled()}catch(error){if(!(error instanceof FlowControl)){const body=request2.body;logger.error("handleRequest failed",{error:error instanceof Error?{name:error.name,message:error.message,stack:error.stack}:error,method:body?.["method"],id:body?.["id"],sessionId:session.id?.slice(0,20)})}throw error}}async onSseListener(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onSseListener");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.info("Recreating transport from Redis session for SSE listener",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("Failed to recreate transport from stored session for SSE listener",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onSseListener: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.notFound("Session not found"));return}await transport.handleRequest(request2,response);this.handled()}async onExtApps(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onExtApps");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const message=request2.body;const isNotification=!("id"in message);if(this.scope.metadata.extApps?.enabled===false){const rpc=request2.body;logger.verbose("onExtApps: ext-apps disabled by config",{method:rpc?.method});if(isNotification){response.status(202).end();this.handled();return}response.status(200).json({jsonrpc:"2.0",id:rpc?.id??null,error:{code:-32601,message:`Method not found: ${rpc?.method}`}});this.handled();return}logger.verbose("onExtApps: starting",{sessionId:session.id?.slice(0,20),method:request2.body?.method});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onExtApps: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onExtApps: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onExtApps: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,session.id);if(wasCreated){logger.info("onExtApps: session expired - client should re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("onExtApps: session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const configuredCapabilities=this.scope.metadata.extApps?.hostCapabilities;const hostCapabilities={serverToolProxy:configuredCapabilities?.serverToolProxy??true,logging:configuredCapabilities?.logging??true,...configuredCapabilities,openLink:false,modelContextUpdate:false,widgetTools:false};const unsupported=["openLink","modelContextUpdate","widgetTools"].filter(key=>configuredCapabilities?.[key]===true);if(unsupported.length>0){logger.warn(`onExtApps: extApps.hostCapabilities ${unsupported.join(", ")} are not supported yet and are not advertised`)}const{user,scopes,claims:claims3}=request2[ServerRequestTokens.auth];const handler=createExtAppsMessageHandler({context:{sessionId:session.id,logger:this.scope.logger,callTool:async(name59,args)=>{const result=await this.scope.runFlow("tools:call-tool",{request:{method:"tools/call",params:{name:name59,arguments:args}},ctx:{authInfo:{sessionId:session.id,sessionIdPayload:session.payload,token,user,scopes:Array.isArray(scopes)?[...scopes]:[],...claims3?{claims:structuredClone(claims3)}:{},clientId:user?.sub??""},surface:mcpRequestSurface(this.scope),_skipUI:true}});const parsed=CallToolResultSchema4.safeParse(result);if(parsed.success){return parsed.data}throw new InternalMcpError("Tool call returned invalid result format")}},hostCapabilities});if(isNotification){await handler.handleNotification(message);response.status(202).end();this.handled();return}const jsonRpcResponse=await handler.handleRequest(message);response.status(200).json(jsonRpcResponse);this.handled()}};__decorateClass([Stage27("applyNodeHeaders")],HandleStreamableHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage27("parseInput")],HandleStreamableHttpFlow.prototype,"parseInput",1);__decorateClass([Stage27("router")],HandleStreamableHttpFlow.prototype,"router",1);__decorateClass([Stage27("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleStreamableHttpFlow.prototype,"onInitialize",1);__decorateClass([Stage27("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleStreamableHttpFlow.prototype,"onElicitResult",1);__decorateClass([Stage27("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleStreamableHttpFlow.prototype,"onMessage",1);__decorateClass([Stage27("onSseListener",{filter:({state:{requestType}})=>requestType==="sseListener"})],HandleStreamableHttpFlow.prototype,"onSseListener",1);__decorateClass([Stage27("onExtApps",{filter:({state:{requestType}})=>requestType==="extApps"})],HandleStreamableHttpFlow.prototype,"onExtApps",1);HandleStreamableHttpFlow=__decorateClass([FrontMcpFlow({name:name27,plan:plan27,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStreamableHttpFlow)}});import{base64Decode as base64Decode4,base64Encode as base64Encode3}from"@frontmcp/utils";function normalizeRequestHeaders(headers){const out={};if(!headers)return out;for(const[name59,value]of Object.entries(headers)){if(typeof value==="string")out[name59.toLowerCase()]=value;else if(Array.isArray(value))out[name59.toLowerCase()]=value.map(String);else if(typeof value==="number")out[name59.toLowerCase()]=String(value)}return out}function serializeRelayRequest(request2){const raw=request2;const url=typeof raw.originalUrl==="string"&&raw.originalUrl?raw.originalUrl:raw.url??"/";const queryIndex=url.indexOf("?");const path4=typeof raw.path==="string"&&raw.path?raw.path:queryIndex>=0?url.slice(0,queryIndex):url;return{method:(raw.method??"GET").toUpperCase(),url,path:path4,headers:normalizeRequestHeaders(raw.headers),query:raw.query&&typeof raw.query==="object"?{...raw.query}:{},...raw.body!==void 0?{body:raw.body}:{},...typeof raw.protocol==="string"?{protocol:raw.protocol}:{},...raw.socket?.encrypted?{encrypted:true}:{},...typeof raw.socket?.remoteAddress==="string"?{peerAddress:raw.socket.remoteAddress}:{}}}function relayedFrom(request2){const value=request2[ServerRequestTokens.relayedFrom];return typeof value==="string"?value:void 0}function isRelayedRequest(request2){return relayedFrom(request2)!==void 0}function createRelayedServerRequest(relayed,sourceNodeId){const headers=normalizeRequestHeaders(relayed.headers);const rawHeaders=[];for(const[name59,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])rawHeaders.push(name59,item)}const socket={remoteAddress:relayed.peerAddress,encrypted:relayed.encrypted===true,destroyed:false,destroy(){socket.destroyed=true},destroySoon(){socket.destroyed=true}};const request2=Object.assign(new RelayEmitter,{method:relayed.method,url:relayed.url,originalUrl:relayed.url,path:relayed.path,headers,rawHeaders,query:relayed.query??{},body:relayed.body,protocol:relayed.protocol??(socket.encrypted?"https":"http"),secure:(relayed.protocol??(socket.encrypted?"https":"http"))==="https",httpVersion:"1.1",httpVersionMajor:1,httpVersionMinor:1,complete:true,readable:false,readableEnded:false,aborted:false,errored:null,destroyed:false,socket,connection:socket,resume(){if(!request2.readableEnded){request2.readableEnded=true;queueMicrotask(()=>request2.emit("end"))}return request2},pause(){return request2},destroy(){request2.destroyed=true}});if(relayed.body!==void 0&&typeof Buffer!=="undefined"){const text=typeof relayed.body==="string"?relayed.body:JSON.stringify(relayed.body);Object.assign(request2,{rawBody:Buffer.from(text)})}request2[ServerRequestTokens.relayedFrom]=sourceNodeId;return request2}function encodeBytes(bytes){if(bytes.byteLength===0)return void 0;try{return{data:utf8Decoder.decode(bytes),encoding:"utf8"}}catch{return{data:base64Encode3(bytes),encoding:"base64"}}}function encodeRelayChunk(chunk,encoding){if(chunk===void 0||chunk===null)return void 0;if(typeof chunk==="string"){if(chunk.length===0)return void 0;if(encoding==="base64")return{data:chunk,encoding:"base64"};return{data:chunk,encoding:"utf8"}}if(chunk instanceof Uint8Array)return encodeBytes(chunk);if(chunk instanceof ArrayBuffer)return encodeBytes(new Uint8Array(chunk));const text=String(chunk);return text.length>0?{data:text,encoding:"utf8"}:void 0}function decodeRelayChunk(chunk){return chunk.encoding==="base64"?base64Decode4(chunk.data):chunk.data}function isFlatHeaderList(headers){return Array.isArray(headers)}var RelayEmitter,utf8Decoder,HOP_BY_HOP_HEADERS2,RelayServerResponse;var init_relay_http=__esm({"libs/sdk/src/transport/relay/relay-http.ts"(){"use strict";init_common();init_http_location_utils();RelayEmitter=class{listeners=new Map;on(event,listener){const list=this.listeners.get(event)??[];list.push(listener);this.listeners.set(event,list);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapper=(...args)=>{this.off(event,wrapper);listener(...args)};wrapper.listener=listener;return this.on(event,wrapper)}off(event,listener){const list=this.listeners.get(event);if(!list)return this;const index=list.findIndex(l=>l===listener||l.listener===listener);if(index>=0)list.splice(index,1);if(list.length===0)this.listeners.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listeners.clear();else this.listeners.delete(event);return this}listenerCount(event){return this.listeners.get(event)?.length??0}emit(event,...args){const list=this.listeners.get(event);if(!list||list.length===0)return false;for(const listener of[...list])listener(...args);return true}};utf8Decoder=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});HOP_BY_HOP_HEADERS2=new Set(["connection","keep-alive","transfer-encoding","upgrade"]);RelayServerResponse=class extends RelayEmitter{constructor(sink){super();this.sink=sink}sink;statusCode=200;statusMessage="";headersSent=false;writableEnded=false;writableFinished=false;destroyed=false;headerMap=new Map;get writable(){return!this.writableEnded&&!this.destroyed}get finished(){return this.writableEnded}setHeader(name59,value){if(this.headersSent)return this;this.headerMap.set(name59.toLowerCase(),Array.isArray(value)?value.map(String):String(value));return this}getHeader(name59){return this.headerMap.get(name59.toLowerCase())}getHeaders(){return Object.fromEntries(this.headerMap)}getHeaderNames(){return[...this.headerMap.keys()]}hasHeader(name59){return this.headerMap.has(name59.toLowerCase())}removeHeader(name59){if(!this.headersSent)this.headerMap.delete(name59.toLowerCase())}writeHead(statusCode,reasonOrHeaders,maybeHeaders){if(this.headersSent)return this;this.statusCode=statusCode;let headers;if(typeof reasonOrHeaders==="string"){this.statusMessage=reasonOrHeaders;headers=maybeHeaders}else{headers=reasonOrHeaders}if(isFlatHeaderList(headers)){for(let i=0;i+1<headers.length;i+=2)this.setHeader(headers[i],headers[i+1])}else if(headers){for(const[name59,value]of Object.entries(headers)){if(value!==void 0)this.setHeader(name59,value)}}this.sendHead();return this}flushHeaders(){this.sendHead()}status(code){this.statusCode=code;return this}json(body){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/json; charset=utf-8");return this.end(JSON.stringify(body))}send(body){if(body===void 0||body===null)return this.end();if(typeof body==="string"){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","text/html; charset=utf-8");return this.end(body)}if(body instanceof Uint8Array){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/octet-stream");return this.end(body)}return this.json(body)}redirect(statusOrUrl,maybeUrl){const status=typeof statusOrUrl==="number"?statusOrUrl:302;const location=typeof statusOrUrl==="string"?statusOrUrl:maybeUrl??"/";this.statusCode=status;this.setHeader("Location",toLocationHeader(location));return this.end()}write(chunk,encodingOrCallback,callback){const cb=typeof encodingOrCallback==="function"?encodingOrCallback:callback;if(!this.writable)return false;this.sendHead();const encoded=encodeRelayChunk(chunk,typeof encodingOrCallback==="string"?encodingOrCallback:void 0);if(encoded)this.sink.data(encoded);if(typeof cb==="function")cb();return true}end(chunk,encodingOrCallback,callback){let data=chunk;let encoding=encodingOrCallback;let cb=callback;if(typeof data==="function"){cb=data;data=void 0;encoding=void 0}else if(typeof encoding==="function"){cb=encoding;encoding=void 0}if(this.writableEnded||this.destroyed){if(typeof cb==="function")cb();return this}this.sendHead();const encoded=encodeRelayChunk(data,typeof encoding==="string"?encoding:void 0);if(encoded)this.sink.data(encoded);this.writableEnded=true;this.sink.end();this.writableFinished=true;this.emit("finish");this.emit("close");if(typeof cb==="function")cb();return this}destroy(error){if(this.destroyed)return this;this.destroyed=true;if(error&&this.listenerCount("error")>0)this.emit("error",error);if(!this.writableFinished)this.emit("close");return this}cork(){}uncork(){}setTimeout(){return this}asServerResponse(){return this}sendHead(){if(this.headersSent||this.destroyed)return;this.headersSent=true;const headers={};for(const[name59,value]of this.headerMap){if(!HOP_BY_HOP_HEADERS2.has(name59))headers[name59]=value}this.sink.head(this.statusCode,headers)}}}});var LocalTransporter;var init_transport_local=__esm({"libs/sdk/src/transport/transport.local.ts"(){"use strict";init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_transport_error();LocalTransporter=class{constructor(scope,key,res,onDispose){this.onDispose=onDispose;this.type=key.type;this.tokenHash=key.tokenHash;const defaultOnDispose=()=>{};switch(this.type){case"sse":this.adapter=new TransportSSEAdapter(scope,key,onDispose??defaultOnDispose,res);break;case"streamable-http":case"stateless-http":this.adapter=new TransportStreamableHttpAdapter(scope,key,onDispose??defaultOnDispose,res);break;default:throw new UnsupportedTransportTypeError(this.type)}}onDispose;type;tokenHash;sessionId;adapter;ping(timeoutMs){throw new MethodNotImplementedError("LocalTransporter","ping")}async handleRequest(req,res){try{await this.adapter.handleRequest(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}async ready(){return this.adapter.ready}async initialize(req,res){try{await this.adapter.ready;return this.adapter.initialize(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}get isInitialized(){return this.adapter.isInitialized}markAsInitialized(){this.adapter.markAsInitialized()}resetForReinitialization(){this.adapter.resetForReinitialization()}reregisterServer(){this.adapter.reregisterServer()}async destroy(reason){try{await this.adapter.destroy(reason)}finally{this.onDispose?.()}}}}});var RemoteTransporter;var init_transport_remote=__esm({"libs/sdk/src/transport/transport.remote.ts"(){"use strict";init_transport_errors();init_transport_error();RemoteTransporter=class{constructor(key,bus,location){this.key=key;this.bus=bus;this.location=location;this.type=key.type;this.tokenHash=key.tokenHash;this.sessionId=key.sessionId}key;bus;location;type;tokenHash;sessionId;get ownerNodeId(){return this.location.nodeId}ping(_timeoutMs){throw new MethodNotImplementedError("RemoteTransporter","ping")}initialize(req,res){return this.relay(req,res)}handleRequest(req,res){return this.relay(req,res)}async destroy(reason){await this.bus.destroyRemote(this.key,reason)}get isInitialized(){return true}markAsInitialized(){}resetForReinitialization(){}reregisterServer(){}async relay(req,res){try{await this.bus.proxyRequest(this.location,this.sessionId,req,res)}catch(error){if(!(error instanceof SessionOwnerUnreachableError)||res.headersSent)throw error;const requestId=req.body?.id??null;res.setHeader("Retry-After",String(error.retryAfterSeconds));res.status(error.statusCode).json(rpcError(error.getPublicMessage(),requestId))}}}}});import{getMachineId as getMachineId4,sha256Hex as sha256Hex20}from"@frontmcp/utils";var SESSION_STORE_RETRY_BASE_MS,SESSION_STORE_RETRY_MAX_MS,DEFAULT_SESSION_CHECK_TIMEOUT_MS,BUS_REFRESH_INTERVAL_MS,MAX_ROUTABLE_SESSION_ID_LENGTH,RELAYABLE_TYPES,TransportService;var init_transport_registry=__esm({"libs/sdk/src/transport/transport.registry.ts"(){"use strict";init_session_store_factory();init_session_id_utils();init_auth_info_utils();init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_handle_mcp_20260728_flow();init_handle_sse_flow();init_handle_stateless_http_flow();init_handle_streamable_http_flow();init_relay_http();init_transport_local();init_transport_remote();init_transport_types();SESSION_STORE_RETRY_BASE_MS=1e3;SESSION_STORE_RETRY_MAX_MS=3e4;DEFAULT_SESSION_CHECK_TIMEOUT_MS=500;BUS_REFRESH_INTERVAL_MS=15*60*1e3;MAX_ROUTABLE_SESSION_ID_LENGTH=4096;RELAYABLE_TYPES=new Set(["streamable-http","sse"]);TransportService=class{ready;byType=new Map;distributed;bus;scope;sessionHistory=new Map;MAX_SESSION_HISTORY=1e4;sessionStore;persistenceConfig;pendingStoreConfig;backendKind;transportKeyPrefix="mcp:transport:";sessionStoreConfigured=false;creationMutex=new Map;async newLocalTransporter(key,res,onDispose){if(key.type==="streamable-http"||key.type==="stateless-http"){await loadStreamableHttpTransport()}else if(key.type==="sse"){await loadSseTransport()}return new LocalTransporter(this.scope,key,res,onDispose)}getDefaultTtlMs(){if(this.resolvedTtlMs!==void 0)return this.resolvedTtlMs;return typeof this.persistenceConfig==="object"?this.persistenceConfig?.defaultTtlMs:void 0}resolvedTtlMs;storeRetryConfig;storeRetryTimer;storeRetryAttempt=0;destroyed=false;lastTtlRefreshAt=new Map;lastBusRefreshAt=new Map;localSessionIds=new Map;ownershipGeneration=new Map;relinquishing=new Set;storedLocalSessions=new Set;sessionCheckTimeoutMs;pendingSessionChecks=new Map;getSessionKeyPrefix(){return`${this.transportKeyPrefix}session:`}constructor(scope,persistenceConfig,bus){this.scope=scope;this.persistenceConfig=persistenceConfig;this.distributed=!!bus;this.bus=bus;this.sessionCheckTimeoutMs=(persistenceConfig!==false?persistenceConfig?.sessionCheckTimeoutMs:void 0)??DEFAULT_SESSION_CHECK_TIMEOUT_MS;if(persistenceConfig!==false&&persistenceConfig?.sqlite){this.sessionStoreConfigured=true;this.backendKind="sqlite";const sqliteConfig=persistenceConfig.sqlite;this.transportKeyPrefix="mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??36e5;this.pendingStoreConfig={sqlite:sqliteConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info("[TransportService] sqlite session store will be initialized for transport persistence")}else if(persistenceConfig!==false&&persistenceConfig?.redis){this.sessionStoreConfigured=true;const redisConfig=persistenceConfig.redis;const providerType="provider"in redisConfig?redisConfig.provider:"redis";this.backendKind=providerType==="vercel-kv"?"vercel-kv":"redis";this.transportKeyPrefix=redisConfig.keyPrefix??"mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??redisConfig.defaultTtlMs??36e5;this.pendingStoreConfig={...redisConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info(`[TransportService] ${providerType} session store will be initialized for transport persistence`)}this.storeRetryConfig=this.pendingStoreConfig;this.ready=this.initialize()}async initialize(){if(this.pendingStoreConfig){const connected=await this.connectSessionStore();if(!connected&&this.backendKind!=="sqlite")this.scheduleSessionStoreRetry()}await this.scope.registryFlows(HandleStreamableHttpFlow,HandleSseFlow,HandleStatelessHttpFlow,HandleMcp20260728Flow)}async connectSessionStore(){const storeConfig=this.pendingStoreConfig??this.storeRetryConfig;if(!storeConfig)return false;try{const store=await createSessionStore(storeConfig,this.scope.logger.child("SessionStore"));this.sessionStore=store;this.pendingStoreConfig=void 0}catch(error){const err=error;this.scope.logger.error("[TransportService] Failed to create session store - session persistence disabled",{error:err.message,cause:err.cause?.message});return false}const isConnected=this.sessionStore?.ping?await this.sessionStore.ping():true;if(!isConnected){const providerType=this.backendKind??"redis";this.scope.logger.error(`[TransportService] Failed to connect to ${providerType} - session persistence disabled`);await this.teardownSessionStore().catch(()=>void 0);return false}this.scope.logger.info("[TransportService] Session store connection validated successfully");return true}scheduleSessionStoreRetry(){if(this.destroyed||this.storeRetryTimer)return;const delay=Math.min(SESSION_STORE_RETRY_MAX_MS,SESSION_STORE_RETRY_BASE_MS*2**this.storeRetryAttempt);this.storeRetryAttempt++;this.storeRetryTimer=setTimeout(()=>{this.storeRetryTimer=void 0;void this.retrySessionStore()},delay);this.storeRetryTimer.unref?.()}async retrySessionStore(){if(this.destroyed||this.sessionStore)return;const connected=await this.connectSessionStore().catch(()=>false);if(this.destroyed){await this.teardownSessionStore().catch(()=>void 0);return}if(connected){this.storeRetryAttempt=0;this.scope.logger.info("[TransportService] Session store recovered after startup failure");return}this.scheduleSessionStoreRetry()}async destroy(){this.destroyed=true;if(this.storeRetryTimer){clearTimeout(this.storeRetryTimer);this.storeRetryTimer=void 0}this.lastTtlRefreshAt.clear();this.lastBusRefreshAt.clear();this.ownershipGeneration.clear();this.storedLocalSessions.clear();await this.teardownSessionStore()}async teardownSessionStore(){if(!this.sessionStore)return;const teardown=this.sessionStore.disconnect??this.sessionStore.close;if(!teardown){this.sessionStore=void 0;return}try{await Promise.resolve(teardown.call(this.sessionStore));this.scope.logger.info("[TransportService] Session store disconnected",{backendKind:this.backendKind??"unknown"})}catch(error){this.scope.logger.warn("[TransportService] Error disconnecting session store",{error:error.message,backendKind:this.backendKind??"unknown"})}finally{this.sessionStore=void 0}}async pingSessionStore(){if(!this.sessionStoreConfigured)return true;if(!this.sessionStore)return false;if(typeof this.sessionStore.ping==="function"){return this.sessionStore.ping()}return true}isSessionStoreConfigured(){return this.sessionStoreConfigured}getBackendKind(){return this.backendKind}sessionStoreLabel(){switch(this.backendKind){case"sqlite":return"SQLite";case"vercel-kv":return"Vercel KV";case"redis":return"Redis";default:return"the session store"}}refreshStoredSessionTtl(sessionId){const store=this.sessionStore;const ttlMs=this.getDefaultTtlMs();if(!store||!ttlMs||this.backendKind!=="redis"&&this.backendKind!=="vercel-kv")return;const now=Date.now();const last=this.lastTtlRefreshAt.get(sessionId);if(last!==void 0&&now-last<Math.max(1e3,Math.floor(ttlMs/4)))return;this.lastTtlRefreshAt.set(sessionId,now);store.get(sessionId).catch(err=>{this.scope.logger.warn("[TransportService] Failed to refresh session TTL",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getTransporter(type,token,sessionId){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local&&await this.holdsLocalSession(sessionId)){this.refreshStoredSessionTtl(sessionId);this.refreshBusAdvertisement(key);return local}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){if(await this.isNodeAlive(location.nodeId)){return new RemoteTransporter(key,this.bus,location)}this.scope.logger.info("[HA] Session owner is gone \u2014 the session will be taken over",{sessionId:sessionId.slice(0,20),previousNodeId:location.nodeId})}}return void 0}async findRemoteSessionOwner(request2){if(!this.distributed||!this.bus?.canRelay()||isRelayedRequest(request2))return void 0;const sessionId=sessionIdPresentedBy(request2);if(!sessionId||sessionId.length>MAX_ROUTABLE_SESSION_ID_LENGTH)return void 0;if(!isDeploymentSessionId(sessionId))return void 0;try{if(this.localSessionIds.has(sessionId)&&await this.holdsLocalSession(sessionId))return void 0;const owner=await this.lookupSessionOwner(sessionId);if(!owner||owner.nodeId===getMachineId4())return void 0;return await this.isNodeAlive(owner.nodeId)?owner:void 0}catch(error){this.scope.logger.warn("[HA] Could not resolve the session owner \u2014 serving the request here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return void 0}}async lookupSessionOwner(sessionId){if(!this.bus)return void 0;const advertised=await this.bus.lookupOwner(sessionId);if(advertised)return advertised;const stored=this.sessionStore?await this.sessionStore.get(sessionId):null;const nodeId=stored?.session?.nodeId;if(!nodeId)return void 0;return{nodeId,channel:this.bus.channelOf(nodeId)}}async relayToSessionOwner(location,request2,response){if(!this.bus)throw new InvalidTransportSessionError("Session relay requires the distributed transport bus.");const sessionId=sessionIdPresentedBy(request2)??"";await this.bus.proxyRequest(location,sessionId,request2,response)}async adoptClaimedSession(sessionId,previousNodeId,info){if(!this.bus)return;const type=info.protocol;if(!info.authorizationId||type!=="streamable-http"&&type!=="sse")return;await this.bus.advertise({type,token:"",tokenHash:info.authorizationId,sessionId});this.scope.logger.info("[HA] Adopted an orphaned session \u2014 this node now serves it",{sessionId:sessionId.slice(0,20),previousNodeId})}async destroyLocalSession(sessionId,reason){let found=false;for(const[type,typeBucket]of[...this.byType.entries()]){if(!RELAYABLE_TYPES.has(type))continue;for(const tokenBucket of[...typeBucket.values()]){const transporter=tokenBucket.get(sessionId);if(!transporter)continue;found=true;await transporter.destroy(reason)}}return found}async holdsLocalSession(sessionId){if(!this.distributed)return this.isStillStored(sessionId);const haManager=this.scope.haManager;const store=this.sessionStore;if(!haManager||!store)return true;const generation=haManager.livenessGeneration();if(generation!==void 0&&this.ownershipGeneration.get(sessionId)===generation)return true;let ownerNodeId;try{ownerNodeId=(await this.withSessionCheckTimeout(`get:${sessionId}`,()=>store.get(sessionId)))?.session?.nodeId}catch(error){this.scope.logger.warn("[HA] Could not confirm this node still owns the session \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}if(!ownerNodeId||ownerNodeId===getMachineId4()){if(generation!==void 0)this.ownershipGeneration.set(sessionId,generation);return true}this.scope.logger.warn("[HA] Another node took this session over while this node was unreachable \u2014 dropping it here",{sessionId:sessionId.slice(0,20),ownerNodeId});this.relinquishing.add(sessionId);try{await this.destroyLocalSession(sessionId,"the session moved to another node")}finally{this.relinquishing.delete(sessionId)}return false}async isStillStored(sessionId){const store=this.sessionStore;if(!store||!this.storedLocalSessions.has(sessionId))return true;try{if(await this.withSessionCheckTimeout(`exists:${sessionId}`,()=>store.exists(sessionId)))return true}catch(error){this.scope.logger.warn("[TransportService] Could not confirm the session is still stored \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}this.scope.logger.info("[TransportService] The stored session is gone \u2014 dropping its transport here",{sessionId:sessionId.slice(0,20)});await this.destroyLocalSession(sessionId,"the session was deleted");return false}withSessionCheckTimeout(key,issueRead){let read=this.pendingSessionChecks.get(key);if(!read){read=issueRead().finally(()=>this.pendingSessionChecks.delete(key));this.pendingSessionChecks.set(key,read)}const timeoutMs=this.sessionCheckTimeoutMs;let timer;const timedOut=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error(`The session store did not answer within ${timeoutMs} ms`)),timeoutMs);timer.unref?.()});return Promise.race([read,timedOut]).finally(()=>clearTimeout(timer))}async isNodeAlive(nodeId){const haManager=this.scope.haManager;if(!haManager)return true;try{return await haManager.isNodeAlive(nodeId)}catch{return true}}refreshBusAdvertisement(key){if(!this.distributed||!this.bus||!RELAYABLE_TYPES.has(key.type))return;const now=Date.now();const last=this.lastBusRefreshAt.get(key.sessionId);if(last!==void 0&&now-last<BUS_REFRESH_INTERVAL_MS)return;this.lastBusRefreshAt.set(key.sessionId,now);this.bus.advertise(key).catch(err=>{this.scope.logger.warn("[HA] Failed to refresh the session advertisement",{sessionId:key.sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getStoredSession(type,token,sessionId,options){if(!this.sessionStore||type!=="streamable-http"&&type!=="sse")return void 0;const tokenHash=this.sha256(token);const stored=await this.sessionStore.get(sessionId);if(!stored)return void 0;if(stored.authorizationId!==tokenHash){this.scope.logger.warn("[TransportService] Session token mismatch during lookup",{sessionId:sessionId.slice(0,20),storedTokenHash:stored.authorizationId.slice(0,8),requestTokenHash:tokenHash.slice(0,8)});return void 0}if(options?.clientFingerprint&&stored.session.clientFingerprint){if(stored.session.clientFingerprint!==options.clientFingerprint){this.scope.logger.warn("[TransportService] Client fingerprint mismatch",{sessionId:sessionId.slice(0,20),storedFingerprint:stored.session.clientFingerprint.slice(0,8),requestFingerprint:options.clientFingerprint.slice(0,8)});if(!options.warnOnFingerprintMismatch){return void 0}}}return stored}async recreateTransporter(type,token,sessionId,storedSession,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const recreationPromise=this.doRecreateTransporter(key,sessionId,storedSession,res);this.creationMutex.set(mutexKey,recreationPromise);try{return await recreationPromise}catch(error){this.scope.logger.error("[TransportService] Failed to recreate transport from stored session",{sessionId:sessionId.slice(0,20),error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}finally{this.creationMutex.delete(mutexKey)}}async remoteOwnerTransporter(key,ownerNodeId){if(!this.distributed||!this.bus)return void 0;if(!await this.isNodeAlive(ownerNodeId))return void 0;return new RemoteTransporter(key,this.bus,{nodeId:ownerNodeId,channel:this.bus.channelOf(ownerNodeId)})}async doRecreateTransporter(key,sessionId,storedSession,res){const existing=this.lookupLocal(key);if(existing)return existing;this.scope.logger.info("[TransportService] Recreating transport from stored session",{sessionId:sessionId.slice(0,20),protocol:storedSession.session.protocol,createdAt:storedSession.createdAt});const currentNodeId=getMachineId4();const ownerNodeId=storedSession.session.nodeId;let latestSession=storedSession;if(this.scope.haManager&&ownerNodeId&&ownerNodeId!==currentNodeId){const remote=await this.remoteOwnerTransporter(key,ownerNodeId);if(remote)return remote;const sessionKey=`${this.getSessionKeyPrefix()}${sessionId}`;const result=await this.scope.haManager.attemptTakeover(sessionKey,ownerNodeId);if(result.claimed){latestSession={...storedSession,reassignedAt:result.reassignedAt,reassignedFrom:ownerNodeId};this.scope.logger.info("[HA] Took over session from a stopped node",{sessionId:sessionId.slice(0,20),previousNodeId:ownerNodeId})}else{const current=this.sessionStore?await this.sessionStore.get(sessionId):null;const newOwner=current?.session?.nodeId;if(newOwner!==currentNodeId){const relayed=newOwner?await this.remoteOwnerTransporter(key,newOwner):void 0;if(relayed)return relayed;this.scope.logger.debug("[HA] Session already claimed by another pod",{sessionId:sessionId.slice(0,20)});throw new SessionClaimConflictError(sessionId)}if(current)latestSession=current}}const historyKey=this.makeHistoryKey(key.type,key.tokenHash,sessionId);this.sessionHistory.set(historyKey,storedSession.createdAt);const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();if(storedSession.initialized!==false){transporter.markAsInitialized()}this.insertLocal(key,transporter);if(sessionStore)this.storedLocalSessions.add(sessionId);if(storedSession.clientCapabilities){this.scope.notifications.setClientCapabilities(sessionId,storedSession.clientCapabilities);this.scope.logger.verbose("[TransportService] Restored client capabilities from stored session",{sessionId:sessionId.slice(0,20)})}if(sessionStore){const updatedSession={...latestSession,session:{...latestSession.session,nodeId:currentNodeId},lastAccessedAt:Date.now()};sessionStore.set(sessionId,updatedSession,defaultTtlMs).catch(err=>{this.scope.logger.warn(`[TransportService] Failed to update session in ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}async createTransporter(type,token,sessionId,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const creationPromise=this.doCreateTransporter(key,sessionId,res,type);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateTransporter(key,sessionId,res,type){const existing=this.lookupLocal(key);if(existing)return existing;const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();this.insertLocal(key,transporter);if(sessionStore&&(type==="streamable-http"||type==="sse")){const storedSession={session:{id:sessionId,authorizationId:key.tokenHash,protocol:type==="sse"?"sse":"streamable-http",createdAt:Date.now(),nodeId:getMachineId4()},authorizationId:key.tokenHash,createdAt:Date.now(),lastAccessedAt:Date.now(),initialized:true};sessionStore.set(sessionId,storedSession,defaultTtlMs).then(()=>{if(this.localSessionIds.has(sessionId))this.storedLocalSessions.add(sessionId)},err=>{this.scope.logger.warn(`[TransportService] Failed to persist session to ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}onSessionTransportDisposed(key,sessionId,sessionStore){key.sessionId=sessionId;this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}if(sessionStore&&!this.relinquishing.has(sessionId)){sessionStore.delete(sessionId).catch(()=>void 0)}}async destroyTransporter(type,token,sessionId,reason){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local){await local.destroy(reason);return}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){await this.bus.destroyRemote(key,reason);return}}throw new InvalidTransportSessionError("Invalid session: cannot destroy non-existent transporter.")}async deleteStoredSession(sessionId){if(!this.sessionStore)return;try{await this.sessionStore.delete(sessionId)}catch(err){this.scope.logger.warn(`[TransportService] Failed to delete session from ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)});throw err}}async updateStoredSessionCapabilities(sessionId,clientCapabilities){if(!this.sessionStore)return;try{const stored=await this.sessionStore.get(sessionId);if(!stored){this.scope.logger.verbose("[TransportService] Cannot update capabilities: session not found in store",{sessionId:sessionId.slice(0,20)});return}const updatedSession={...stored,clientCapabilities,lastAccessedAt:Date.now()};const defaultTtlMs=this.getDefaultTtlMs();await this.sessionStore.set(sessionId,updatedSession,defaultTtlMs);this.scope.logger.verbose("[TransportService] Persisted client capabilities to session store",{sessionId:sessionId.slice(0,20)})}catch(err){this.scope.logger.warn("[TransportService] Failed to persist client capabilities",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})}}async getOrCreateAnonymousStatelessTransport(type,res){return this.getOrCreateStatelessTransport(this.keyOf(type,"__anonymous__",STATELESS_SESSION_ID),res)}async getOrCreateAuthenticatedStatelessTransport(type,token,res){return this.getOrCreateStatelessTransport(this.keyOf(type,token,STATELESS_SESSION_ID),res)}async getOrCreateStatelessTransport(key,res){const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:key.type,h:key.tokenHash,s:key.sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2)return pendingCreation2;const creationPromise=this.doCreateStatelessTransport(key,res);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateStatelessTransport(key,res){const transporter=await this.newLocalTransporter(key,res,()=>{this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}});await transporter.ready();this.insertLocal(key,transporter);if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}wasSessionCreated(type,token,sessionId){const tokenHash=this.sha256(token);const historyKey=this.makeHistoryKey(type,tokenHash,sessionId);return this.sessionHistory.has(historyKey)}async wasSessionCreatedAsync(type,token,sessionId){if(this.wasSessionCreated(type,token,sessionId)){return true}if(this.sessionStore&&(type==="streamable-http"||type==="sse")){const stored=await this.getStoredSession(type,token,sessionId);return stored!==void 0}return false}sha256(value){return sha256Hex20(value)}makeHistoryKey(type,tokenHash,sessionId){return JSON.stringify({t:type,h:tokenHash,s:sessionId})}parseHistoryKey(key){try{const parsed=JSON.parse(key);if(typeof parsed.t==="string"&&typeof parsed.h==="string"&&typeof parsed.s==="string"){return{type:parsed.t,tokenHash:parsed.h,sessionId:parsed.s}}return void 0}catch{return void 0}}keyOf(type,token,sessionId,sessionIdSse){return{type,token,tokenHash:this.sha256(token),sessionId,sessionIdSse}}ensureTypeBucket(type){let bucket=this.byType.get(type);if(!bucket){bucket=new Map;this.byType.set(type,bucket)}return bucket}ensureTokenBucket(typeBucket,tokenHash){let bucket=typeBucket.get(tokenHash);if(!bucket){bucket=new Map;typeBucket.set(tokenHash,bucket)}return bucket}lookupLocal(key){const typeBucket=this.byType.get(key.type);if(!typeBucket)return void 0;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return void 0;return tokenBucket.get(key.sessionId)}insertLocal(key,t){const typeBucket=this.ensureTypeBucket(key.type);const tokenBucket=this.ensureTokenBucket(typeBucket,key.tokenHash);if(!tokenBucket.has(key.sessionId)){this.localSessionIds.set(key.sessionId,(this.localSessionIds.get(key.sessionId)??0)+1)}tokenBucket.set(key.sessionId,t);const generation=this.distributed?this.scope.haManager?.livenessGeneration():void 0;if(generation!==void 0)this.ownershipGeneration.set(key.sessionId,generation);const historyKey=this.makeHistoryKey(key.type,key.tokenHash,key.sessionId);this.sessionHistory.set(historyKey,Date.now());if(this.sessionHistory.size>this.MAX_SESSION_HISTORY){const entries=[...this.sessionHistory.entries()].sort((a,b)=>a[1]-b[1]);const targetEvictions=Math.ceil(this.MAX_SESSION_HISTORY*.1);let evicted=0;for(const[histKey]of entries){if(evicted>=targetEvictions)break;const parsed=this.parseHistoryKey(histKey);if(!parsed){this.sessionHistory.delete(histKey);evicted++;continue}const{type,tokenHash,sessionId}=parsed;const typeBucket2=this.byType.get(type);const tokenBucket2=typeBucket2?.get(tokenHash);const hasActiveTransport=tokenBucket2?.has(sessionId)??false;if(!hasActiveTransport){this.sessionHistory.delete(histKey);evicted++}}if(evicted<targetEvictions){this.scope.logger.warn("[TransportService] Session history eviction: unable to free target memory",{targetEvictions,actualEvictions:evicted,currentSize:this.sessionHistory.size,maxSize:this.MAX_SESSION_HISTORY})}}}evictLocal(key){this.lastTtlRefreshAt.delete(key.sessionId);this.lastBusRefreshAt.delete(key.sessionId);const typeBucket=this.byType.get(key.type);if(!typeBucket)return;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return;if(tokenBucket.delete(key.sessionId)){const remaining=(this.localSessionIds.get(key.sessionId)??1)-1;if(remaining>0)this.localSessionIds.set(key.sessionId,remaining);else{this.localSessionIds.delete(key.sessionId);this.ownershipGeneration.delete(key.sessionId);this.storedLocalSessions.delete(key.sessionId)}}if(tokenBucket.size===0)typeBucket.delete(key.tokenHash);if(typeBucket.size===0)this.byType.delete(key.type)}}}});function loadStreamableHttpTransportOnStart(scope){const{enableStreamableHttp,enableStatelessHttp,enableStatefulHttp}=toLegacyProtocolFlags(scope.metadata.transport?.protocol);if(!enableStreamableHttp&&!enableStatelessHttp&&!enableStatefulHttp)return;scope.onServerStarted(()=>{setImmediate(()=>{loadStreamableHttpTransport().catch(error=>scope.logger.verbose("Streamable HTTP transport preload failed",{error}))})})}var init_streamable_http_preload=__esm({"libs/sdk/src/transport/streamable-http-preload.ts"(){"use strict";init_schema7();init_transport_streamable_http_adapter()}});function getErrorMessage(err){if(err instanceof Error)return err.message;return String(err)}function createStorageProbe(name59,adapter){return{name:name59,async check(){const start=Date.now();try{const ok=await adapter.ping();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}function createRemoteAppProbe(appId,provider){return{name:`remote:${appId}`,async check(){const result=provider.getHealthStatus(appId);if(!result||result.status==="unknown"&&result.consecutiveFailures===0){return{status:"degraded",details:{state:"unknown"}}}return{status:result.status==="healthy"?"healthy":result.status==="degraded"?"degraded":"unhealthy",latencyMs:result.latencyMs,...result.error?{error:result.error}:{}}}}}function createTransportSessionProbe(provider){return{name:"session-store",async check(){const start=Date.now();try{const ok=await provider.pingSessionStore();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Session store ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}var init_health_probes=__esm({"libs/sdk/src/health/health.probes.ts"(){"use strict"}});import{getRuntimeContext as getRuntimeContext21,sha256Hex as sha256Hex21}from"@frontmcp/utils";var processStartTime,HealthService;var init_health_service=__esm({"libs/sdk/src/health/health.service.ts"(){"use strict";init_health_probes();processStartTime=Date.now();HealthService=class{probeSources=[];config;serverInfo;scopeView;constructor(config,serverInfo){this.config=config;this.serverInfo=serverInfo}registerProbe(probe2){this.probeSources.push(()=>[probe2])}registerProbeSource(source){this.probeSources.push(source)}autoDiscoverProbes(scope){this.scopeView=scope;if(scope.transportService){this.registerProbe(createTransportSessionProbe(scope.transportService))}for(const app of scope.apps.getApps()){if(app.isRemote&&typeof app.getMcpClient==="function"){const client=app.getMcpClient();if(client&&typeof client.getHealthStatus==="function"){this.registerProbe(createRemoteAppProbe(app.id,client))}}}if(scope.haManager?.isStarted()){const ha=scope.haManager;this.registerProbe({name:"ha",check:async()=>{const alive=await ha.isNodeAlive(ha.getNodeId());return{status:alive?"healthy":"unhealthy",details:{nodeId:ha.getNodeId(),heartbeatActive:alive}}}})}this.registerProbeSource(()=>scope.healthProbes??[]);const userProbes=this.config.probes??[];for(const probe2 of userProbes){if(probe2&&typeof probe2.check==="function"&&typeof probe2.name==="string"){this.registerProbe({name:probe2.name,check:()=>probe2.check()})}}}getHealthz(){const ctx=getRuntimeContext21();return{status:"ok",server:{name:this.serverInfo.name??"unknown",version:this.serverInfo.version??"unknown"},runtime:{platform:ctx.platform,runtime:ctx.runtime,deployment:ctx.deployment,env:ctx.env},uptime:(Date.now()-processStartTime)/1e3}}async getReadyz(){const start=Date.now();const timeoutMs=this.config.readyz?.timeoutMs??5e3;const includeDetails=this.resolveIncludeDetails();const results=await Promise.all(this.getProbes().map(async probe2=>{const result=await this.runProbeWithTimeout(probe2,timeoutMs);return{name:probe2.name,result}}));const hasUnhealthy=results.some(r=>r.result.status==="unhealthy");const catalog=this.computeCatalogInfo();const response={status:hasUnhealthy?"not_ready":"ready",totalLatencyMs:Date.now()-start,catalog};if(includeDetails){const probes={};for(const{name:name59,result}of results){probes[name59]=result}response.probes=probes}return response}getProbeCount(){return this.getProbes().length}getProbes(){return this.probeSources.flatMap(source=>source())}setScopeView(scope){this.scopeView=scope}async runProbeWithTimeout(probe2,timeoutMs){let timeoutId;try{const timeoutPromise=new Promise(resolve4=>{timeoutId=setTimeout(()=>resolve4({status:"unhealthy",latencyMs:timeoutMs,error:`Probe timed out after ${timeoutMs}ms`}),timeoutMs)});return await Promise.race([probe2.check(),timeoutPromise])}catch(err){return{status:"unhealthy",error:err instanceof Error?err.message:String(err)}}finally{if(timeoutId!==void 0){clearTimeout(timeoutId)}}}computeCatalogInfo(){if(!this.scopeView){return{toolsHash:"",toolCount:0,resourceCount:0,promptCount:0,skillCount:0,agentCount:0}}const tools=this.scopeView.tools.getTools(true);const toolNames=tools.map(t=>t.name).sort();const toolsHash=sha256Hex21(toolNames.join(","));return{toolsHash,toolCount:tools.length,resourceCount:this.scopeView.resources.getResources(true).length,promptCount:this.scopeView.prompts.getPrompts(true).length,skillCount:this.scopeView.skills.getSkills(true).length,agentCount:this.scopeView.agents.getAgents().length}}resolveIncludeDetails(){if(this.config.includeDetails!==void 0){return this.config.includeDetails}const ctx=getRuntimeContext21();return ctx.env!=="production"}}}});var health_exports={};__export(health_exports,{HealthService:()=>HealthService,createRemoteAppProbe:()=>createRemoteAppProbe,createStorageProbe:()=>createStorageProbe,createTransportSessionProbe:()=>createTransportSessionProbe,isReadyzEnabled:()=>isReadyzEnabled,registerHealthRoutes:()=>registerHealthRoutes,servedHealthPaths:()=>servedHealthPaths});var init_health2=__esm({"libs/sdk/src/health/index.ts"(){"use strict";init_health_probes();init_health_service();init_health_routes()}});var http_scope_helper_exports={};__export(http_scope_helper_exports,{HealthService:()=>HealthService,HttpIpFilterFlow:()=>HttpIpFilterFlow,HttpRequestFlow:()=>HttpRequestFlow,HttpRouteFlow:()=>HttpRouteFlow,TransportService:()=>TransportService,attachHttpRoutes:()=>attachHttpRoutes,loadStreamableHttpTransportOnStart:()=>loadStreamableHttpTransportOnStart,registerCustomHttpRoutes:()=>registerCustomHttpRoutes,servedHealthPaths:()=>servedHealthPaths});var init_http_scope_helper=__esm({"libs/sdk/src/scope/http-scope.helper.ts"(){"use strict";init_http_route_flow();init_http_route_table();init_http_request_flow();init_http_ip_filter_flow();init_transport_registry();init_streamable_http_preload();init_custom_routes_helper();init_health2()}});var DEFAULT_HA_CONFIG;var init_ha_types=__esm({"libs/sdk/src/ha/ha.types.ts"(){"use strict";init_ha_constants();DEFAULT_HA_CONFIG={heartbeatIntervalMs:1e4,heartbeatTtlMs:3e4,takeoverGracePeriodMs:5e3,redisKeyPrefix:"mcp:ha:",affinityCookieName:DEFAULT_FRONTMCP_NODE_COOKIE,machineIdHeader:DEFAULT_FRONTMCP_MACHINE_ID_HEADER}}});var HeartbeatService;var init_heartbeat_service=__esm({"libs/sdk/src/ha/heartbeat.service.ts"(){"use strict";init_ha_types();HeartbeatService=class{constructor(redis,nodeId,config){this.redis=redis;this.nodeId=nodeId;this.startedAt=Date.now();this.lastBeatAt=this.startedAt;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.intervalMs=config?.heartbeatIntervalMs??DEFAULT_HA_CONFIG.heartbeatIntervalMs;this.ttlMs=config?.heartbeatTtlMs??DEFAULT_HA_CONFIG.heartbeatTtlMs}redis;nodeId;timer;startedAt;keyPrefix;intervalMs;ttlMs;sessionCount=0;lastBeatAt;lapses=0;start(){if(this.timer)return;this.writeHeartbeat();this.timer=setInterval(()=>this.writeHeartbeat(),this.intervalMs);if(this.timer.unref)this.timer.unref()}async stop(){if(this.timer){clearInterval(this.timer);this.timer=void 0}try{await this.redis.del(this.heartbeatKey())}catch{}}setSessionCount(count){this.sessionCount=count}async isAlive(nodeId){const exists=await this.redis.exists(`${this.keyPrefix}heartbeat:${nodeId}`);return exists===1}async getHeartbeat(nodeId){const raw=await this.redis.get(`${this.keyPrefix}heartbeat:${nodeId}`);if(!raw)return null;try{return JSON.parse(raw)}catch{return null}}livenessGeneration(){return Date.now()-this.lastBeatAt>=this.ttlMs?void 0:this.lapses}async getAliveNodes(){const keys=await this.redis.keys(`${this.keyPrefix}heartbeat:*`);return keys.map(key=>key.slice(`${this.keyPrefix}heartbeat:`.length))}heartbeatKey(){return`${this.keyPrefix}heartbeat:${this.nodeId}`}writeHeartbeat(){const value={nodeId:this.nodeId,startedAt:this.startedAt,lastBeat:Date.now(),sessionCount:this.sessionCount};this.redis.set(this.heartbeatKey(),JSON.stringify(value),"PX",this.ttlMs).then(()=>this.recordBeat(value.lastBeat),()=>void 0)}recordBeat(writtenAt){if(Date.now()-this.lastBeatAt>=this.ttlMs)this.lapses++;this.lastBeatAt=Math.max(this.lastBeatAt,writtenAt)}}}});var NotificationRelay;var init_notification_relay=__esm({"libs/sdk/src/ha/notification-relay.ts"(){"use strict";init_ha_types();NotificationRelay=class{constructor(subscriber,publisher,nodeId,config){this.subscriber=subscriber;this.publisher=publisher;this.nodeId=nodeId;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.channel=this.channelOf(nodeId)}subscriber;publisher;nodeId;handler;channel;keyPrefix;channelOf(nodeId){return`${this.keyPrefix}notify:${nodeId}`}async subscribe(handler){this.handler=handler;this.subscriber.removeListener("message",this.onMessage);this.subscriber.on("message",this.onMessage);await this.subscriber.subscribe(this.channel)}async unsubscribe(){this.handler=void 0;this.subscriber.removeListener("message",this.onMessage);try{await this.subscriber.unsubscribe(this.channel)}catch{}}async publish(targetNodeId,sessionId,notification){await this.send(targetNodeId,{kind:"notification",sessionId,notification,sourceNodeId:this.nodeId,timestamp:Date.now()})}async send(targetNodeId,message){return this.publisher.publish(this.channelOf(targetNodeId),JSON.stringify(message))}onMessage=(channel2,raw)=>{if(!this.handler||channel2!==this.channel)return;let message;try{message=JSON.parse(raw)}catch{return}if(!message||typeof message!=="object")return;try{Promise.resolve(this.handler(message)).catch(()=>void 0)}catch{}}}}});async function attemptSessionTakeover(redis,sessionKey,expectedOldNodeId,newNodeId){const reassignedAt=Date.now();const result=await redis.eval(TAKEOVER_LUA,1,sessionKey,expectedOldNodeId,newNodeId,reassignedAt.toString());const claimed=result===1;return{claimed,sessionId:sessionKey,previousNodeId:claimed?expectedOldNodeId:void 0,reassignedAt:claimed?reassignedAt:void 0}}var TAKEOVER_LUA;var init_session_takeover=__esm({"libs/sdk/src/ha/session-takeover.ts"(){"use strict";TAKEOVER_LUA=`
|
package/index.js
CHANGED
|
@@ -288,7 +288,7 @@ data: ${relativeUrlWithSession}
|
|
|
288
288
|
event: message
|
|
289
289
|
data: ${JSON.stringify(message)}
|
|
290
290
|
|
|
291
|
-
`)}get sessionId(){return this._sessionId}get lastEventId(){return this._eventIdCounter}setEventIdCounter(eventId){this._eventIdCounter=eventId}}}});var node_sse_transport_exports={};__export(node_sse_transport_exports,{SSEServerTransport:()=>SSEServerTransport});var init_node_sse_transport=__esm({"libs/sdk/src/transport/adapters/polyfills/node-sse-transport.ts"(){"use strict";init_base_sse_transport()}});var sse_transport_exports={};__export(sse_transport_exports,{RecreateableSSEServerTransport:()=>RecreateableSSEServerTransport});var RecreateableSSEServerTransport;var init_sse_transport=__esm({"libs/sdk/src/transport/adapters/sse-transport.ts"(){"use strict";init_node_sse_transport();RecreateableSSEServerTransport=class extends SSEServerTransport{_isRecreatedSession=false;constructor(endpoint,res,options){super(endpoint,res,options);if(options?.initialEventId!==void 0&&this.isValidEventId(options.initialEventId)){this.setEventIdCounter(options.initialEventId);this._isRecreatedSession=true}}isValidEventId(eventId){return Number.isInteger(eventId)&&eventId>=0&&eventId<=Number.MAX_SAFE_INTEGER}get isRecreatedSession(){return this._isRecreatedSession}get eventIdCounter(){return this.lastEventId}setEventIdCounter(eventId){if(!this.isValidEventId(eventId)){console.warn(`[RecreateableSSEServerTransport] Invalid eventId: ${eventId}. Must be a non-negative integer. Ignoring.`);return}super.setEventIdCounter(eventId)}setSessionState(sessionId,lastEventId){if(this.sessionId!==sessionId){const redact=id=>`${id.slice(0,8)}\u2026`;console.warn(`RecreateableSSEServerTransport: session ID mismatch. Expected ${redact(this.sessionId)}, got ${redact(sessionId)}. Using constructor value.`)}if(lastEventId!==void 0){this.setEventIdCounter(lastEventId)}this._isRecreatedSession=true}}}});async function loadSseTransport(){RecreateableTransport??=(await Promise.resolve().then(()=>(init_sse_transport(),sse_transport_exports))).RecreateableSSEServerTransport}function sseTransportClass(){if(!RecreateableTransport){throw new InternalMcpError("The SSE transport was used before loadSseTransport() loaded it")}return RecreateableTransport}var import_lazy_zod115,RecreateableTransport,TransportSSEAdapter;var init_transport_sse_adapter=__esm({"libs/sdk/src/transport/adapters/transport.sse.adapter.ts"(){"use strict";import_lazy_zod115=require("@frontmcp/lazy-zod");init_elicitation_types();init_errors();init_transport_error();init_transport_local_adapter();TransportSSEAdapter=class extends LocalTransportAdapter{sessionId;configureTransportHandlers(transport){transport.onerror=error=>{console.error("SSE error:",error instanceof Error?error.message:"Unknown error")};transport.onclose=this.destroy.bind(this)}createTransport(sessionId,res){this.sessionId=sessionId;this.logger.info(`new transport session: ${sessionId.slice(0,40)}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId});this.configureTransportHandlers(transport);return transport}createTransportFromSession(sessionId,res,lastEventId){this.sessionId=sessionId;this.logger.info(`recreating transport session: ${sessionId.slice(0,40)}, lastEventId: ${lastEventId??"none"}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId,initialEventId:lastEventId});this.configureTransportHandlers(transport);return transport}initialize(req,res){this.logger.verbose(`[${this.sessionId}] handle initialize request`);this.ensureAuthInfo(req,this);return Promise.resolve()}async handleRequest(req,res){await this.ready;const authInfo=this.ensureAuthInfo(req,this);if(this.handleIfElicitResult(req)){this.logger.verbose(`[${this.sessionId}] handled elicitation result`);res.writeHead(202,{"Content-Type":"application/json"});res.end(JSON.stringify({jsonrpc:"2.0",id:null,result:{}}));return}if(req.method==="GET"){this.logger.verbose(`[${this.sessionId}] handle get request`);return this.transport.handleMessage(req.body,{requestInfo:{headers:req.headers},authInfo})}else{this.logger.verbose(`[${this.sessionId}] handle post request`);return this.transport.handlePostMessage(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=options??{};if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}await this.cancelPendingElicit();const elicitId=elicitationId||`elicit-${this.newRequestId}`;const sessionId=this.key.sessionId;const expiresAt=Date.now()+ttl;const store=this.requireElicitStore();await store.setPending({elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode});const params={mode,message,requestedSchema:(0,import_lazy_zod115.toJSONSchema)(requestedSchema)};if(mode==="url"){params["elicitationId"]=elicitId;params["url"]=url}this.logger.info("sendElicitRequest",{relatedRequestId,elicitId,mode,ttl});await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",params));return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}}}});function createSessionScopedEventStore(store,sessionId){const prefix=`${sessionId}${SCOPE_SEPARATOR}`;const scope=streamId=>`${prefix}${streamId}`;const unscope=streamId=>{const value=String(streamId);return value.startsWith(prefix)?value.slice(prefix.length):value};const resolveOwnedStream=async eventId=>{const lookup=store.getStreamIdForEventId;if(lookup){const resolved=await lookup.call(store,eventId);return resolved!==void 0&&String(resolved).startsWith(prefix)?resolved:void 0}if(!String(eventId).startsWith(prefix))return void 0;const value=String(eventId);const lastColon=value.lastIndexOf(":");return lastColon===-1?void 0:value.slice(0,lastColon)};return{async storeEvent(streamId,message){return store.storeEvent(scope(streamId),message)},async getStreamIdForEventId(eventId){const owned=await resolveOwnedStream(eventId);return owned===void 0?void 0:unscope(owned)},async replayEventsAfter(lastEventId,options){const owned=await resolveOwnedStream(lastEventId);if(owned===void 0){return"default-stream"}return unscope(await store.replayEventsAfter(lastEventId,options))}}}var SCOPE_SEPARATOR;var init_session_scoped_event_store=__esm({"libs/sdk/src/transport/event-stores/session-scoped.event-store.ts"(){"use strict";SCOPE_SEPARATOR=" "}});var streamable_http_transport_exports={};__export(streamable_http_transport_exports,{RecreateableStreamableHTTPServerTransport:()=>RecreateableStreamableHTTPServerTransport});var import_protocol64,RecreateableStreamableHTTPServerTransport;var init_streamable_http_transport=__esm({"libs/sdk/src/transport/adapters/streamable-http-transport.ts"(){"use strict";import_protocol64=require("@frontmcp/protocol");init_transport_errors();RecreateableStreamableHTTPServerTransport=class extends import_protocol64.StreamableHTTPServerTransport{_pendingInitState;_constructorOptions;_isStateless;constructor(options={}){super(options);this._constructorOptions=options;this._isStateless=options.isStateless??false}get isInitialized(){return this._webStandardTransport?._initialized??false}get hasPendingInitState(){return this._pendingInitState!==void 0}setInitializationState(sessionId){if(!sessionId||typeof sessionId!=="string"||sessionId.trim()===""){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] sessionId cannot be empty")}const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=sessionId;return}this._applyInitState(webTransport,sessionId)}resetForReinitialization(){const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=void 0;return}if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=false;webTransport.sessionId=void 0;this._pendingInitState=void 0}_applyInitState(webTransport,sessionId){if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=true;webTransport.sessionId=sessionId}async handleRequest(req,res,body){const oldWebTransport=this._webStandardTransport;if(oldWebTransport&&this._isStateless&&oldWebTransport._hasHandledRequest){const fresh=new import_protocol64.WebStandardStreamableHTTPServerTransport(this._constructorOptions);fresh.onmessage=oldWebTransport.onmessage;fresh.onclose=oldWebTransport.onclose;fresh.onerror=oldWebTransport.onerror;await fresh.start();this._webStandardTransport=fresh}if(this._pendingInitState){const webTransport=this._webStandardTransport;if(webTransport){this._applyInitState(webTransport,this._pendingInitState);this._pendingInitState=void 0}}if(!res.headersSent)res.removeHeader?.("Content-Type");return super.handleRequest(req,res,body)}}}});async function loadStreamableHttpTransport(){RecreateableTransport2??=(await Promise.resolve().then(()=>(init_streamable_http_transport(),streamable_http_transport_exports))).RecreateableStreamableHTTPServerTransport}var import_lazy_zod116,RecreateableTransport2,resolveSessionIdGenerator,TransportStreamableHttpAdapter;var init_transport_streamable_http_adapter=__esm({"libs/sdk/src/transport/adapters/transport.streamable-http.adapter.ts"(){"use strict";import_lazy_zod116=require("@frontmcp/lazy-zod");init_errors();init_session_scoped_event_store();init_transport_error();init_transport_types();init_transport_local_adapter();resolveSessionIdGenerator=(transportType,sessionId)=>{return transportType==="stateless-http"?()=>STATELESS_SESSION_ID:()=>sessionId};TransportStreamableHttpAdapter=class extends LocalTransportAdapter{createTransport(sessionId,response){const sessionIdGenerator=resolveSessionIdGenerator(this.key.type,sessionId);const sharedEventStore=this.scope.eventStore;const eventStore=sharedEventStore?createSessionScopedEventStore(sharedEventStore,sessionId):void 0;const isStateless=this.key.type==="stateless-http";if(!RecreateableTransport2){throw new InternalMcpError("The Streamable HTTP transport was used before loadStreamableHttpTransport() loaded it")}return new RecreateableTransport2({sessionIdGenerator,isStateless,onsessionclosed:()=>{},onsessioninitialized:sessionId2=>{if(sessionId2){this.logger.verbose("[StreamableHttpAdapter] session initialized",{sessionId:sessionId2.slice(0,40)})}else{this.logger.verbose("[StreamableHttpAdapter] stateless session initialized")}},eventStore})}async initialize(req,res){this.ensureAuthInfo(req,this);this.logger.verbose("[StreamableHttpAdapter] initialize() called",{method:req.method,sessionId:this.key.sessionId.slice(0,30),bodyMethod:req.body?.method,bodyJsonrpc:req.body?.jsonrpc,bodyId:req.body?.id,bodyType:typeof req.body,bodyKeys:req.body&&typeof req.body==="object"?Object.keys(req.body):[]});await this.ready;this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest",{isRecreatable:RecreateableTransport2!==void 0&&this.transport instanceof RecreateableTransport2,hasWebTransport:!!this.transport._webStandardTransport,webTransportInitialized:this.transport._webStandardTransport?._initialized,webTransportStarted:this.transport._webStandardTransport?._started,hasSessionIdGenerator:this.transport._webStandardTransport?.sessionIdGenerator!==void 0});const originalWrite=res.write.bind(res);const originalEnd=res.end.bind(res);let responseBody="";res.write=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}return originalWrite.call(this,chunk,encodingOrCb,cb)};const adapter=this;res.end=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}adapter.logger.verbose("[StreamableHttpAdapter] initialize response",{statusCode:res.statusCode,headers:res.getHeaders?.()??{},bodyLength:responseBody.length});return originalEnd.call(this,chunk,encodingOrCb,cb)};return this.transport.handleRequest(req,res,req.body)}async handleRequest(req,res){this.ensureAuthInfo(req,this);if(req.method==="GET"){return this.transport.handleRequest(req,res)}else{if(this.handleIfElicitResult(req)){return}return this.transport.handleRequest(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){await this.cancelPendingElicit();const store=this.requireElicitStore();const sessionId=this.key.sessionId;const flowOutput=await this.scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:(0,import_lazy_zod116.toJSONSchema)(requestedSchema),options});const{elicitId,expiresAt,requestParams,pendingRecord}=flowOutput;const ttl=expiresAt-Date.now();this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create",{relatedRequestId,elicitId,mode:pendingRecord.mode,message:message.slice(0,100)});try{await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",requestParams),{relatedRequestId});this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed")}catch(error){this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed",error);try{await store.deletePending(sessionId);this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: cleaned up pending record after send failure")}catch(cleanupError){this.logger.warn("[StreamableHttpAdapter] sendElicitRequest: failed to clean up pending record",cleanupError)}throw error}return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}get isInitialized(){return this.transport.isInitialized||this.transport.hasPendingInitState}resetForReinitialization(){this.transport.resetForReinitialization();this.logger.info("[StreamableHttpAdapter] Reset transport for re-initialization",{sessionId:this.key.sessionId?.slice(0,20)})}markAsInitialized(){this.transport.setInitializationState(this.key.sessionId);this.logger.info("[StreamableHttpAdapter] Marked transport as pre-initialized for session recreation",{sessionId:this.key.sessionId?.slice(0,20),isInitialized:this.transport.isInitialized})}}}});function frame3(message){return encoder8.encode(`event: message
|
|
291
|
+
`)}get sessionId(){return this._sessionId}get lastEventId(){return this._eventIdCounter}setEventIdCounter(eventId){this._eventIdCounter=eventId}}}});var node_sse_transport_exports={};__export(node_sse_transport_exports,{SSEServerTransport:()=>SSEServerTransport});var init_node_sse_transport=__esm({"libs/sdk/src/transport/adapters/polyfills/node-sse-transport.ts"(){"use strict";init_base_sse_transport()}});var sse_transport_exports={};__export(sse_transport_exports,{RecreateableSSEServerTransport:()=>RecreateableSSEServerTransport});var RecreateableSSEServerTransport;var init_sse_transport=__esm({"libs/sdk/src/transport/adapters/sse-transport.ts"(){"use strict";init_node_sse_transport();RecreateableSSEServerTransport=class extends SSEServerTransport{_isRecreatedSession=false;constructor(endpoint,res,options){super(endpoint,res,options);if(options?.initialEventId!==void 0&&this.isValidEventId(options.initialEventId)){this.setEventIdCounter(options.initialEventId);this._isRecreatedSession=true}}isValidEventId(eventId){return Number.isInteger(eventId)&&eventId>=0&&eventId<=Number.MAX_SAFE_INTEGER}get isRecreatedSession(){return this._isRecreatedSession}get eventIdCounter(){return this.lastEventId}setEventIdCounter(eventId){if(!this.isValidEventId(eventId)){console.warn(`[RecreateableSSEServerTransport] Invalid eventId: ${eventId}. Must be a non-negative integer. Ignoring.`);return}super.setEventIdCounter(eventId)}setSessionState(sessionId,lastEventId){if(this.sessionId!==sessionId){const redact=id=>`${id.slice(0,8)}\u2026`;console.warn(`RecreateableSSEServerTransport: session ID mismatch. Expected ${redact(this.sessionId)}, got ${redact(sessionId)}. Using constructor value.`)}if(lastEventId!==void 0){this.setEventIdCounter(lastEventId)}this._isRecreatedSession=true}}}});async function loadSseTransport(){RecreateableTransport??=(await Promise.resolve().then(()=>(init_sse_transport(),sse_transport_exports))).RecreateableSSEServerTransport}function sseTransportClass(){if(!RecreateableTransport){throw new InternalMcpError("The SSE transport was used before loadSseTransport() loaded it")}return RecreateableTransport}var import_lazy_zod115,RecreateableTransport,TransportSSEAdapter;var init_transport_sse_adapter=__esm({"libs/sdk/src/transport/adapters/transport.sse.adapter.ts"(){"use strict";import_lazy_zod115=require("@frontmcp/lazy-zod");init_elicitation_types();init_errors();init_transport_error();init_transport_local_adapter();TransportSSEAdapter=class extends LocalTransportAdapter{sessionId;configureTransportHandlers(transport){transport.onerror=error=>{console.error("SSE error:",error instanceof Error?error.message:"Unknown error")};transport.onclose=this.destroy.bind(this)}createTransport(sessionId,res){this.sessionId=sessionId;this.logger.info(`new transport session: ${sessionId.slice(0,40)}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId});this.configureTransportHandlers(transport);return transport}createTransportFromSession(sessionId,res,lastEventId){this.sessionId=sessionId;this.logger.info(`recreating transport session: ${sessionId.slice(0,40)}, lastEventId: ${lastEventId??"none"}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId,initialEventId:lastEventId});this.configureTransportHandlers(transport);return transport}initialize(req,res){this.logger.verbose(`[${this.sessionId}] handle initialize request`);this.ensureAuthInfo(req,this);return Promise.resolve()}async handleRequest(req,res){await this.ready;const authInfo=this.ensureAuthInfo(req,this);if(this.handleIfElicitResult(req)){this.logger.verbose(`[${this.sessionId}] handled elicitation result`);res.writeHead(202,{"Content-Type":"application/json"});res.end(JSON.stringify({jsonrpc:"2.0",id:null,result:{}}));return}if(req.method==="GET"){this.logger.verbose(`[${this.sessionId}] handle get request`);return this.transport.handleMessage(req.body,{requestInfo:{headers:req.headers},authInfo})}else{this.logger.verbose(`[${this.sessionId}] handle post request`);return this.transport.handlePostMessage(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=options??{};if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}await this.cancelPendingElicit();const elicitId=elicitationId||`elicit-${this.newRequestId}`;const sessionId=this.key.sessionId;const expiresAt=Date.now()+ttl;const store=this.requireElicitStore();await store.setPending({elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode});const params={mode,message,requestedSchema:(0,import_lazy_zod115.toJSONSchema)(requestedSchema)};if(mode==="url"){params["elicitationId"]=elicitId;params["url"]=url}this.logger.info("sendElicitRequest",{relatedRequestId,elicitId,mode,ttl});await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",params));return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}}}});function createSessionScopedEventStore(store,sessionId){const prefix=`${sessionId}${SCOPE_SEPARATOR}`;const scope=streamId=>`${prefix}${streamId}`;const unscope=streamId=>{const value=String(streamId);return value.startsWith(prefix)?value.slice(prefix.length):value};const resolveOwnedStream=async eventId=>{const lookup=store.getStreamIdForEventId;if(lookup){const resolved=await lookup.call(store,eventId);return resolved!==void 0&&String(resolved).startsWith(prefix)?resolved:void 0}if(!String(eventId).startsWith(prefix))return void 0;const value=String(eventId);const lastColon=value.lastIndexOf(":");return lastColon===-1?void 0:value.slice(0,lastColon)};return{async storeEvent(streamId,message){return store.storeEvent(scope(streamId),message)},async getStreamIdForEventId(eventId){const owned=await resolveOwnedStream(eventId);return owned===void 0?void 0:unscope(owned)},async replayEventsAfter(lastEventId,options){const owned=await resolveOwnedStream(lastEventId);if(owned===void 0){return"default-stream"}return unscope(await store.replayEventsAfter(lastEventId,options))}}}var SCOPE_SEPARATOR;var init_session_scoped_event_store=__esm({"libs/sdk/src/transport/event-stores/session-scoped.event-store.ts"(){"use strict";SCOPE_SEPARATOR=" "}});var streamable_http_transport_exports={};__export(streamable_http_transport_exports,{RecreateableStreamableHTTPServerTransport:()=>RecreateableStreamableHTTPServerTransport});var import_protocol64,RecreateableStreamableHTTPServerTransport;var init_streamable_http_transport=__esm({"libs/sdk/src/transport/adapters/streamable-http-transport.ts"(){"use strict";import_protocol64=require("@frontmcp/protocol");init_transport_errors();RecreateableStreamableHTTPServerTransport=class extends import_protocol64.StreamableHTTPServerTransport{_pendingInitState;_constructorOptions;_isStateless;constructor(options={}){super(options);this._constructorOptions=options;this._isStateless=options.isStateless??false}get isInitialized(){return this._webStandardTransport?._initialized??false}get hasPendingInitState(){return this._pendingInitState!==void 0}setInitializationState(sessionId){if(!sessionId||typeof sessionId!=="string"||sessionId.trim()===""){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] sessionId cannot be empty")}const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=sessionId;return}this._applyInitState(webTransport,sessionId)}resetForReinitialization(){const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=void 0;return}if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=false;webTransport.sessionId=void 0;this._pendingInitState=void 0}_applyInitState(webTransport,sessionId){if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=true;webTransport.sessionId=sessionId}async handleRequest(req,res,body){const oldWebTransport=this._webStandardTransport;if(oldWebTransport&&this._isStateless&&oldWebTransport._hasHandledRequest){const fresh=new import_protocol64.WebStandardStreamableHTTPServerTransport(this._constructorOptions);fresh.onmessage=oldWebTransport.onmessage;fresh.onclose=oldWebTransport.onclose;fresh.onerror=oldWebTransport.onerror;await fresh.start();this._webStandardTransport=fresh}if(this._pendingInitState){const webTransport=this._webStandardTransport;if(webTransport){this._applyInitState(webTransport,this._pendingInitState);this._pendingInitState=void 0}}if(!res.headersSent)res.removeHeader?.("Content-Type");return super.handleRequest(req,res,body)}}}});async function loadStreamableHttpTransport(){RecreateableTransport2??=(await Promise.resolve().then(()=>(init_streamable_http_transport(),streamable_http_transport_exports))).RecreateableStreamableHTTPServerTransport}var import_lazy_zod116,RecreateableTransport2,resolveSessionIdGenerator,TransportStreamableHttpAdapter;var init_transport_streamable_http_adapter=__esm({"libs/sdk/src/transport/adapters/transport.streamable-http.adapter.ts"(){"use strict";import_lazy_zod116=require("@frontmcp/lazy-zod");init_errors();init_session_scoped_event_store();init_transport_error();init_transport_types();init_transport_local_adapter();resolveSessionIdGenerator=(transportType,sessionId)=>{return transportType==="stateless-http"?()=>STATELESS_SESSION_ID:()=>sessionId};TransportStreamableHttpAdapter=class extends LocalTransportAdapter{createTransport(sessionId,response){const sessionIdGenerator=resolveSessionIdGenerator(this.key.type,sessionId);const sharedEventStore=this.scope.eventStore;const eventStore=sharedEventStore?createSessionScopedEventStore(sharedEventStore,sessionId):void 0;const isStateless=this.key.type==="stateless-http";if(!RecreateableTransport2){throw new InternalMcpError("The Streamable HTTP transport was used before loadStreamableHttpTransport() loaded it")}return new RecreateableTransport2({sessionIdGenerator,isStateless,onsessionclosed:()=>{},onsessioninitialized:sessionId2=>{if(sessionId2){this.logger.verbose("[StreamableHttpAdapter] session initialized",{sessionId:sessionId2.slice(0,40)})}else{this.logger.verbose("[StreamableHttpAdapter] stateless session initialized")}},eventStore})}async initialize(req,res){this.ensureAuthInfo(req,this);this.logger.verbose("[StreamableHttpAdapter] initialize() called",{method:req.method,sessionId:this.key.sessionId.slice(0,30),bodyMethod:req.body?.method,bodyJsonrpc:req.body?.jsonrpc,bodyId:req.body?.id,bodyType:typeof req.body,bodyKeys:req.body&&typeof req.body==="object"?Object.keys(req.body):[]});await this.ready;this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest",{isRecreatable:RecreateableTransport2!==void 0&&this.transport instanceof RecreateableTransport2,hasWebTransport:!!this.transport._webStandardTransport,webTransportInitialized:this.transport._webStandardTransport?._initialized,webTransportStarted:this.transport._webStandardTransport?._started,hasSessionIdGenerator:this.transport._webStandardTransport?.sessionIdGenerator!==void 0});const originalWrite=res.write.bind(res);const originalEnd=res.end.bind(res);let responseBody="";res.write=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}return originalWrite.call(this,chunk,encodingOrCb,cb)};const adapter=this;res.end=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}adapter.logger.verbose("[StreamableHttpAdapter] initialize response",{statusCode:res.statusCode,headers:res.getHeaders?.()??{},bodyLength:responseBody.length});return originalEnd.call(this,chunk,encodingOrCb,cb)};return this.transport.handleRequest(req,res,req.body)}async handleRequest(req,res){this.ensureAuthInfo(req,this);if(req.method==="GET"){return this.transport.handleRequest(req,res)}else{if(this.handleIfElicitResult(req)){return}return this.transport.handleRequest(req,res,req.body)}}async destroy(reason){if(reason===void 0)await this.transport.close().catch(()=>void 0);return super.destroy(reason)}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){await this.cancelPendingElicit();const store=this.requireElicitStore();const sessionId=this.key.sessionId;const flowOutput=await this.scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:(0,import_lazy_zod116.toJSONSchema)(requestedSchema),options});const{elicitId,expiresAt,requestParams,pendingRecord}=flowOutput;const ttl=expiresAt-Date.now();this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create",{relatedRequestId,elicitId,mode:pendingRecord.mode,message:message.slice(0,100)});try{await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",requestParams),{relatedRequestId});this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed")}catch(error){this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed",error);try{await store.deletePending(sessionId);this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: cleaned up pending record after send failure")}catch(cleanupError){this.logger.warn("[StreamableHttpAdapter] sendElicitRequest: failed to clean up pending record",cleanupError)}throw error}return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}get isInitialized(){return this.transport.isInitialized||this.transport.hasPendingInitState}resetForReinitialization(){this.transport.resetForReinitialization();this.logger.info("[StreamableHttpAdapter] Reset transport for re-initialization",{sessionId:this.key.sessionId?.slice(0,20)})}markAsInitialized(){this.transport.setInitializationState(this.key.sessionId);this.logger.info("[StreamableHttpAdapter] Marked transport as pre-initialized for session recreation",{sessionId:this.key.sessionId?.slice(0,20),isInitialized:this.transport.isInitialized})}}}});function frame3(message){return encoder8.encode(`event: message
|
|
292
292
|
data: ${JSON.stringify(message)}
|
|
293
293
|
|
|
294
294
|
`)}function acceptsEventStream(headers){const accept=readHeader(headers,"accept");return typeof accept==="string"&&accept.includes("text/event-stream")}function extractTraceContext(meta){const out={};for(const key of TRACE_META_KEYS){if(typeof meta[key]==="string")out[key]=meta[key]}return Object.keys(out).length>0?out:void 0}async function*streamMessageResponse(options,sink,requestId,runInContext){let outcome;let failure;const running=runInContext(async()=>{try{outcome=await dispatch20260728(options)}catch(error){failure=error}}).finally(()=>sink.close());while(!sink.closed){await sink.waitForActivity();for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}}await running;for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}const id=requestId??null;if(failure!==void 0){const mapped=toJsonRpcError(failure);yield frame3({jsonrpc:"2.0",id,error:mapped.error});return}if(outcome?.kind==="error"){yield frame3({jsonrpc:"2.0",id,error:outcome.error});return}yield frame3({jsonrpc:"2.0",id,result:outcome?.result})}function isAnonymousCaller(auth){if(!auth)return true;if(!(0,import_auth54.isAnonymousSubject)(auth.user?.sub))return false;return!auth.token||auth.session?.payload?.isPublic===true}function errorResponse(status,error,id){return httpRespond.json({jsonrpc:"2.0",id:id===void 0?null:id,error},{status})}function toClientInfo(value){if(typeof value!=="object"||value===null)return void 0;const{name:name59,version}=value;return typeof name59==="string"&&typeof version==="string"?{name:name59,version}:void 0}var import_auth54,import_lazy_zod117,import_protocol65,import_utils143,plan24,MAX_RESOURCE_SUBSCRIPTIONS,subscriptionParamsSchema,requestIdSchema,stateSchema21,name24,Stage24,encoder8,TRACE_META_KEYS,HandleMcp20260728Flow;var init_handle_mcp_20260728_flow=__esm({"libs/sdk/src/transport/flows/handle.mcp-20260728.flow.ts"(){"use strict";import_auth54=require("@frontmcp/auth");import_lazy_zod117=require("@frontmcp/lazy-zod");import_protocol65=require("@frontmcp/protocol");import_utils143=require("@frontmcp/utils");init_common();init_tool_lookup_utils();init_context();init_notification();init_notification_service();init_skill_instructions_helper();init_mcp_20260728();init_mcp_surface();plan24={pre:["parseInput","validate","router"],execute:["handleNotification","handleSubscriptions","handleEventStream","handleMessage"],post:[],finalize:["cleanup"]};MAX_RESOURCE_SUBSCRIPTIONS=1e3;subscriptionParamsSchema=import_lazy_zod117.internalZ.object({notifications:import_lazy_zod117.internalZ.object({toolsListChanged:import_lazy_zod117.internalZ.boolean().optional(),promptsListChanged:import_lazy_zod117.internalZ.boolean().optional(),resourcesListChanged:import_lazy_zod117.internalZ.boolean().optional(),resourceSubscriptions:import_lazy_zod117.internalZ.array(import_lazy_zod117.internalZ.string()).max(MAX_RESOURCE_SUBSCRIPTIONS,{message:`subscriptions/listen takes at most ${MAX_RESOURCE_SUBSCRIPTIONS} resourceSubscriptions`}).optional()}).default({})});requestIdSchema=import_lazy_zod117.internalZ.union([import_lazy_zod117.internalZ.string(),import_lazy_zod117.internalZ.number()]);stateSchema21=import_lazy_zod117.internalZ.object({version:import_lazy_zod117.internalZ.string().optional(),requestType:import_lazy_zod117.internalZ.enum(["notification","subscriptions","eventStream","message"]).optional(),isAnonymous:import_lazy_zod117.internalZ.boolean().default(true),clientDeclaredRevision:import_lazy_zod117.internalZ.boolean().optional()});name24="handle:mcp-202607280728";({Stage:Stage24}=FlowHooksOf(name24));encoder8=new TextEncoder;TRACE_META_KEYS=["traceparent","tracestate","baggage"];HandleMcp20260728Flow=class extends FlowBase{name=name24;get log(){return this.scope.logger.child("HandleMcp20260728Flow")}async parseInput(){const{request:request2}=this.rawInput;const auth=request2[ServerRequestTokens.auth];this.state.set(stateSchema21.parse({isAnonymous:isAnonymousCaller(auth)}))}async validate(){const{request:request2}=this.rawInput;const method=request2.method.toUpperCase();if(method==="GET"||method==="DELETE"){this.respond({kind:"text",status:405,body:`HTTP ${method} is not supported by MCP protocol 2026-07-28`,contentType:"text/plain; charset=utf-8",headers:{Allow:"POST"}});return}const body=request2.body??{};const scope=this.scope;const clientDeclaredRevision=declaresProtocol20260728({headers:request2.headers,body});const result=validate20260728Request({headers:request2.headers,body,lookupToolSchema:toolName=>this.findToolSchema(scope,toolName),strictHeaders:clientDeclaredRevision&&!this.stdioOrigin});if(!result.ok){this.log.info("validate: rejected",{code:result.error.code,message:result.error.message});this.respond(errorResponse(result.status,result.error,body["id"]));return}this.state.set("version",result.version);this.state.set("clientDeclaredRevision",clientDeclaredRevision)}get stdioOrigin(){return this.rawInput.request[ServerRequestTokens.stdio]}buildContextRunner(){const context=this.tryGetContext();if(!context)return fn=>fn();const storage=this.scope.providers.get(FrontMcpContextStorage);return async fn=>{await(0,import_utils143.runRequestExclusive)(()=>storage.runWithContext(context,fn))}}findToolSchema(scope,toolName){return lookupTool(scope,toolName)?.getInputJsonSchema()??null}async router(){const body=this.rawInput.request.body??{};const isNotification=body["id"]===void 0||body["id"]===null;if(isNotification){this.state.set("requestType","notification");return}if(body["method"]==="events/stream"&&this.scope.events?.performs("push")){this.state.set("requestType","eventStream");return}this.state.set("requestType",body["method"]==="subscriptions/listen"?"subscriptions":"message")}async handleNotification(){this.respond({kind:"text",status:202,body:"",contentType:"text/plain; charset=utf-8"})}async handleSubscriptions(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const subscriptionId=requestIdSchema.safeParse(body["id"]);if(!subscriptionId.success){this.respond(errorResponse(400,{code:-32602,message:"subscriptions/listen requires a string or number id"},null));return}const parsedParams=subscriptionParamsSchema.safeParse(body["params"]??{});if(!parsedParams.success){this.respond(errorResponse(400,{code:-32602,message:`Invalid subscriptions/listen params: ${parsedParams.error.issues[0]?.message??"not an object"}`},subscriptionId.data));return}const auth=request2[ServerRequestTokens.auth];const listenerAuthInfo=auth?authInfoFromAuthorization(auth):{};const mayRead=this.resourceReadCheck(listenerAuthInfo);const requested={...parsedParams.data.notifications,resourceSubscriptions:await this.readableUris(parsedParams.data.notifications.resourceSubscriptions,mayRead)};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});const{acknowledged,stream}=createSubscriptionStream({scope:this.scope,subscriptionId:subscriptionId.data,requested,channels:await this.listenedChannels(body["params"]?._meta),signal:controller.signal,mayReceiveUpdate:(uri,watchedUri)=>listenerMayReceive(()=>hasExpiredCaller({caller:sessionCallerOf(listenerAuthInfo)}),()=>mayRead(this.scope.resources.findResourceForUri(uri)?uri:watchedUri))});this.log.info("handleSubscriptions: stream opened",{subscriptionId:body["id"],acknowledged:Object.keys(acknowledged)});this.respond({kind:"sse",status:200,stream,contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}async handleEventStream(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const requestId=requestIdSchema.safeParse(body["id"]);if(!requestId.success){this.respond(errorResponse(400,{code:-32602,message:"events/stream requires a string or number id"},null));return}const streamRequest=import_protocol65.StreamEventsRequestSchema.safeParse({method:"events/stream",params:body["params"]});if(!streamRequest.success){const problem2=streamRequest.error.issues[0]?.message??"not an object";const error={code:-32602,message:`Invalid events/stream params: ${problem2}`};this.respond(errorResponse(400,error,requestId.data));return}const meta=body["params"]?._meta??{};const clientInfo=toClientInfo(meta[import_protocol65.MCP_20260728_META.clientInfo]);const clientCapabilities=meta[import_protocol65.MCP_20260728_META.clientCapabilities]??{};const platformDetection=this.scope.metadata.transport?.platformDetection;this.tryGetContext()?.setClientInfo(clientInfo,resolvePlatformType(clientInfo,clientCapabilities,platformDetection));const auth=request2[ServerRequestTokens.auth];const authInfo=auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:{};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});let opened;try{opened=await this.scope.runFlowForOutput("events:stream",{request:streamRequest.data,ctx:{authInfo,surface:mcpRequestSurface(this.scope)},requestId:requestId.data,signal:controller.signal})}catch(failure){const mapped=toJsonRpcError(failure);this.respond(errorResponse(mapped.status,mapped.error,requestId.data));return}this.log.info("handleEventStream: stream opened",{subscriptionId:requestId.data});this.respond({kind:"sse",status:200,stream:eventStreamFrames(opened.stream,requestId.data),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}resourceReadCheck(authInfo){const runInRequest=this.buildContextRunner();const ctx={authInfo,surface:mcpRequestSurface(this.scope)};return async uri=>{let allowed=false;await runInRequest(async()=>{const request2={method:"resources/subscribe",params:{uri}};allowed=await this.scope.runFlow("resources:subscribe",{request:request2,ctx}).then(()=>true,()=>false)});return allowed}}async readableUris(uris,mayRead){if(!uris)return void 0;const unique=[...new Set(uris)];const allowed=await Promise.all(unique.map(mayRead));return unique.filter((_uri,index)=>allowed[index])}async listenedChannels(meta){const capabilities=meta?.[import_protocol65.MCP_20260728_META.clientCapabilities];if(!supportsChannels(capabilities)||!this.scope.channels)return[];const listed=await this.scope.runFlowForOutput("channels:list",{});return listed.channels.map(channel2=>channel2.name)}async handleMessage(){const{request:request2}=this.rawInput;const body=request2.body??{};const params=body["params"]??{};const meta=params["_meta"]??{};const auth=request2[ServerRequestTokens.auth];const stdio=this.stdioOrigin;const clientCapabilities=meta[import_protocol65.MCP_20260728_META.clientCapabilities]??{};const logLevel=typeof meta[import_protocol65.MCP_20260728_META.logLevel]==="string"?meta[import_protocol65.MCP_20260728_META.logLevel]:void 0;const rawProgressToken=meta["progressToken"];const progressToken=typeof rawProgressToken==="string"||typeof rawProgressToken==="number"?rawProgressToken:void 0;const sink=new RequestNotificationSink(logLevel,progressToken);const clientInfo=toClientInfo(meta[import_protocol65.MCP_20260728_META.clientInfo]);const platformType=resolvePlatformType(clientInfo,clientCapabilities,this.scope.metadata.transport?.platformDetection);this.tryGetContext()?.setClientInfo(clientInfo,platformType);const dispatchOptions={scope:this.scope,body,clientCapabilities,frontmcpContext:this.tryGetContext(),authInfo:auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:stdio&&{sessionId:this.tryGetContext()?.sessionId},isAnonymous:this.state.required.isAnonymous,transportPrincipal:stdio?.principal,signal:stdio?.signal,clientDeclaredRevision:this.state.clientDeclaredRevision!==false,composeInstructions:(caller,clientName)=>composeCallerInstructions(this.scope,{ctx:caller,clientName:clientName??this.tryGetContext()?.clientInfo?.name,skillUriHints:true}),notificationSink:sink,traceContext:extractTraceContext(meta)};const streams=stdio!==void 0||acceptsEventStream(request2.headers);if(sink.active&&streams){this.respond({kind:"sse",status:200,stream:streamMessageResponse(dispatchOptions,sink,body["id"],this.buildContextRunner()),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}});return}const outcome=await dispatch20260728(dispatchOptions);sink.close();if(outcome.kind==="error"){this.respond(errorResponse(outcome.status,outcome.error,body["id"]));return}this.respond(httpRespond.json({jsonrpc:"2.0",id:body["id"]??null,result:outcome.result},{status:200}))}async cleanup(){}};__decorateClass([Stage24("parseInput")],HandleMcp20260728Flow.prototype,"parseInput",1);__decorateClass([Stage24("validate")],HandleMcp20260728Flow.prototype,"validate",1);__decorateClass([Stage24("router")],HandleMcp20260728Flow.prototype,"router",1);__decorateClass([Stage24("handleNotification",{filter:({state})=>state.required.requestType==="notification"})],HandleMcp20260728Flow.prototype,"handleNotification",1);__decorateClass([Stage24("handleSubscriptions",{filter:({state})=>state.required.requestType==="subscriptions"})],HandleMcp20260728Flow.prototype,"handleSubscriptions",1);__decorateClass([Stage24("handleEventStream",{filter:({state})=>state.required.requestType==="eventStream"})],HandleMcp20260728Flow.prototype,"handleEventStream",1);__decorateClass([Stage24("handleMessage",{filter:({state})=>state.required.requestType==="message"})],HandleMcp20260728Flow.prototype,"handleMessage",1);__decorateClass([Stage24("cleanup")],HandleMcp20260728Flow.prototype,"cleanup",1);HandleMcp20260728Flow=__decorateClass([FrontMcpFlow({name:name24,plan:plan24,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleMcp20260728Flow)}});function getQuerySessionId2(urlPath){if(!urlPath)return void 0;try{const u=new URL(String(urlPath),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function resolveLegacySseSession(params){const{rawHeader,requestUrl,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);const querySessionId=getQuerySessionId2(requestUrl);const validatedQuerySessionId=querySessionId?validateMcpSessionHeader(querySessionId):void 0;if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(querySessionId!==void 0&&!validatedQuerySessionId){return{responded404:true,createdNew:false}}const effectiveSessionId=mcpSessionHeader??validatedQuerySessionId;if(effectiveSessionId){if(authorizationSession?.id===effectiveSessionId){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}var import_lazy_zod118,plan25,stateSessionSchema,stateSchema22,name25,Stage25,HandleSseFlow;var init_handle_sse_flow=__esm({"libs/sdk/src/transport/flows/handle.sse.flow.ts"(){"use strict";import_lazy_zod118=require("@frontmcp/lazy-zod");init_session_id_utils();init_common();init_errors();init_ha_headers();init_skill_mode_utils();plan25={pre:["parseInput","router"],execute:["onInitialize","onMessage","onElicitResult"],post:[],finalize:["cleanup"]};stateSessionSchema=import_lazy_zod118.internalZ.object({id:import_lazy_zod118.internalZ.string(),payload:import_lazy_zod118.internalZ.object({nodeId:import_lazy_zod118.internalZ.string(),authSig:import_lazy_zod118.internalZ.string(),uuid:import_lazy_zod118.internalZ.string().uuid(),iat:import_lazy_zod118.internalZ.number(),protocol:import_lazy_zod118.internalZ.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:import_lazy_zod118.internalZ.boolean().optional(),platformType:import_lazy_zod118.internalZ.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema22=import_lazy_zod118.internalZ.object({token:import_lazy_zod118.internalZ.string(),session:stateSessionSchema,requestType:import_lazy_zod118.internalZ.enum(["initialize","message","elicitResult"]).optional()});name25="handle:legacy-sse";({Stage:Stage25}=FlowHooksOf(name25));HandleSseFlow=class extends FlowBase{async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const anyReq=request2;const resolution=resolveLegacySseSession({rawHeader:request2.headers?.["mcp-session-id"],requestUrl:anyReq.url??anyReq.path,authorizationSession:authorization.session,createSession:()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("legacy-sse",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})}});if(resolution.responded404||!resolution.session){this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=resolution.session;this.state.set(stateSchema22.parse({token,session}))}async router(){const{request:request2}=this.rawInput;const requestPath=normalizeEntryPrefix(request2.path);const prefix=normalizeEntryPrefix(this.scope.entryPath);const scopePath=normalizeScopeBase(this.scope.routeBase);const basePath=`${prefix}${scopePath}`;if(requestPath===`${basePath}/sse`){this.state.set("requestType","initialize")}else if(requestPath===`${basePath}/message`){this.state.set("requestType","message")}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const authorization=request2[ServerRequestTokens.auth];authorization.session??=session;const transport=await transportService.createTransporter("sse",token,session.id,response);applyNodeAffinity(response,request2);await transport.initialize(request2,response);this.handled()}async onElicitResult(){this.fail(new Error("Not implemented"))}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:legacy-sse:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const transport=await transportService.getTransporter("sse",token,session.id);if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("sse",token,session.id);const body=request2.body;if(wasCreated){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"]});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}await transport.handleRequest(request2,response);this.handled()}};__decorateClass([Stage25("parseInput")],HandleSseFlow.prototype,"parseInput",1);__decorateClass([Stage25("router")],HandleSseFlow.prototype,"router",1);__decorateClass([Stage25("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleSseFlow.prototype,"onInitialize",1);__decorateClass([Stage25("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleSseFlow.prototype,"onElicitResult",1);__decorateClass([Stage25("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleSseFlow.prototype,"onMessage",1);HandleSseFlow=__decorateClass([FrontMcpFlow({name:name25,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,plan:plan25})],HandleSseFlow)}});var import_lazy_zod119,import_protocol66,plan26,stateSchema23,name26,Stage26,HandleStatelessHttpFlow;var init_handle_stateless_http_flow=__esm({"libs/sdk/src/transport/flows/handle.stateless-http.flow.ts"(){"use strict";import_lazy_zod119=require("@frontmcp/lazy-zod");import_protocol66=require("@frontmcp/protocol");init_common();init_errors();init_ha_headers();init_transport_types();plan26={pre:["applyNodeHeaders","parseInput","router"],execute:["handleRequest"],post:[],finalize:["cleanup"]};stateSchema23=import_lazy_zod119.internalZ.object({token:import_lazy_zod119.internalZ.string().optional(),isAuthenticated:import_lazy_zod119.internalZ.boolean(),requestType:import_lazy_zod119.internalZ.enum(["initialize","message"]).optional()});name26="handle:stateless-http";({Stage:Stage26}=FlowHooksOf(name26));HandleStatelessHttpFlow=class extends FlowBase{name=name26;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const auth=request2[ServerRequestTokens.auth];const token=auth?.token;const isAuthenticated=!!token&&token.length>0;logger.verbose("parseInput",{isAuthenticated,hasToken:!!token});this.state.set(stateSchema23.parse({token:token||void 0,isAuthenticated}))}async router(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const body=request2.body;const method=body?.method;if(method==="initialize"){this.state.set("requestType","initialize");logger.verbose("router: requestType=initialize, method=POST")}else if(method&&import_protocol66.RequestSchema.safeParse(request2.body).success){this.state.set("requestType","message");logger.verbose(`router: requestType=message, method=${method}`)}else{logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"))}}async handleRequest(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("HandleStatelessHttpFlow");const{request:request2,response}=this.rawInput;const{token,isAuthenticated,requestType}=this.state;logger.verbose(`handleRequest: using ${isAuthenticated?"authenticated":"anonymous"} stateless transport`);const transport=isAuthenticated&&token?await transportService.getOrCreateAuthenticatedStatelessTransport("stateless-http",token,response):await transportService.getOrCreateAnonymousStatelessTransport("stateless-http",response);if(!request2.headers["mcp-session-id"]){request2.headers["mcp-session-id"]=STATELESS_SESSION_ID;logger.verbose(`handleRequest: injected ${STATELESS_SESSION_ID} session ID`)}logger.verbose(`handleRequest: requestType=${requestType}, forwarding to transport`);try{if(requestType==="initialize"){await transport.initialize(request2,response)}else{await transport.handleRequest(request2,response)}}catch(error){logger.error("handleRequest: transport failed",{requestType,error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}this.handled()}};__decorateClass([Stage26("applyNodeHeaders")],HandleStatelessHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage26("parseInput")],HandleStatelessHttpFlow.prototype,"parseInput",1);__decorateClass([Stage26("router")],HandleStatelessHttpFlow.prototype,"router",1);__decorateClass([Stage26("handleRequest")],HandleStatelessHttpFlow.prototype,"handleRequest",1);HandleStatelessHttpFlow=__decorateClass([FrontMcpFlow({name:name26,plan:plan26,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStatelessHttpFlow)}});var EXT_APPS_ERROR_CODES;var init_ext_apps_types=__esm({"libs/sdk/src/ext-apps/ext-apps.types.ts"(){"use strict";EXT_APPS_ERROR_CODES={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TOOL_NOT_FOUND:-32001,TOOL_EXECUTION_FAILED:-32002,NOT_SUPPORTED:-32003,CANCELLED:-32004}}});function createExtAppsMessageHandler(options){return new ExtAppsMessageHandler(options)}var import_utils144,MCP_LOG_LEVELS,ExtAppsMessageHandler,ExtAppsError,ExtAppsMethodNotFoundError,ExtAppsInvalidParamsError,ExtAppsNotSupportedError,ExtAppsToolNotFoundError;var init_ext_apps_handler=__esm({"libs/sdk/src/ext-apps/ext-apps.handler.ts"(){"use strict";import_utils144=require("@frontmcp/utils");init_errors();init_ext_apps_types();MCP_LOG_LEVELS={debug:"debug",info:"info",notice:"info",warning:"warn",error:"error",critical:"error",alert:"error",emergency:"error"};ExtAppsMessageHandler=class{context;hostCapabilities;logger;constructor(options){this.context=options.context;this.hostCapabilities=options.hostCapabilities||{};this.logger=options.context.logger.child("ExtAppsMessageHandler")}getHostCapabilities(){return{...this.hostCapabilities}}async handleRequest(request2){const{id,method,params}=request2;this.logger.verbose(`handleRequest: method=${(0,import_utils144.escapeControlCharacters)(method)}, id=${(0,import_utils144.escapeControlCharacters)(id)}`);try{const result=await this.routeMethod(method,params);return{jsonrpc:"2.0",id,result:result===void 0?{}:result}}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);const errorCode2=this.getErrorCode(error);this.logger.warn(`handleRequest: method=${(0,import_utils144.escapeControlCharacters)(method)} failed: ${(0,import_utils144.escapeControlCharacters)(errorMessage2)}`);return{jsonrpc:"2.0",id,error:{code:errorCode2,message:this.widgetMessageOf(error),data:(0,import_utils144.isDevelopment)()&&error instanceof Error?{stack:error.stack}:void 0}}}}async handleNotification(notification){const{method,params}=notification;if(method!=="notifications/message"&&method!=="ui/notifications/request-teardown"){this.logger.verbose(`handleNotification: ignoring method=${(0,import_utils144.escapeControlCharacters)(method)}`);return}if(method==="ui/notifications/request-teardown"&&!this.context.close){this.logger.verbose("handleNotification: ignoring ui/notifications/request-teardown (no close callback)");return}try{await this.routeMethod(method,params)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.warn(`handleNotification: method=${(0,import_utils144.escapeControlCharacters)(method)} failed: ${(0,import_utils144.escapeControlCharacters)(errorMessage2)}`)}}async routeMethod(method,params){if(params!==void 0&&(params===null||typeof params!=="object"||Array.isArray(params))){throw new ExtAppsInvalidParamsError("Invalid params: expected object")}const normalizedParams=params??{};switch(method){case"ui/initialize":return this.handleInitialize(normalizedParams);case"ui/callServerTool":return this.handleCallServerTool(normalizedParams);case"ui/update-model-context":return this.handleSpecUpdateModelContext(normalizedParams);case"ui/updateModelContext":return this.handleUpdateModelContext(normalizedParams);case"ui/open-link":case"ui/openLink":return this.handleOpenLink(normalizedParams);case"ui/request-display-mode":case"ui/setDisplayMode":return this.handleSetDisplayMode(normalizedParams);case"ui/notifications/request-teardown":case"ui/close":return this.handleClose(normalizedParams);case"notifications/message":return this.handleLogMessage(normalizedParams);case"ui/log":return this.handleLog(normalizedParams);case"ui/registerTool":return this.handleRegisterTool(normalizedParams);case"ui/unregisterTool":return this.handleUnregisterTool(normalizedParams);default:throw new ExtAppsMethodNotFoundError(`Unknown ext-apps method: ${method}`)}}handleInitialize(params){const{appInfo,protocolVersion}=params;this.logger.verbose(`handleInitialize: app=${(0,import_utils144.escapeControlCharacters)(appInfo?.name||"unknown")} v${(0,import_utils144.escapeControlCharacters)(appInfo?.version||"unknown")}, protocol=${(0,import_utils144.escapeControlCharacters)(protocolVersion)}`);return{hostCapabilities:this.hostCapabilities,protocolVersion:protocolVersion||"2024-11-05"}}async handleCallServerTool(params){if(!this.hostCapabilities.serverToolProxy){throw new ExtAppsNotSupportedError("Server tool proxy not supported by host")}const{name:name59,arguments:args={}}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleCallServerTool: tool=${(0,import_utils144.escapeControlCharacters)(name59)}`);return this.context.callTool(name59,args)}async handleUpdateModelContext(params){if(!this.hostCapabilities.modelContextUpdate){throw new ExtAppsNotSupportedError("Model context update not advertised by host")}if(!this.context.updateModelContext){throw new ExtAppsNotSupportedError("Model context update not supported by host")}const{context,merge=true}=params;this.logger.verbose(`handleUpdateModelContext: merge=${merge}`);await this.context.updateModelContext(context,merge)}async handleSpecUpdateModelContext(params){const{content,structuredContent}=params;if(content!==void 0&&!Array.isArray(content)){throw new ExtAppsInvalidParamsError("content must be an array of content blocks")}if(structuredContent!==void 0&&(typeof structuredContent!=="object"||structuredContent===null||Array.isArray(structuredContent))){throw new ExtAppsInvalidParamsError("structuredContent must be an object")}const context={};if(content!==void 0)context.content=content;if(structuredContent!==void 0)context.structuredContent=structuredContent;await this.handleUpdateModelContext({context,merge:false})}async handleOpenLink(params){if(!this.hostCapabilities.openLink){throw new ExtAppsNotSupportedError("Open link not advertised by host")}if(!this.context.openLink){throw new ExtAppsNotSupportedError("Open link not supported by host")}const{url}=params;if(!url||typeof url!=="string"){throw new ExtAppsInvalidParamsError("URL is required")}let parsed;try{parsed=new URL(url)}catch{throw new ExtAppsInvalidParamsError("Invalid URL format")}const allowedSchemes=["http:","https:"];if(!allowedSchemes.includes(parsed.protocol)){throw new ExtAppsInvalidParamsError(`URL scheme '${parsed.protocol}' not allowed. Only http: and https: are permitted.`)}this.logger.verbose(`handleOpenLink: url=${(0,import_utils144.escapeControlCharacters)(url)}`);await this.context.openLink(url)}async handleSetDisplayMode(params){const{mode}=params;if(!mode||!["inline","fullscreen","pip"].includes(mode)){throw new ExtAppsInvalidParamsError("Invalid display mode. Must be inline, fullscreen, or pip")}if(this.hostCapabilities.displayModes&&!this.hostCapabilities.displayModes.includes(mode)){throw new ExtAppsNotSupportedError(`Display mode '${mode}' not advertised by host`)}if(!this.context.setDisplayMode){throw new ExtAppsNotSupportedError("Display mode change not supported by host")}this.logger.verbose(`handleSetDisplayMode: mode=${(0,import_utils144.escapeControlCharacters)(mode)}`);await this.context.setDisplayMode(mode);return{mode}}async handleClose(params){if(!this.context.close){throw new ExtAppsNotSupportedError("Widget close not supported by host")}const{reason}=params;this.logger.verbose(`handleClose: reason=${(0,import_utils144.escapeControlCharacters)(reason||"none")}`);await this.context.close(reason)}async handleLog(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,message,data}=params;if(!message||typeof message!=="string"){throw new ExtAppsInvalidParamsError("Log message is required")}const validLevels=["debug","info","warn","error"];if(level&&!validLevels.includes(level)){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${validLevels.join(", ")}`)}this.writeWidgetLog(level??"info",message,data)}async handleLogMessage(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,logger,data}=params;const serverLevel=Object.hasOwn(MCP_LOG_LEVELS,level)?MCP_LOG_LEVELS[level]:void 0;if(!serverLevel){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${Object.keys(MCP_LOG_LEVELS).join(", ")}`)}if(typeof data==="string"){this.writeWidgetLog(serverLevel,data,void 0)}else{this.writeWidgetLog(serverLevel,logger??"widget log",data)}}writeWidgetLog(level,text,data){const widgetLogger=this.logger.child(`Widget:${this.context.sessionId}`);const message=(0,import_utils144.escapeControlCharacters)(text);switch(level){case"debug":widgetLogger.verbose(message,data);break;case"info":widgetLogger.info(message,data);break;case"warn":widgetLogger.warn(message,data);break;case"error":widgetLogger.error(message,data);break;default:widgetLogger.info(message,data)}}async handleRegisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.registerTool){throw new ExtAppsNotSupportedError("Widget tool registration not supported by host")}const{name:name59,description,inputSchema:inputSchema53}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}if(!description||typeof description!=="string"){throw new ExtAppsInvalidParamsError("Tool description is required")}if(!inputSchema53||typeof inputSchema53!=="object"||Array.isArray(inputSchema53)){throw new ExtAppsInvalidParamsError("Tool input schema must be a non-null object")}this.logger.verbose(`handleRegisterTool: name=${(0,import_utils144.escapeControlCharacters)(name59)}`);await this.context.registerTool(name59,description,inputSchema53)}async handleUnregisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.unregisterTool){throw new ExtAppsNotSupportedError("Widget tool unregistration not supported by host")}const{name:name59}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleUnregisterTool: name=${(0,import_utils144.escapeControlCharacters)(name59)}`);await this.context.unregisterTool(name59)}widgetMessageOf(error){if(error instanceof ExtAppsError||(0,import_utils144.isDevelopment)())return error instanceof Error?error.message:String(error);return toMcpError(error).getPublicMessage()}getErrorCode(error){if(error instanceof ExtAppsMethodNotFoundError){return EXT_APPS_ERROR_CODES.METHOD_NOT_FOUND}if(error instanceof ExtAppsInvalidParamsError){return EXT_APPS_ERROR_CODES.INVALID_PARAMS}if(error instanceof ExtAppsNotSupportedError){return EXT_APPS_ERROR_CODES.NOT_SUPPORTED}if(error instanceof ExtAppsToolNotFoundError){return EXT_APPS_ERROR_CODES.TOOL_NOT_FOUND}return EXT_APPS_ERROR_CODES.INTERNAL_ERROR}};ExtAppsError=class extends Error{constructor(message){super(message);this.name="ExtAppsError"}};ExtAppsMethodNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsMethodNotFoundError"}};ExtAppsInvalidParamsError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsInvalidParamsError"}};ExtAppsNotSupportedError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsNotSupportedError"}};ExtAppsToolNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsToolNotFoundError"}}}});var init_ext_apps2=__esm({"libs/sdk/src/ext-apps/index.ts"(){"use strict";init_ext_apps_types();init_ext_apps_handler()}});function resolveStreamableHttpSession(params){const{rawHeader,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(mcpSessionHeader){if(authorizationSession?.id===mcpSessionHeader){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}function classifyStreamableHttpRequest(params){const{method,body}=params;if(method.toUpperCase()==="GET"){return{requestType:"sseListener"}}const jsonRpcMethod=body?.method;if(jsonRpcMethod==="initialize"){return{requestType:"initialize"}}if(typeof jsonRpcMethod==="string"&&(jsonRpcMethod.startsWith("ui/")||jsonRpcMethod==="notifications/message")){return{requestType:"extApps"}}if(import_protocol67.ElicitResultSchema.safeParse(body?.result).success){return{requestType:"elicitResult"}}if(jsonRpcMethod&&import_protocol67.RequestSchema.safeParse(body).success){return{requestType:"message"}}return{error:"Invalid Request"}}function syncStreamableHttpAuthorizationSession(authorization,session){if(!authorization.session){authorization.session=session}}function resetInitializedTransportForReinit(transport){if(!transport.isInitialized){return true}transport.resetForReinitialization();transport.reregisterServer();return!transport.isInitialized}function buildReinitFailedResponse(sessionId,requestId){return httpRespond.rpcError(`Could not re-initialize session "${sessionId}". It is stuck in an initialized state \u2014 terminate it with an HTTP DELETE to the MCP endpoint (including the mcp-session-id header), or reconnect without the stored mcp-session-id to start a fresh session.`,requestId)}async function lookupStreamableHttpTransport(params){const{transportService,token,sessionId,response}=params;const inMemoryTransport=await transportService.getTransporter("streamable-http",token,sessionId);if(inMemoryTransport){return{kind:"transport",source:"memory",transport:inMemoryTransport}}let recreationError;try{const storedSession=await transportService.getStoredSession("streamable-http",token,sessionId);if(storedSession){const recreatedTransport=await transportService.recreateTransporter("streamable-http",token,sessionId,storedSession,response);if(recreatedTransport){return{kind:"transport",source:"redis",transport:recreatedTransport}}}}catch(error){recreationError=error}const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,sessionId);if(wasCreated){return{kind:"session-expired",recreationError}}return{kind:"session-not-initialized",recreationError}}function sessionIdForLog(sessionId){return typeof sessionId==="string"?sessionId.slice(0,20):void 0}function errorMessageForLog(error,sessionId){const message=error instanceof Error?error.message:String(error);return sessionId?message.replaceAll(sessionId,`${sessionIdForLog(sessionId)}...`):message}var import_lazy_zod120,import_protocol67,plan27,stateSessionSchema2,stateSchema24,name27,Stage27,HandleStreamableHttpFlow;var init_handle_streamable_http_flow=__esm({"libs/sdk/src/transport/flows/handle.streamable-http.flow.ts"(){"use strict";import_lazy_zod120=require("@frontmcp/lazy-zod");import_protocol67=require("@frontmcp/protocol");init_session_id_utils();init_common();init_errors();init_ext_apps2();init_ha_headers();init_skill_mode_utils();init_mcp_surface();plan27={pre:["applyNodeHeaders","parseInput","router"],execute:["onInitialize","onMessage","onElicitResult","onSseListener","onExtApps"],post:[],finalize:["cleanup"]};stateSessionSchema2=import_lazy_zod120.internalZ.object({id:import_lazy_zod120.internalZ.string(),payload:import_lazy_zod120.internalZ.object({nodeId:import_lazy_zod120.internalZ.string(),authSig:import_lazy_zod120.internalZ.string(),uuid:import_lazy_zod120.internalZ.string().uuid(),iat:import_lazy_zod120.internalZ.number(),protocol:import_lazy_zod120.internalZ.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:import_lazy_zod120.internalZ.boolean().optional(),platformType:import_lazy_zod120.internalZ.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema24=import_lazy_zod120.internalZ.object({token:import_lazy_zod120.internalZ.string(),session:stateSessionSchema2,requestType:import_lazy_zod120.internalZ.enum(["initialize","message","elicitResult","sseListener","extApps"]).optional()});name27="handle:streamable-http";({Stage:Stage27}=FlowHooksOf(name27));HandleStreamableHttpFlow=class extends FlowBase{name=name27;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const logger=this.scopeLogger.child("handle:streamable-http:parseInput");const body=request2.body;const isInitialize2=body?.method==="initialize";const createSession=()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("streamable-http",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})};let sessionResolution;if(isInitialize2){if(authorization.session?.id){sessionResolution={session:authorization.session,createdNew:false,responded404:false}}else{sessionResolution={session:createSession(),createdNew:true,responded404:false}}}else{sessionResolution=resolveStreamableHttpSession({rawHeader:request2.headers?.["mcp-session-id"],authorizationSession:authorization.session,createSession})}if(sessionResolution.responded404||!sessionResolution.session){logger.warn("parseInput: mcp-session-id is not a session this server verified");this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=sessionResolution.session;this.state.set(stateSchema24.parse({token,session}));logger.verbose("parseInput: session resolved",{sessionId:session.id?.slice(0,20)})}async router(){const{request:request2}=this.rawInput;const logger=this.scopeLogger.child("handle:streamable-http:router");const classification=classifyStreamableHttpRequest({method:request2.method,body:request2.body});if("error"in classification){logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"));return}this.state.set("requestType",classification.requestType);if(classification.requestType==="sseListener"){logger.verbose("router: requestType=sseListener, method=GET")}else if(classification.requestType==="initialize"){logger.verbose("router: requestType=initialize, method=POST")}else if(classification.requestType==="extApps"){const method=request2.body?.method;logger.verbose(`router: requestType=extApps, method=${method}`)}else if(classification.requestType==="elicitResult"){logger.verbose("router: requestType=elicitResult, method=POST")}else{const method=request2.body?.method;logger.verbose(`router: requestType=message, method=${method}`)}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("handle:streamable-http:onInitialize");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.info("onInitialize: creating transport",{sessionId:session.id?.slice(0,20),hasToken:!!token,tokenPrefix:token?.slice(0,10)});try{const authorization=request2[ServerRequestTokens.auth];syncStreamableHttpAuthorizationSession(authorization,session);const transport=await transportService.createTransporter("streamable-http",token,session.id,response);const isReinitialize=!!request2[ServerRequestTokens.reinitialize];if(transport.isInitialized){logger.info("onInitialize: transport already initialized, resetting for re-initialization",{sessionId:session.id?.slice(0,20),reinitialize:isReinitialize});if(!resetInitializedTransportForReinit(transport)){const requestId=request2.body?.id??null;logger.error("onInitialize: transport still initialized after reset \u2014 cannot re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(buildReinitFailedResponse(session.id,requestId));return}}applyNodeAffinity(response,request2);logger.info("onInitialize: transport created, calling initialize");await transport.initialize(request2,response);logger.info("onInitialize: completed successfully");this.handled()}catch(error){if(error instanceof FlowControl){throw error}logger.error("onInitialize: failed",{error:error instanceof Error?error.message:String(error),stack:error instanceof Error?error.stack:void 0});throw error}}async onElicitResult(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onElicitResult");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onElicitResult: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onElicitResult: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onElicitResult: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onElicitResult: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onElicitResult: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session not found"));return}await transport.handleRequest(request2,response);if(!response.writableEnded){response.status(202).json({jsonrpc:"2.0",result:{}})}this.handled()}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onMessage: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});const transportLookup=await lookupStreamableHttpTransport({transportService,token,sessionId:session.id,response});if(transportLookup.kind!=="transport"){const body=request2.body;if(transportLookup.recreationError){logger.warn("Failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(transportLookup.recreationError,session.id)})}if(transportLookup.kind==="session-expired"){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"])});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"]),userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const transport=transportLookup.transport;logger.verbose("onMessage: transport resolved",{source:transportLookup.source});try{await transport.handleRequest(request2,response);this.handled()}catch(error){if(!(error instanceof FlowControl)){const body=request2.body;logger.error("handleRequest failed",{error:error instanceof Error?{name:error.name,message:error.message,stack:error.stack}:error,method:body?.["method"],id:body?.["id"],sessionId:session.id?.slice(0,20)})}throw error}}async onSseListener(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onSseListener");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.info("Recreating transport from Redis session for SSE listener",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("Failed to recreate transport from stored session for SSE listener",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onSseListener: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.notFound("Session not found"));return}await transport.handleRequest(request2,response);this.handled()}async onExtApps(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onExtApps");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const message=request2.body;const isNotification=!("id"in message);if(this.scope.metadata.extApps?.enabled===false){const rpc=request2.body;logger.verbose("onExtApps: ext-apps disabled by config",{method:rpc?.method});if(isNotification){response.status(202).end();this.handled();return}response.status(200).json({jsonrpc:"2.0",id:rpc?.id??null,error:{code:-32601,message:`Method not found: ${rpc?.method}`}});this.handled();return}logger.verbose("onExtApps: starting",{sessionId:session.id?.slice(0,20),method:request2.body?.method});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onExtApps: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onExtApps: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onExtApps: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,session.id);if(wasCreated){logger.info("onExtApps: session expired - client should re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("onExtApps: session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const configuredCapabilities=this.scope.metadata.extApps?.hostCapabilities;const hostCapabilities={serverToolProxy:configuredCapabilities?.serverToolProxy??true,logging:configuredCapabilities?.logging??true,...configuredCapabilities,openLink:false,modelContextUpdate:false,widgetTools:false};const unsupported=["openLink","modelContextUpdate","widgetTools"].filter(key=>configuredCapabilities?.[key]===true);if(unsupported.length>0){logger.warn(`onExtApps: extApps.hostCapabilities ${unsupported.join(", ")} are not supported yet and are not advertised`)}const{user,scopes,claims:claims3}=request2[ServerRequestTokens.auth];const handler=createExtAppsMessageHandler({context:{sessionId:session.id,logger:this.scope.logger,callTool:async(name59,args)=>{const result=await this.scope.runFlow("tools:call-tool",{request:{method:"tools/call",params:{name:name59,arguments:args}},ctx:{authInfo:{sessionId:session.id,sessionIdPayload:session.payload,token,user,scopes:Array.isArray(scopes)?[...scopes]:[],...claims3?{claims:structuredClone(claims3)}:{},clientId:user?.sub??""},surface:mcpRequestSurface(this.scope),_skipUI:true}});const parsed=import_protocol67.CallToolResultSchema.safeParse(result);if(parsed.success){return parsed.data}throw new InternalMcpError("Tool call returned invalid result format")}},hostCapabilities});if(isNotification){await handler.handleNotification(message);response.status(202).end();this.handled();return}const jsonRpcResponse=await handler.handleRequest(message);response.status(200).json(jsonRpcResponse);this.handled()}};__decorateClass([Stage27("applyNodeHeaders")],HandleStreamableHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage27("parseInput")],HandleStreamableHttpFlow.prototype,"parseInput",1);__decorateClass([Stage27("router")],HandleStreamableHttpFlow.prototype,"router",1);__decorateClass([Stage27("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleStreamableHttpFlow.prototype,"onInitialize",1);__decorateClass([Stage27("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleStreamableHttpFlow.prototype,"onElicitResult",1);__decorateClass([Stage27("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleStreamableHttpFlow.prototype,"onMessage",1);__decorateClass([Stage27("onSseListener",{filter:({state:{requestType}})=>requestType==="sseListener"})],HandleStreamableHttpFlow.prototype,"onSseListener",1);__decorateClass([Stage27("onExtApps",{filter:({state:{requestType}})=>requestType==="extApps"})],HandleStreamableHttpFlow.prototype,"onExtApps",1);HandleStreamableHttpFlow=__decorateClass([FrontMcpFlow({name:name27,plan:plan27,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStreamableHttpFlow)}});function normalizeRequestHeaders(headers){const out={};if(!headers)return out;for(const[name59,value]of Object.entries(headers)){if(typeof value==="string")out[name59.toLowerCase()]=value;else if(Array.isArray(value))out[name59.toLowerCase()]=value.map(String);else if(typeof value==="number")out[name59.toLowerCase()]=String(value)}return out}function serializeRelayRequest(request2){const raw=request2;const url=typeof raw.originalUrl==="string"&&raw.originalUrl?raw.originalUrl:raw.url??"/";const queryIndex=url.indexOf("?");const path4=typeof raw.path==="string"&&raw.path?raw.path:queryIndex>=0?url.slice(0,queryIndex):url;return{method:(raw.method??"GET").toUpperCase(),url,path:path4,headers:normalizeRequestHeaders(raw.headers),query:raw.query&&typeof raw.query==="object"?{...raw.query}:{},...raw.body!==void 0?{body:raw.body}:{},...typeof raw.protocol==="string"?{protocol:raw.protocol}:{},...raw.socket?.encrypted?{encrypted:true}:{},...typeof raw.socket?.remoteAddress==="string"?{peerAddress:raw.socket.remoteAddress}:{}}}function relayedFrom(request2){const value=request2[ServerRequestTokens.relayedFrom];return typeof value==="string"?value:void 0}function isRelayedRequest(request2){return relayedFrom(request2)!==void 0}function createRelayedServerRequest(relayed,sourceNodeId){const headers=normalizeRequestHeaders(relayed.headers);const rawHeaders=[];for(const[name59,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])rawHeaders.push(name59,item)}const socket={remoteAddress:relayed.peerAddress,encrypted:relayed.encrypted===true,destroyed:false,destroy(){socket.destroyed=true},destroySoon(){socket.destroyed=true}};const request2=Object.assign(new RelayEmitter,{method:relayed.method,url:relayed.url,originalUrl:relayed.url,path:relayed.path,headers,rawHeaders,query:relayed.query??{},body:relayed.body,protocol:relayed.protocol??(socket.encrypted?"https":"http"),secure:(relayed.protocol??(socket.encrypted?"https":"http"))==="https",httpVersion:"1.1",httpVersionMajor:1,httpVersionMinor:1,complete:true,readable:false,readableEnded:false,aborted:false,errored:null,destroyed:false,socket,connection:socket,resume(){if(!request2.readableEnded){request2.readableEnded=true;queueMicrotask(()=>request2.emit("end"))}return request2},pause(){return request2},destroy(){request2.destroyed=true}});if(relayed.body!==void 0&&typeof Buffer!=="undefined"){const text=typeof relayed.body==="string"?relayed.body:JSON.stringify(relayed.body);Object.assign(request2,{rawBody:Buffer.from(text)})}request2[ServerRequestTokens.relayedFrom]=sourceNodeId;return request2}function encodeBytes(bytes){if(bytes.byteLength===0)return void 0;try{return{data:utf8Decoder.decode(bytes),encoding:"utf8"}}catch{return{data:(0,import_utils145.base64Encode)(bytes),encoding:"base64"}}}function encodeRelayChunk(chunk,encoding){if(chunk===void 0||chunk===null)return void 0;if(typeof chunk==="string"){if(chunk.length===0)return void 0;if(encoding==="base64")return{data:chunk,encoding:"base64"};return{data:chunk,encoding:"utf8"}}if(chunk instanceof Uint8Array)return encodeBytes(chunk);if(chunk instanceof ArrayBuffer)return encodeBytes(new Uint8Array(chunk));const text=String(chunk);return text.length>0?{data:text,encoding:"utf8"}:void 0}function decodeRelayChunk(chunk){return chunk.encoding==="base64"?(0,import_utils145.base64Decode)(chunk.data):chunk.data}function isFlatHeaderList(headers){return Array.isArray(headers)}var import_utils145,RelayEmitter,utf8Decoder,HOP_BY_HOP_HEADERS2,RelayServerResponse;var init_relay_http=__esm({"libs/sdk/src/transport/relay/relay-http.ts"(){"use strict";import_utils145=require("@frontmcp/utils");init_common();init_http_location_utils();RelayEmitter=class{listeners=new Map;on(event,listener){const list=this.listeners.get(event)??[];list.push(listener);this.listeners.set(event,list);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapper=(...args)=>{this.off(event,wrapper);listener(...args)};wrapper.listener=listener;return this.on(event,wrapper)}off(event,listener){const list=this.listeners.get(event);if(!list)return this;const index=list.findIndex(l=>l===listener||l.listener===listener);if(index>=0)list.splice(index,1);if(list.length===0)this.listeners.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listeners.clear();else this.listeners.delete(event);return this}listenerCount(event){return this.listeners.get(event)?.length??0}emit(event,...args){const list=this.listeners.get(event);if(!list||list.length===0)return false;for(const listener of[...list])listener(...args);return true}};utf8Decoder=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});HOP_BY_HOP_HEADERS2=new Set(["connection","keep-alive","transfer-encoding","upgrade"]);RelayServerResponse=class extends RelayEmitter{constructor(sink){super();this.sink=sink}sink;statusCode=200;statusMessage="";headersSent=false;writableEnded=false;writableFinished=false;destroyed=false;headerMap=new Map;get writable(){return!this.writableEnded&&!this.destroyed}get finished(){return this.writableEnded}setHeader(name59,value){if(this.headersSent)return this;this.headerMap.set(name59.toLowerCase(),Array.isArray(value)?value.map(String):String(value));return this}getHeader(name59){return this.headerMap.get(name59.toLowerCase())}getHeaders(){return Object.fromEntries(this.headerMap)}getHeaderNames(){return[...this.headerMap.keys()]}hasHeader(name59){return this.headerMap.has(name59.toLowerCase())}removeHeader(name59){if(!this.headersSent)this.headerMap.delete(name59.toLowerCase())}writeHead(statusCode,reasonOrHeaders,maybeHeaders){if(this.headersSent)return this;this.statusCode=statusCode;let headers;if(typeof reasonOrHeaders==="string"){this.statusMessage=reasonOrHeaders;headers=maybeHeaders}else{headers=reasonOrHeaders}if(isFlatHeaderList(headers)){for(let i=0;i+1<headers.length;i+=2)this.setHeader(headers[i],headers[i+1])}else if(headers){for(const[name59,value]of Object.entries(headers)){if(value!==void 0)this.setHeader(name59,value)}}this.sendHead();return this}flushHeaders(){this.sendHead()}status(code){this.statusCode=code;return this}json(body){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/json; charset=utf-8");return this.end(JSON.stringify(body))}send(body){if(body===void 0||body===null)return this.end();if(typeof body==="string"){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","text/html; charset=utf-8");return this.end(body)}if(body instanceof Uint8Array){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/octet-stream");return this.end(body)}return this.json(body)}redirect(statusOrUrl,maybeUrl){const status=typeof statusOrUrl==="number"?statusOrUrl:302;const location=typeof statusOrUrl==="string"?statusOrUrl:maybeUrl??"/";this.statusCode=status;this.setHeader("Location",toLocationHeader(location));return this.end()}write(chunk,encodingOrCallback,callback){const cb=typeof encodingOrCallback==="function"?encodingOrCallback:callback;if(!this.writable)return false;this.sendHead();const encoded=encodeRelayChunk(chunk,typeof encodingOrCallback==="string"?encodingOrCallback:void 0);if(encoded)this.sink.data(encoded);if(typeof cb==="function")cb();return true}end(chunk,encodingOrCallback,callback){let data=chunk;let encoding=encodingOrCallback;let cb=callback;if(typeof data==="function"){cb=data;data=void 0;encoding=void 0}else if(typeof encoding==="function"){cb=encoding;encoding=void 0}if(this.writableEnded||this.destroyed){if(typeof cb==="function")cb();return this}this.sendHead();const encoded=encodeRelayChunk(data,typeof encoding==="string"?encoding:void 0);if(encoded)this.sink.data(encoded);this.writableEnded=true;this.sink.end();this.writableFinished=true;this.emit("finish");this.emit("close");if(typeof cb==="function")cb();return this}destroy(error){if(this.destroyed)return this;this.destroyed=true;if(error&&this.listenerCount("error")>0)this.emit("error",error);if(!this.writableFinished)this.emit("close");return this}cork(){}uncork(){}setTimeout(){return this}asServerResponse(){return this}sendHead(){if(this.headersSent||this.destroyed)return;this.headersSent=true;const headers={};for(const[name59,value]of this.headerMap){if(!HOP_BY_HOP_HEADERS2.has(name59))headers[name59]=value}this.sink.head(this.statusCode,headers)}}}});var LocalTransporter;var init_transport_local=__esm({"libs/sdk/src/transport/transport.local.ts"(){"use strict";init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_transport_error();LocalTransporter=class{constructor(scope,key,res,onDispose){this.onDispose=onDispose;this.type=key.type;this.tokenHash=key.tokenHash;const defaultOnDispose=()=>{};switch(this.type){case"sse":this.adapter=new TransportSSEAdapter(scope,key,onDispose??defaultOnDispose,res);break;case"streamable-http":case"stateless-http":this.adapter=new TransportStreamableHttpAdapter(scope,key,onDispose??defaultOnDispose,res);break;default:throw new UnsupportedTransportTypeError(this.type)}}onDispose;type;tokenHash;sessionId;adapter;ping(timeoutMs){throw new MethodNotImplementedError("LocalTransporter","ping")}async handleRequest(req,res){try{await this.adapter.handleRequest(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}async ready(){return this.adapter.ready}async initialize(req,res){try{await this.adapter.ready;return this.adapter.initialize(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}get isInitialized(){return this.adapter.isInitialized}markAsInitialized(){this.adapter.markAsInitialized()}resetForReinitialization(){this.adapter.resetForReinitialization()}reregisterServer(){this.adapter.reregisterServer()}async destroy(reason){try{await this.adapter.destroy(reason)}finally{this.onDispose?.()}}}}});var RemoteTransporter;var init_transport_remote=__esm({"libs/sdk/src/transport/transport.remote.ts"(){"use strict";init_transport_errors();init_transport_error();RemoteTransporter=class{constructor(key,bus,location){this.key=key;this.bus=bus;this.location=location;this.type=key.type;this.tokenHash=key.tokenHash;this.sessionId=key.sessionId}key;bus;location;type;tokenHash;sessionId;get ownerNodeId(){return this.location.nodeId}ping(_timeoutMs){throw new MethodNotImplementedError("RemoteTransporter","ping")}initialize(req,res){return this.relay(req,res)}handleRequest(req,res){return this.relay(req,res)}async destroy(reason){await this.bus.destroyRemote(this.key,reason)}get isInitialized(){return true}markAsInitialized(){}resetForReinitialization(){}reregisterServer(){}async relay(req,res){try{await this.bus.proxyRequest(this.location,this.sessionId,req,res)}catch(error){if(!(error instanceof SessionOwnerUnreachableError)||res.headersSent)throw error;const requestId=req.body?.id??null;res.setHeader("Retry-After",String(error.retryAfterSeconds));res.status(error.statusCode).json(rpcError(error.getPublicMessage(),requestId))}}}}});var import_utils146,SESSION_STORE_RETRY_BASE_MS,SESSION_STORE_RETRY_MAX_MS,DEFAULT_SESSION_CHECK_TIMEOUT_MS,BUS_REFRESH_INTERVAL_MS,MAX_ROUTABLE_SESSION_ID_LENGTH,RELAYABLE_TYPES,TransportService;var init_transport_registry=__esm({"libs/sdk/src/transport/transport.registry.ts"(){"use strict";import_utils146=require("@frontmcp/utils");init_session_store_factory();init_session_id_utils();init_auth_info_utils();init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_handle_mcp_20260728_flow();init_handle_sse_flow();init_handle_stateless_http_flow();init_handle_streamable_http_flow();init_relay_http();init_transport_local();init_transport_remote();init_transport_types();SESSION_STORE_RETRY_BASE_MS=1e3;SESSION_STORE_RETRY_MAX_MS=3e4;DEFAULT_SESSION_CHECK_TIMEOUT_MS=500;BUS_REFRESH_INTERVAL_MS=15*60*1e3;MAX_ROUTABLE_SESSION_ID_LENGTH=4096;RELAYABLE_TYPES=new Set(["streamable-http","sse"]);TransportService=class{ready;byType=new Map;distributed;bus;scope;sessionHistory=new Map;MAX_SESSION_HISTORY=1e4;sessionStore;persistenceConfig;pendingStoreConfig;backendKind;transportKeyPrefix="mcp:transport:";sessionStoreConfigured=false;creationMutex=new Map;async newLocalTransporter(key,res,onDispose){if(key.type==="streamable-http"||key.type==="stateless-http"){await loadStreamableHttpTransport()}else if(key.type==="sse"){await loadSseTransport()}return new LocalTransporter(this.scope,key,res,onDispose)}getDefaultTtlMs(){if(this.resolvedTtlMs!==void 0)return this.resolvedTtlMs;return typeof this.persistenceConfig==="object"?this.persistenceConfig?.defaultTtlMs:void 0}resolvedTtlMs;storeRetryConfig;storeRetryTimer;storeRetryAttempt=0;destroyed=false;lastTtlRefreshAt=new Map;lastBusRefreshAt=new Map;localSessionIds=new Map;ownershipGeneration=new Map;relinquishing=new Set;storedLocalSessions=new Set;sessionCheckTimeoutMs;pendingSessionChecks=new Map;getSessionKeyPrefix(){return`${this.transportKeyPrefix}session:`}constructor(scope,persistenceConfig,bus){this.scope=scope;this.persistenceConfig=persistenceConfig;this.distributed=!!bus;this.bus=bus;this.sessionCheckTimeoutMs=(persistenceConfig!==false?persistenceConfig?.sessionCheckTimeoutMs:void 0)??DEFAULT_SESSION_CHECK_TIMEOUT_MS;if(persistenceConfig!==false&&persistenceConfig?.sqlite){this.sessionStoreConfigured=true;this.backendKind="sqlite";const sqliteConfig=persistenceConfig.sqlite;this.transportKeyPrefix="mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??36e5;this.pendingStoreConfig={sqlite:sqliteConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info("[TransportService] sqlite session store will be initialized for transport persistence")}else if(persistenceConfig!==false&&persistenceConfig?.redis){this.sessionStoreConfigured=true;const redisConfig=persistenceConfig.redis;const providerType="provider"in redisConfig?redisConfig.provider:"redis";this.backendKind=providerType==="vercel-kv"?"vercel-kv":"redis";this.transportKeyPrefix=redisConfig.keyPrefix??"mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??redisConfig.defaultTtlMs??36e5;this.pendingStoreConfig={...redisConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info(`[TransportService] ${providerType} session store will be initialized for transport persistence`)}this.storeRetryConfig=this.pendingStoreConfig;this.ready=this.initialize()}async initialize(){if(this.pendingStoreConfig){const connected=await this.connectSessionStore();if(!connected&&this.backendKind!=="sqlite")this.scheduleSessionStoreRetry()}await this.scope.registryFlows(HandleStreamableHttpFlow,HandleSseFlow,HandleStatelessHttpFlow,HandleMcp20260728Flow)}async connectSessionStore(){const storeConfig=this.pendingStoreConfig??this.storeRetryConfig;if(!storeConfig)return false;try{const store=await createSessionStore(storeConfig,this.scope.logger.child("SessionStore"));this.sessionStore=store;this.pendingStoreConfig=void 0}catch(error){const err=error;this.scope.logger.error("[TransportService] Failed to create session store - session persistence disabled",{error:err.message,cause:err.cause?.message});return false}const isConnected=this.sessionStore?.ping?await this.sessionStore.ping():true;if(!isConnected){const providerType=this.backendKind??"redis";this.scope.logger.error(`[TransportService] Failed to connect to ${providerType} - session persistence disabled`);await this.teardownSessionStore().catch(()=>void 0);return false}this.scope.logger.info("[TransportService] Session store connection validated successfully");return true}scheduleSessionStoreRetry(){if(this.destroyed||this.storeRetryTimer)return;const delay=Math.min(SESSION_STORE_RETRY_MAX_MS,SESSION_STORE_RETRY_BASE_MS*2**this.storeRetryAttempt);this.storeRetryAttempt++;this.storeRetryTimer=setTimeout(()=>{this.storeRetryTimer=void 0;void this.retrySessionStore()},delay);this.storeRetryTimer.unref?.()}async retrySessionStore(){if(this.destroyed||this.sessionStore)return;const connected=await this.connectSessionStore().catch(()=>false);if(this.destroyed){await this.teardownSessionStore().catch(()=>void 0);return}if(connected){this.storeRetryAttempt=0;this.scope.logger.info("[TransportService] Session store recovered after startup failure");return}this.scheduleSessionStoreRetry()}async destroy(){this.destroyed=true;if(this.storeRetryTimer){clearTimeout(this.storeRetryTimer);this.storeRetryTimer=void 0}this.lastTtlRefreshAt.clear();this.lastBusRefreshAt.clear();this.ownershipGeneration.clear();this.storedLocalSessions.clear();await this.teardownSessionStore()}async teardownSessionStore(){if(!this.sessionStore)return;const teardown=this.sessionStore.disconnect??this.sessionStore.close;if(!teardown){this.sessionStore=void 0;return}try{await Promise.resolve(teardown.call(this.sessionStore));this.scope.logger.info("[TransportService] Session store disconnected",{backendKind:this.backendKind??"unknown"})}catch(error){this.scope.logger.warn("[TransportService] Error disconnecting session store",{error:error.message,backendKind:this.backendKind??"unknown"})}finally{this.sessionStore=void 0}}async pingSessionStore(){if(!this.sessionStoreConfigured)return true;if(!this.sessionStore)return false;if(typeof this.sessionStore.ping==="function"){return this.sessionStore.ping()}return true}isSessionStoreConfigured(){return this.sessionStoreConfigured}getBackendKind(){return this.backendKind}sessionStoreLabel(){switch(this.backendKind){case"sqlite":return"SQLite";case"vercel-kv":return"Vercel KV";case"redis":return"Redis";default:return"the session store"}}refreshStoredSessionTtl(sessionId){const store=this.sessionStore;const ttlMs=this.getDefaultTtlMs();if(!store||!ttlMs||this.backendKind!=="redis"&&this.backendKind!=="vercel-kv")return;const now=Date.now();const last=this.lastTtlRefreshAt.get(sessionId);if(last!==void 0&&now-last<Math.max(1e3,Math.floor(ttlMs/4)))return;this.lastTtlRefreshAt.set(sessionId,now);store.get(sessionId).catch(err=>{this.scope.logger.warn("[TransportService] Failed to refresh session TTL",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getTransporter(type,token,sessionId){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local&&await this.holdsLocalSession(sessionId)){this.refreshStoredSessionTtl(sessionId);this.refreshBusAdvertisement(key);return local}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){if(await this.isNodeAlive(location.nodeId)){return new RemoteTransporter(key,this.bus,location)}this.scope.logger.info("[HA] Session owner is gone \u2014 the session will be taken over",{sessionId:sessionId.slice(0,20),previousNodeId:location.nodeId})}}return void 0}async findRemoteSessionOwner(request2){if(!this.distributed||!this.bus?.canRelay()||isRelayedRequest(request2))return void 0;const sessionId=sessionIdPresentedBy(request2);if(!sessionId||sessionId.length>MAX_ROUTABLE_SESSION_ID_LENGTH)return void 0;if(!isDeploymentSessionId(sessionId))return void 0;try{if(this.localSessionIds.has(sessionId)&&await this.holdsLocalSession(sessionId))return void 0;const owner=await this.lookupSessionOwner(sessionId);if(!owner||owner.nodeId===(0,import_utils146.getMachineId)())return void 0;return await this.isNodeAlive(owner.nodeId)?owner:void 0}catch(error){this.scope.logger.warn("[HA] Could not resolve the session owner \u2014 serving the request here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return void 0}}async lookupSessionOwner(sessionId){if(!this.bus)return void 0;const advertised=await this.bus.lookupOwner(sessionId);if(advertised)return advertised;const stored=this.sessionStore?await this.sessionStore.get(sessionId):null;const nodeId=stored?.session?.nodeId;if(!nodeId)return void 0;return{nodeId,channel:this.bus.channelOf(nodeId)}}async relayToSessionOwner(location,request2,response){if(!this.bus)throw new InvalidTransportSessionError("Session relay requires the distributed transport bus.");const sessionId=sessionIdPresentedBy(request2)??"";await this.bus.proxyRequest(location,sessionId,request2,response)}async adoptClaimedSession(sessionId,previousNodeId,info){if(!this.bus)return;const type=info.protocol;if(!info.authorizationId||type!=="streamable-http"&&type!=="sse")return;await this.bus.advertise({type,token:"",tokenHash:info.authorizationId,sessionId});this.scope.logger.info("[HA] Adopted an orphaned session \u2014 this node now serves it",{sessionId:sessionId.slice(0,20),previousNodeId})}async destroyLocalSession(sessionId,reason){let found=false;for(const[type,typeBucket]of[...this.byType.entries()]){if(!RELAYABLE_TYPES.has(type))continue;for(const tokenBucket of[...typeBucket.values()]){const transporter=tokenBucket.get(sessionId);if(!transporter)continue;found=true;await transporter.destroy(reason)}}return found}async holdsLocalSession(sessionId){if(!this.distributed)return this.isStillStored(sessionId);const haManager=this.scope.haManager;const store=this.sessionStore;if(!haManager||!store)return true;const generation=haManager.livenessGeneration();if(generation!==void 0&&this.ownershipGeneration.get(sessionId)===generation)return true;let ownerNodeId;try{ownerNodeId=(await this.withSessionCheckTimeout(`get:${sessionId}`,()=>store.get(sessionId)))?.session?.nodeId}catch(error){this.scope.logger.warn("[HA] Could not confirm this node still owns the session \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}if(!ownerNodeId||ownerNodeId===(0,import_utils146.getMachineId)()){if(generation!==void 0)this.ownershipGeneration.set(sessionId,generation);return true}this.scope.logger.warn("[HA] Another node took this session over while this node was unreachable \u2014 dropping it here",{sessionId:sessionId.slice(0,20),ownerNodeId});this.relinquishing.add(sessionId);try{await this.destroyLocalSession(sessionId,"the session moved to another node")}finally{this.relinquishing.delete(sessionId)}return false}async isStillStored(sessionId){const store=this.sessionStore;if(!store||!this.storedLocalSessions.has(sessionId))return true;try{if(await this.withSessionCheckTimeout(`exists:${sessionId}`,()=>store.exists(sessionId)))return true}catch(error){this.scope.logger.warn("[TransportService] Could not confirm the session is still stored \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}this.scope.logger.info("[TransportService] The stored session is gone \u2014 dropping its transport here",{sessionId:sessionId.slice(0,20)});await this.destroyLocalSession(sessionId,"the session was deleted");return false}withSessionCheckTimeout(key,issueRead){let read=this.pendingSessionChecks.get(key);if(!read){read=issueRead().finally(()=>this.pendingSessionChecks.delete(key));this.pendingSessionChecks.set(key,read)}const timeoutMs=this.sessionCheckTimeoutMs;let timer;const timedOut=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error(`The session store did not answer within ${timeoutMs} ms`)),timeoutMs);timer.unref?.()});return Promise.race([read,timedOut]).finally(()=>clearTimeout(timer))}async isNodeAlive(nodeId){const haManager=this.scope.haManager;if(!haManager)return true;try{return await haManager.isNodeAlive(nodeId)}catch{return true}}refreshBusAdvertisement(key){if(!this.distributed||!this.bus||!RELAYABLE_TYPES.has(key.type))return;const now=Date.now();const last=this.lastBusRefreshAt.get(key.sessionId);if(last!==void 0&&now-last<BUS_REFRESH_INTERVAL_MS)return;this.lastBusRefreshAt.set(key.sessionId,now);this.bus.advertise(key).catch(err=>{this.scope.logger.warn("[HA] Failed to refresh the session advertisement",{sessionId:key.sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getStoredSession(type,token,sessionId,options){if(!this.sessionStore||type!=="streamable-http"&&type!=="sse")return void 0;const tokenHash=this.sha256(token);const stored=await this.sessionStore.get(sessionId);if(!stored)return void 0;if(stored.authorizationId!==tokenHash){this.scope.logger.warn("[TransportService] Session token mismatch during lookup",{sessionId:sessionId.slice(0,20),storedTokenHash:stored.authorizationId.slice(0,8),requestTokenHash:tokenHash.slice(0,8)});return void 0}if(options?.clientFingerprint&&stored.session.clientFingerprint){if(stored.session.clientFingerprint!==options.clientFingerprint){this.scope.logger.warn("[TransportService] Client fingerprint mismatch",{sessionId:sessionId.slice(0,20),storedFingerprint:stored.session.clientFingerprint.slice(0,8),requestFingerprint:options.clientFingerprint.slice(0,8)});if(!options.warnOnFingerprintMismatch){return void 0}}}return stored}async recreateTransporter(type,token,sessionId,storedSession,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const recreationPromise=this.doRecreateTransporter(key,sessionId,storedSession,res);this.creationMutex.set(mutexKey,recreationPromise);try{return await recreationPromise}catch(error){this.scope.logger.error("[TransportService] Failed to recreate transport from stored session",{sessionId:sessionId.slice(0,20),error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}finally{this.creationMutex.delete(mutexKey)}}async remoteOwnerTransporter(key,ownerNodeId){if(!this.distributed||!this.bus)return void 0;if(!await this.isNodeAlive(ownerNodeId))return void 0;return new RemoteTransporter(key,this.bus,{nodeId:ownerNodeId,channel:this.bus.channelOf(ownerNodeId)})}async doRecreateTransporter(key,sessionId,storedSession,res){const existing=this.lookupLocal(key);if(existing)return existing;this.scope.logger.info("[TransportService] Recreating transport from stored session",{sessionId:sessionId.slice(0,20),protocol:storedSession.session.protocol,createdAt:storedSession.createdAt});const currentNodeId=(0,import_utils146.getMachineId)();const ownerNodeId=storedSession.session.nodeId;let latestSession=storedSession;if(this.scope.haManager&&ownerNodeId&&ownerNodeId!==currentNodeId){const remote=await this.remoteOwnerTransporter(key,ownerNodeId);if(remote)return remote;const sessionKey=`${this.getSessionKeyPrefix()}${sessionId}`;const result=await this.scope.haManager.attemptTakeover(sessionKey,ownerNodeId);if(result.claimed){latestSession={...storedSession,reassignedAt:result.reassignedAt,reassignedFrom:ownerNodeId};this.scope.logger.info("[HA] Took over session from a stopped node",{sessionId:sessionId.slice(0,20),previousNodeId:ownerNodeId})}else{const current=this.sessionStore?await this.sessionStore.get(sessionId):null;const newOwner=current?.session?.nodeId;if(newOwner!==currentNodeId){const relayed=newOwner?await this.remoteOwnerTransporter(key,newOwner):void 0;if(relayed)return relayed;this.scope.logger.debug("[HA] Session already claimed by another pod",{sessionId:sessionId.slice(0,20)});throw new SessionClaimConflictError(sessionId)}if(current)latestSession=current}}const historyKey=this.makeHistoryKey(key.type,key.tokenHash,sessionId);this.sessionHistory.set(historyKey,storedSession.createdAt);const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();if(storedSession.initialized!==false){transporter.markAsInitialized()}this.insertLocal(key,transporter);if(sessionStore)this.storedLocalSessions.add(sessionId);if(storedSession.clientCapabilities){this.scope.notifications.setClientCapabilities(sessionId,storedSession.clientCapabilities);this.scope.logger.verbose("[TransportService] Restored client capabilities from stored session",{sessionId:sessionId.slice(0,20)})}if(sessionStore){const updatedSession={...latestSession,session:{...latestSession.session,nodeId:currentNodeId},lastAccessedAt:Date.now()};sessionStore.set(sessionId,updatedSession,defaultTtlMs).catch(err=>{this.scope.logger.warn(`[TransportService] Failed to update session in ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}async createTransporter(type,token,sessionId,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const creationPromise=this.doCreateTransporter(key,sessionId,res,type);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateTransporter(key,sessionId,res,type){const existing=this.lookupLocal(key);if(existing)return existing;const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();this.insertLocal(key,transporter);if(sessionStore&&(type==="streamable-http"||type==="sse")){const storedSession={session:{id:sessionId,authorizationId:key.tokenHash,protocol:type==="sse"?"sse":"streamable-http",createdAt:Date.now(),nodeId:(0,import_utils146.getMachineId)()},authorizationId:key.tokenHash,createdAt:Date.now(),lastAccessedAt:Date.now(),initialized:true};sessionStore.set(sessionId,storedSession,defaultTtlMs).then(()=>{if(this.localSessionIds.has(sessionId))this.storedLocalSessions.add(sessionId)},err=>{this.scope.logger.warn(`[TransportService] Failed to persist session to ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}onSessionTransportDisposed(key,sessionId,sessionStore){key.sessionId=sessionId;this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}if(sessionStore&&!this.relinquishing.has(sessionId)){sessionStore.delete(sessionId).catch(()=>void 0)}}async destroyTransporter(type,token,sessionId,reason){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local){await local.destroy(reason);return}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){await this.bus.destroyRemote(key,reason);return}}throw new InvalidTransportSessionError("Invalid session: cannot destroy non-existent transporter.")}async deleteStoredSession(sessionId){if(!this.sessionStore)return;try{await this.sessionStore.delete(sessionId)}catch(err){this.scope.logger.warn(`[TransportService] Failed to delete session from ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)});throw err}}async updateStoredSessionCapabilities(sessionId,clientCapabilities){if(!this.sessionStore)return;try{const stored=await this.sessionStore.get(sessionId);if(!stored){this.scope.logger.verbose("[TransportService] Cannot update capabilities: session not found in store",{sessionId:sessionId.slice(0,20)});return}const updatedSession={...stored,clientCapabilities,lastAccessedAt:Date.now()};const defaultTtlMs=this.getDefaultTtlMs();await this.sessionStore.set(sessionId,updatedSession,defaultTtlMs);this.scope.logger.verbose("[TransportService] Persisted client capabilities to session store",{sessionId:sessionId.slice(0,20)})}catch(err){this.scope.logger.warn("[TransportService] Failed to persist client capabilities",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})}}async getOrCreateAnonymousStatelessTransport(type,res){return this.getOrCreateStatelessTransport(this.keyOf(type,"__anonymous__",STATELESS_SESSION_ID),res)}async getOrCreateAuthenticatedStatelessTransport(type,token,res){return this.getOrCreateStatelessTransport(this.keyOf(type,token,STATELESS_SESSION_ID),res)}async getOrCreateStatelessTransport(key,res){const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:key.type,h:key.tokenHash,s:key.sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2)return pendingCreation2;const creationPromise=this.doCreateStatelessTransport(key,res);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateStatelessTransport(key,res){const transporter=await this.newLocalTransporter(key,res,()=>{this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}});await transporter.ready();this.insertLocal(key,transporter);if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}wasSessionCreated(type,token,sessionId){const tokenHash=this.sha256(token);const historyKey=this.makeHistoryKey(type,tokenHash,sessionId);return this.sessionHistory.has(historyKey)}async wasSessionCreatedAsync(type,token,sessionId){if(this.wasSessionCreated(type,token,sessionId)){return true}if(this.sessionStore&&(type==="streamable-http"||type==="sse")){const stored=await this.getStoredSession(type,token,sessionId);return stored!==void 0}return false}sha256(value){return(0,import_utils146.sha256Hex)(value)}makeHistoryKey(type,tokenHash,sessionId){return JSON.stringify({t:type,h:tokenHash,s:sessionId})}parseHistoryKey(key){try{const parsed=JSON.parse(key);if(typeof parsed.t==="string"&&typeof parsed.h==="string"&&typeof parsed.s==="string"){return{type:parsed.t,tokenHash:parsed.h,sessionId:parsed.s}}return void 0}catch{return void 0}}keyOf(type,token,sessionId,sessionIdSse){return{type,token,tokenHash:this.sha256(token),sessionId,sessionIdSse}}ensureTypeBucket(type){let bucket=this.byType.get(type);if(!bucket){bucket=new Map;this.byType.set(type,bucket)}return bucket}ensureTokenBucket(typeBucket,tokenHash){let bucket=typeBucket.get(tokenHash);if(!bucket){bucket=new Map;typeBucket.set(tokenHash,bucket)}return bucket}lookupLocal(key){const typeBucket=this.byType.get(key.type);if(!typeBucket)return void 0;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return void 0;return tokenBucket.get(key.sessionId)}insertLocal(key,t){const typeBucket=this.ensureTypeBucket(key.type);const tokenBucket=this.ensureTokenBucket(typeBucket,key.tokenHash);if(!tokenBucket.has(key.sessionId)){this.localSessionIds.set(key.sessionId,(this.localSessionIds.get(key.sessionId)??0)+1)}tokenBucket.set(key.sessionId,t);const generation=this.distributed?this.scope.haManager?.livenessGeneration():void 0;if(generation!==void 0)this.ownershipGeneration.set(key.sessionId,generation);const historyKey=this.makeHistoryKey(key.type,key.tokenHash,key.sessionId);this.sessionHistory.set(historyKey,Date.now());if(this.sessionHistory.size>this.MAX_SESSION_HISTORY){const entries=[...this.sessionHistory.entries()].sort((a,b)=>a[1]-b[1]);const targetEvictions=Math.ceil(this.MAX_SESSION_HISTORY*.1);let evicted=0;for(const[histKey]of entries){if(evicted>=targetEvictions)break;const parsed=this.parseHistoryKey(histKey);if(!parsed){this.sessionHistory.delete(histKey);evicted++;continue}const{type,tokenHash,sessionId}=parsed;const typeBucket2=this.byType.get(type);const tokenBucket2=typeBucket2?.get(tokenHash);const hasActiveTransport=tokenBucket2?.has(sessionId)??false;if(!hasActiveTransport){this.sessionHistory.delete(histKey);evicted++}}if(evicted<targetEvictions){this.scope.logger.warn("[TransportService] Session history eviction: unable to free target memory",{targetEvictions,actualEvictions:evicted,currentSize:this.sessionHistory.size,maxSize:this.MAX_SESSION_HISTORY})}}}evictLocal(key){this.lastTtlRefreshAt.delete(key.sessionId);this.lastBusRefreshAt.delete(key.sessionId);const typeBucket=this.byType.get(key.type);if(!typeBucket)return;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return;if(tokenBucket.delete(key.sessionId)){const remaining=(this.localSessionIds.get(key.sessionId)??1)-1;if(remaining>0)this.localSessionIds.set(key.sessionId,remaining);else{this.localSessionIds.delete(key.sessionId);this.ownershipGeneration.delete(key.sessionId);this.storedLocalSessions.delete(key.sessionId)}}if(tokenBucket.size===0)typeBucket.delete(key.tokenHash);if(typeBucket.size===0)this.byType.delete(key.type)}}}});function loadStreamableHttpTransportOnStart(scope){const{enableStreamableHttp,enableStatelessHttp,enableStatefulHttp}=toLegacyProtocolFlags(scope.metadata.transport?.protocol);if(!enableStreamableHttp&&!enableStatelessHttp&&!enableStatefulHttp)return;scope.onServerStarted(()=>{setImmediate(()=>{loadStreamableHttpTransport().catch(error=>scope.logger.verbose("Streamable HTTP transport preload failed",{error}))})})}var init_streamable_http_preload=__esm({"libs/sdk/src/transport/streamable-http-preload.ts"(){"use strict";init_schema7();init_transport_streamable_http_adapter()}});function getErrorMessage(err){if(err instanceof Error)return err.message;return String(err)}function createStorageProbe(name59,adapter){return{name:name59,async check(){const start=Date.now();try{const ok=await adapter.ping();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}function createRemoteAppProbe(appId,provider){return{name:`remote:${appId}`,async check(){const result=provider.getHealthStatus(appId);if(!result||result.status==="unknown"&&result.consecutiveFailures===0){return{status:"degraded",details:{state:"unknown"}}}return{status:result.status==="healthy"?"healthy":result.status==="degraded"?"degraded":"unhealthy",latencyMs:result.latencyMs,...result.error?{error:result.error}:{}}}}}function createTransportSessionProbe(provider){return{name:"session-store",async check(){const start=Date.now();try{const ok=await provider.pingSessionStore();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Session store ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}var init_health_probes=__esm({"libs/sdk/src/health/health.probes.ts"(){"use strict"}});var import_utils147,processStartTime,HealthService;var init_health_service=__esm({"libs/sdk/src/health/health.service.ts"(){"use strict";import_utils147=require("@frontmcp/utils");init_health_probes();processStartTime=Date.now();HealthService=class{probeSources=[];config;serverInfo;scopeView;constructor(config,serverInfo){this.config=config;this.serverInfo=serverInfo}registerProbe(probe2){this.probeSources.push(()=>[probe2])}registerProbeSource(source){this.probeSources.push(source)}autoDiscoverProbes(scope){this.scopeView=scope;if(scope.transportService){this.registerProbe(createTransportSessionProbe(scope.transportService))}for(const app of scope.apps.getApps()){if(app.isRemote&&typeof app.getMcpClient==="function"){const client=app.getMcpClient();if(client&&typeof client.getHealthStatus==="function"){this.registerProbe(createRemoteAppProbe(app.id,client))}}}if(scope.haManager?.isStarted()){const ha=scope.haManager;this.registerProbe({name:"ha",check:async()=>{const alive=await ha.isNodeAlive(ha.getNodeId());return{status:alive?"healthy":"unhealthy",details:{nodeId:ha.getNodeId(),heartbeatActive:alive}}}})}this.registerProbeSource(()=>scope.healthProbes??[]);const userProbes=this.config.probes??[];for(const probe2 of userProbes){if(probe2&&typeof probe2.check==="function"&&typeof probe2.name==="string"){this.registerProbe({name:probe2.name,check:()=>probe2.check()})}}}getHealthz(){const ctx=(0,import_utils147.getRuntimeContext)();return{status:"ok",server:{name:this.serverInfo.name??"unknown",version:this.serverInfo.version??"unknown"},runtime:{platform:ctx.platform,runtime:ctx.runtime,deployment:ctx.deployment,env:ctx.env},uptime:(Date.now()-processStartTime)/1e3}}async getReadyz(){const start=Date.now();const timeoutMs=this.config.readyz?.timeoutMs??5e3;const includeDetails=this.resolveIncludeDetails();const results=await Promise.all(this.getProbes().map(async probe2=>{const result=await this.runProbeWithTimeout(probe2,timeoutMs);return{name:probe2.name,result}}));const hasUnhealthy=results.some(r=>r.result.status==="unhealthy");const catalog=this.computeCatalogInfo();const response={status:hasUnhealthy?"not_ready":"ready",totalLatencyMs:Date.now()-start,catalog};if(includeDetails){const probes={};for(const{name:name59,result}of results){probes[name59]=result}response.probes=probes}return response}getProbeCount(){return this.getProbes().length}getProbes(){return this.probeSources.flatMap(source=>source())}setScopeView(scope){this.scopeView=scope}async runProbeWithTimeout(probe2,timeoutMs){let timeoutId;try{const timeoutPromise=new Promise(resolve4=>{timeoutId=setTimeout(()=>resolve4({status:"unhealthy",latencyMs:timeoutMs,error:`Probe timed out after ${timeoutMs}ms`}),timeoutMs)});return await Promise.race([probe2.check(),timeoutPromise])}catch(err){return{status:"unhealthy",error:err instanceof Error?err.message:String(err)}}finally{if(timeoutId!==void 0){clearTimeout(timeoutId)}}}computeCatalogInfo(){if(!this.scopeView){return{toolsHash:"",toolCount:0,resourceCount:0,promptCount:0,skillCount:0,agentCount:0}}const tools=this.scopeView.tools.getTools(true);const toolNames=tools.map(t=>t.name).sort();const toolsHash=(0,import_utils147.sha256Hex)(toolNames.join(","));return{toolsHash,toolCount:tools.length,resourceCount:this.scopeView.resources.getResources(true).length,promptCount:this.scopeView.prompts.getPrompts(true).length,skillCount:this.scopeView.skills.getSkills(true).length,agentCount:this.scopeView.agents.getAgents().length}}resolveIncludeDetails(){if(this.config.includeDetails!==void 0){return this.config.includeDetails}const ctx=(0,import_utils147.getRuntimeContext)();return ctx.env!=="production"}}}});var health_exports={};__export(health_exports,{HealthService:()=>HealthService,createRemoteAppProbe:()=>createRemoteAppProbe,createStorageProbe:()=>createStorageProbe,createTransportSessionProbe:()=>createTransportSessionProbe,isReadyzEnabled:()=>isReadyzEnabled,registerHealthRoutes:()=>registerHealthRoutes,servedHealthPaths:()=>servedHealthPaths});var init_health2=__esm({"libs/sdk/src/health/index.ts"(){"use strict";init_health_probes();init_health_service();init_health_routes()}});var http_scope_helper_exports={};__export(http_scope_helper_exports,{HealthService:()=>HealthService,HttpIpFilterFlow:()=>HttpIpFilterFlow,HttpRequestFlow:()=>HttpRequestFlow,HttpRouteFlow:()=>HttpRouteFlow,TransportService:()=>TransportService,attachHttpRoutes:()=>attachHttpRoutes,loadStreamableHttpTransportOnStart:()=>loadStreamableHttpTransportOnStart,registerCustomHttpRoutes:()=>registerCustomHttpRoutes,servedHealthPaths:()=>servedHealthPaths});var init_http_scope_helper=__esm({"libs/sdk/src/scope/http-scope.helper.ts"(){"use strict";init_http_route_flow();init_http_route_table();init_http_request_flow();init_http_ip_filter_flow();init_transport_registry();init_streamable_http_preload();init_custom_routes_helper();init_health2()}});var DEFAULT_HA_CONFIG;var init_ha_types=__esm({"libs/sdk/src/ha/ha.types.ts"(){"use strict";init_ha_constants();DEFAULT_HA_CONFIG={heartbeatIntervalMs:1e4,heartbeatTtlMs:3e4,takeoverGracePeriodMs:5e3,redisKeyPrefix:"mcp:ha:",affinityCookieName:DEFAULT_FRONTMCP_NODE_COOKIE,machineIdHeader:DEFAULT_FRONTMCP_MACHINE_ID_HEADER}}});var HeartbeatService;var init_heartbeat_service=__esm({"libs/sdk/src/ha/heartbeat.service.ts"(){"use strict";init_ha_types();HeartbeatService=class{constructor(redis,nodeId,config){this.redis=redis;this.nodeId=nodeId;this.startedAt=Date.now();this.lastBeatAt=this.startedAt;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.intervalMs=config?.heartbeatIntervalMs??DEFAULT_HA_CONFIG.heartbeatIntervalMs;this.ttlMs=config?.heartbeatTtlMs??DEFAULT_HA_CONFIG.heartbeatTtlMs}redis;nodeId;timer;startedAt;keyPrefix;intervalMs;ttlMs;sessionCount=0;lastBeatAt;lapses=0;start(){if(this.timer)return;this.writeHeartbeat();this.timer=setInterval(()=>this.writeHeartbeat(),this.intervalMs);if(this.timer.unref)this.timer.unref()}async stop(){if(this.timer){clearInterval(this.timer);this.timer=void 0}try{await this.redis.del(this.heartbeatKey())}catch{}}setSessionCount(count){this.sessionCount=count}async isAlive(nodeId){const exists=await this.redis.exists(`${this.keyPrefix}heartbeat:${nodeId}`);return exists===1}async getHeartbeat(nodeId){const raw=await this.redis.get(`${this.keyPrefix}heartbeat:${nodeId}`);if(!raw)return null;try{return JSON.parse(raw)}catch{return null}}livenessGeneration(){return Date.now()-this.lastBeatAt>=this.ttlMs?void 0:this.lapses}async getAliveNodes(){const keys=await this.redis.keys(`${this.keyPrefix}heartbeat:*`);return keys.map(key=>key.slice(`${this.keyPrefix}heartbeat:`.length))}heartbeatKey(){return`${this.keyPrefix}heartbeat:${this.nodeId}`}writeHeartbeat(){const value={nodeId:this.nodeId,startedAt:this.startedAt,lastBeat:Date.now(),sessionCount:this.sessionCount};this.redis.set(this.heartbeatKey(),JSON.stringify(value),"PX",this.ttlMs).then(()=>this.recordBeat(value.lastBeat),()=>void 0)}recordBeat(writtenAt){if(Date.now()-this.lastBeatAt>=this.ttlMs)this.lapses++;this.lastBeatAt=Math.max(this.lastBeatAt,writtenAt)}}}});var NotificationRelay;var init_notification_relay=__esm({"libs/sdk/src/ha/notification-relay.ts"(){"use strict";init_ha_types();NotificationRelay=class{constructor(subscriber,publisher,nodeId,config){this.subscriber=subscriber;this.publisher=publisher;this.nodeId=nodeId;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.channel=this.channelOf(nodeId)}subscriber;publisher;nodeId;handler;channel;keyPrefix;channelOf(nodeId){return`${this.keyPrefix}notify:${nodeId}`}async subscribe(handler){this.handler=handler;this.subscriber.removeListener("message",this.onMessage);this.subscriber.on("message",this.onMessage);await this.subscriber.subscribe(this.channel)}async unsubscribe(){this.handler=void 0;this.subscriber.removeListener("message",this.onMessage);try{await this.subscriber.unsubscribe(this.channel)}catch{}}async publish(targetNodeId,sessionId,notification){await this.send(targetNodeId,{kind:"notification",sessionId,notification,sourceNodeId:this.nodeId,timestamp:Date.now()})}async send(targetNodeId,message){return this.publisher.publish(this.channelOf(targetNodeId),JSON.stringify(message))}onMessage=(channel2,raw)=>{if(!this.handler||channel2!==this.channel)return;let message;try{message=JSON.parse(raw)}catch{return}if(!message||typeof message!=="object")return;try{Promise.resolve(this.handler(message)).catch(()=>void 0)}catch{}}}}});async function attemptSessionTakeover(redis,sessionKey,expectedOldNodeId,newNodeId){const reassignedAt=Date.now();const result=await redis.eval(TAKEOVER_LUA,1,sessionKey,expectedOldNodeId,newNodeId,reassignedAt.toString());const claimed=result===1;return{claimed,sessionId:sessionKey,previousNodeId:claimed?expectedOldNodeId:void 0,reassignedAt:claimed?reassignedAt:void 0}}var TAKEOVER_LUA;var init_session_takeover=__esm({"libs/sdk/src/ha/session-takeover.ts"(){"use strict";TAKEOVER_LUA=`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/sdk",
|
|
3
|
-
"version": "1.13.0-rc.
|
|
3
|
+
"version": "1.13.0-rc.2",
|
|
4
4
|
"description": "TypeScript framework for building MCP servers: tools, resources and prompts as decorated classes, with transports, sessions, auth and dependency injection",
|
|
5
5
|
"author": "AgentFront <info@agentfront.dev>",
|
|
6
6
|
"homepage": "https://frontmcp.dev",
|
|
@@ -134,8 +134,8 @@
|
|
|
134
134
|
"peerDependencies": {
|
|
135
135
|
"@anthropic-ai/sdk": "^0.30.0 || ^0.78.0",
|
|
136
136
|
"@enclave-vm/core": "^2.16.0",
|
|
137
|
-
"@frontmcp/observability": "1.13.0-rc.
|
|
138
|
-
"@frontmcp/storage-sqlite": "1.13.0-rc.
|
|
137
|
+
"@frontmcp/observability": "1.13.0-rc.2",
|
|
138
|
+
"@frontmcp/storage-sqlite": "1.13.0-rc.2",
|
|
139
139
|
"@opentelemetry/api": "^1.9.0",
|
|
140
140
|
"@opentelemetry/sdk-trace-base": "^2.8.0",
|
|
141
141
|
"content-type": "^1.0.5",
|
|
@@ -168,13 +168,13 @@
|
|
|
168
168
|
}
|
|
169
169
|
},
|
|
170
170
|
"dependencies": {
|
|
171
|
-
"@frontmcp/auth": "1.13.0-rc.
|
|
172
|
-
"@frontmcp/di": "1.13.0-rc.
|
|
173
|
-
"@frontmcp/guard": "1.13.0-rc.
|
|
174
|
-
"@frontmcp/lazy-zod": "1.13.0-rc.
|
|
175
|
-
"@frontmcp/protocol": "1.13.0-rc.
|
|
176
|
-
"@frontmcp/uipack": "1.13.0-rc.
|
|
177
|
-
"@frontmcp/utils": "1.13.0-rc.
|
|
171
|
+
"@frontmcp/auth": "1.13.0-rc.2",
|
|
172
|
+
"@frontmcp/di": "1.13.0-rc.2",
|
|
173
|
+
"@frontmcp/guard": "1.13.0-rc.2",
|
|
174
|
+
"@frontmcp/lazy-zod": "1.13.0-rc.2",
|
|
175
|
+
"@frontmcp/protocol": "1.13.0-rc.2",
|
|
176
|
+
"@frontmcp/uipack": "1.13.0-rc.2",
|
|
177
|
+
"@frontmcp/utils": "1.13.0-rc.2",
|
|
178
178
|
"@types/cors": "^2.8.17",
|
|
179
179
|
"croner": "11.0.0",
|
|
180
180
|
"ioredis": "^5.8.0",
|
|
@@ -20,6 +20,8 @@ export declare class TransportStreamableHttpAdapter extends LocalTransportAdapte
|
|
|
20
20
|
createTransport(sessionId: string, response: ServerResponse): RecreateableStreamableHTTPServerTransport;
|
|
21
21
|
initialize(req: AuthenticatedServerRequest, res: ServerResponse): Promise<void>;
|
|
22
22
|
handleRequest(req: AuthenticatedServerRequest, res: ServerResponse): Promise<void>;
|
|
23
|
+
/** A destroy without a reason is the client's DELETE: closing the transport aborts the session's in-flight calls. */
|
|
24
|
+
destroy(reason?: string): Promise<void>;
|
|
23
25
|
/**
|
|
24
26
|
* Send an elicitation request to the client.
|
|
25
27
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.streamable-http.adapter.d.ts","sourceRoot":"","sources":["../../../src/transport/adapters/transport.streamable-http.adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE1E,OAAO,EAAE,KAAK,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAG5E,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,KAAK,EAAE,yCAAyC,EAAE,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAKlE,wBAAsB,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC,CAEjE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,GACpC,eAAe,aAAa,EAC5B,WAAW,MAAM,KAChB,CAAC,MAAM,MAAM,CAAC,GAAG,SAEnB,CAAC;AAEF,qBAAa,8BAA+B,SAAQ,qBAAqB,CAAC,yCAAyC,CAAC;IACzG,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,yCAAyC;IA2C1G,UAAU,CAAC,GAAG,EAAE,0BAA0B,EAAE,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA2D/E,aAAa,CAAC,GAAG,EAAE,0BAA0B,EAAE,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBxF;;;;;;;;;;;;;;;;;OAiBG;IACG,iBAAiB,CAAC,CAAC,SAAS,OAAO,EACvC,gBAAgB,EAAE,SAAS,EAC3B,OAAO,EAAE,MAAM,EACf,eAAe,EAAE,CAAC,EAClB,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,YAAY,CAAC,CAAC,SAAS,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC;IAkHlE,IAAa,aAAa,IAAI,OAAO,CAEpC;IAED;;;;OAIG;IACM,wBAAwB,IAAI,IAAI;IAOzC;;;;;;;OAOG;IACM,iBAAiB,IAAI,IAAI;CAOnC"}
|
|
1
|
+
{"version":3,"file":"transport.streamable-http.adapter.d.ts","sourceRoot":"","sources":["../../../src/transport/adapters/transport.streamable-http.adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE1E,OAAO,EAAE,KAAK,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAG5E,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,KAAK,EAAE,yCAAyC,EAAE,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAKlE,wBAAsB,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC,CAEjE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,GACpC,eAAe,aAAa,EAC5B,WAAW,MAAM,KAChB,CAAC,MAAM,MAAM,CAAC,GAAG,SAEnB,CAAC;AAEF,qBAAa,8BAA+B,SAAQ,qBAAqB,CAAC,yCAAyC,CAAC;IACzG,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,yCAAyC;IA2C1G,UAAU,CAAC,GAAG,EAAE,0BAA0B,EAAE,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA2D/E,aAAa,CAAC,GAAG,EAAE,0BAA0B,EAAE,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBxF,qHAAqH;IACtG,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKtD;;;;;;;;;;;;;;;;;OAiBG;IACG,iBAAiB,CAAC,CAAC,SAAS,OAAO,EACvC,gBAAgB,EAAE,SAAS,EAC3B,OAAO,EAAE,MAAM,EACf,eAAe,EAAE,CAAC,EAClB,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,YAAY,CAAC,CAAC,SAAS,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC;IAkHlE,IAAa,aAAa,IAAI,OAAO,CAEpC;IAED;;;;OAIG;IACM,wBAAwB,IAAI,IAAI;IAOzC;;;;;;;OAOG;IACM,iBAAiB,IAAI,IAAI;CAOnC"}
|