@frontmcp/testing 1.12.0 → 1.12.1

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/perf/index.js CHANGED
@@ -13,7 +13,7 @@ ${intervalSummary}${perfStats}`}else if(isSignificantGrowth){message=`Memory gro
13
13
  Interval breakdown:
14
14
  ${intervalSummary}${perfStats}`}else{message=`No leak detected: ${formatBytes(totalGrowth)} total, ${formatBytes(growthRate)}/iteration
15
15
  Interval breakdown:
16
- ${intervalSummary}${perfStats}`}return{hasLeak,leakSizePerIteration:hasLeak?growthRate:0,totalGrowth,growthRate,rSquared,samples,message,intervals,graphData,durationMs,requestsPerSecond}}generateIntervals(samples,intervalSize){const intervals=[];const safeIntervalSize=intervalSize<=0?1:intervalSize;const numIntervals=Math.ceil(samples.length/safeIntervalSize);for(let i=0;i<numIntervals;i++){const startIdx=i*safeIntervalSize;const endIdx=Math.min((i+1)*safeIntervalSize-1,samples.length-1);if(startIdx>=samples.length)break;const heapAtStart=samples[startIdx];const heapAtEnd=samples[endIdx];const delta=heapAtEnd-heapAtStart;const iterationsInInterval=endIdx-startIdx+1;const growthRatePerIteration=iterationsInInterval>1?delta/(iterationsInInterval-1):0;intervals.push({startIteration:startIdx,endIteration:endIdx,heapAtStart,heapAtEnd,delta,deltaFormatted:formatBytes(delta),growthRatePerIteration})}return intervals}generateGraphData(samples){if(samples.length===0)return[];const baselineHeap=samples[0];return samples.map((heapUsed,iteration)=>({iteration,heapUsed,heapUsedFormatted:formatBytes(heapUsed),cumulativeDelta:heapUsed-baselineHeap,cumulativeDeltaFormatted:formatBytes(heapUsed-baselineHeap)}))}};function sleep2(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function assertNoLeak(operation,options){const detector=new LeakDetector;const result=await detector.detectLeak(operation,options);if(result.hasLeak){throw new Error(`Memory leak detected: ${result.message}`)}return result}function createLeakDetector(){return new LeakDetector}function createPerfFixtures(testName,project){return new PerfFixturesImpl(testName,project)}var PerfFixturesImpl=class{constructor(testName,project){this.testName=testName;this.project=project;this.collector=new MetricsCollector;this.leakDetector=new LeakDetector}testName;project;collector;leakDetector;baselineSnapshot=null;startTime=0;issues=[];leakResults=[];async baseline(){this.startTime=Date.now();this.baselineSnapshot=await this.collector.captureBaseline();return this.baselineSnapshot}measure(label){return this.collector.captureSnapshot(label)}async checkLeak(operation,options){const result=await this.leakDetector.detectLeak(operation,options);this.leakResults.push(result);if(result.hasLeak){this.issues.push({type:"memory-leak",severity:"error",message:result.message,metric:"heapUsed",actual:result.totalGrowth,expected:options?.threshold??1024*1024})}return result}async checkLeakParallel(operationFactory,options){const result=await this.leakDetector.detectLeakParallel(operationFactory,options);this.leakResults.push(result);if(result.hasLeak){this.issues.push({type:"memory-leak",severity:"error",message:result.message,metric:"heapUsed",actual:result.totalGrowth,expected:options?.threshold??1024*1024})}return result}assertThresholds(thresholds){const finalSnapshot=this.collector.captureSnapshot("final");const baseline=this.collector.getBaseline();if(!baseline){throw new Error("Cannot assert thresholds without baseline. Call baseline() first.")}const duration=Date.now()-this.startTime;const memoryDelta=this.collector.calculateMemoryDelta(finalSnapshot.memory);if(thresholds.maxHeapDelta!==void 0&&memoryDelta){if(memoryDelta.heapUsed>thresholds.maxHeapDelta){const issue={type:"threshold-exceeded",severity:"error",message:`Heap delta ${formatBytes(memoryDelta.heapUsed)} exceeds threshold ${formatBytes(thresholds.maxHeapDelta)}`,metric:"heapUsed",actual:memoryDelta.heapUsed,expected:thresholds.maxHeapDelta};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxDurationMs!==void 0){if(duration>thresholds.maxDurationMs){const issue={type:"threshold-exceeded",severity:"error",message:`Duration ${formatDuration(duration)} exceeds threshold ${formatDuration(thresholds.maxDurationMs)}`,metric:"durationMs",actual:duration,expected:thresholds.maxDurationMs};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxCpuTime!==void 0){const cpuUsage=this.collector.getCpuUsage();if(cpuUsage.total>thresholds.maxCpuTime){const issue={type:"threshold-exceeded",severity:"error",message:`CPU time ${cpuUsage.total}\xB5s exceeds threshold ${thresholds.maxCpuTime}\xB5s`,metric:"cpuTime",actual:cpuUsage.total,expected:thresholds.maxCpuTime};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxRssDelta!==void 0&&memoryDelta){if(memoryDelta.rss>thresholds.maxRssDelta){const issue={type:"threshold-exceeded",severity:"error",message:`RSS delta ${formatBytes(memoryDelta.rss)} exceeds threshold ${formatBytes(thresholds.maxRssDelta)}`,metric:"rss",actual:memoryDelta.rss,expected:thresholds.maxRssDelta};this.issues.push(issue);throw new Error(issue.message)}}}getMeasurements(){return this.collector.getMeasurements()}getTestName(){return this.testName}getProject(){return this.project}getIssues(){return[...this.issues]}buildMeasurement(){const endTime=Date.now();const finalSnapshot=this.collector.captureSnapshot("final");const baseline=this.collector.getBaseline();const memoryDelta=baseline?this.collector.calculateMemoryDelta(finalSnapshot.memory):void 0;return{name:this.testName,project:this.project,baseline:baseline??finalSnapshot,measurements:this.collector.getMeasurements(),final:finalSnapshot,timing:{startTime:this.startTime||endTime,endTime,durationMs:endTime-(this.startTime||endTime)},memoryDelta:memoryDelta??void 0,issues:this.getIssues(),leakDetectionResults:this.leakResults.length>0?this.leakResults:void 0}}reset(){this.collector.reset();this.baselineSnapshot=null;this.startTime=0;this.issues=[];this.leakResults=[]}};var MEASUREMENTS_KEY="__FRONTMCP_PERF_MEASUREMENTS__";function getGlobalMeasurementsArray(){if(!globalThis[MEASUREMENTS_KEY]){globalThis[MEASUREMENTS_KEY]=[]}return globalThis[MEASUREMENTS_KEY]}function addGlobalMeasurement(measurement){getGlobalMeasurementsArray().push(measurement)}function getGlobalMeasurements(){return[...getGlobalMeasurementsArray()]}function clearGlobalMeasurements(){const arr=getGlobalMeasurementsArray();arr.length=0}function getMeasurementsForProject(project){return getGlobalMeasurementsArray().filter(m=>m.project===project)}var import_jose=require("jose");var TestTokenFactory=class{issuer;audience;privateKey=null;publicKey=null;jwk=null;keyId;hmacSecret;constructor(options={}){this.issuer=options.issuer??"https://test.frontmcp.local";this.audience=options.audience??"frontmcp-test";this.keyId=`test-key-${Date.now()}`;this.hmacSecret=options.hmacSecret?new TextEncoder().encode(options.hmacSecret):null}get isHmac(){return this.hmacSecret!==null}get alg(){return this.isHmac?"HS256":"RS256"}signingKey(){if(this.hmacSecret)return this.hmacSecret;if(!this.privateKey){throw new Error("Private key not initialized")}return this.privateKey}async ensureKeys(){if(this.isHmac)return;if(this.privateKey&&this.publicKey)return;const{publicKey,privateKey}=await(0,import_jose.generateKeyPair)("RS256",{extractable:true});this.privateKey=privateKey;this.publicKey=publicKey;this.jwk=await(0,import_jose.exportJWK)(publicKey);this.jwk.kid=this.keyId;this.jwk.use="sig";this.jwk.alg="RS256"}async createTestToken(options){await this.ensureKeys();const nowMs=Date.now();const iat=Math.floor(nowMs/1e3);const exp=options.exp??3600;const payload={iss:options.iss??this.issuer,sub:options.sub,aud:options.aud??this.audience,iat,exp:Math.ceil(nowMs/1e3)+exp,scope:options.scopes?.join(" "),...options.claims};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}async createAdminToken(sub="admin-001"){return this.createTestToken({sub,scopes:["admin:*","read","write","delete"],claims:{email:"admin@test.local",name:"Test Admin",role:"admin"}})}async createUserToken(sub="user-001",scopes=["read","write"]){return this.createTestToken({sub,scopes,claims:{email:"user@test.local",name:"Test User",role:"user"}})}async createAnonymousToken(expiresIn){return this.createTestToken({sub:`anon:${Date.now()}`,scopes:["anonymous"],exp:expiresIn,claims:{name:"Anonymous",role:"anonymous"}})}async createExpiredToken(options){await this.ensureKeys();const now=Math.floor(Date.now()/1e3);const payload={iss:this.issuer,sub:options.sub,aud:this.audience,iat:now-7200,exp:now-3600};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}createTokenWithInvalidSignature(options){const now=Math.floor(Date.now()/1e3);const headerObj=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const header=Buffer.from(JSON.stringify(headerObj)).toString("base64url");const payload=Buffer.from(JSON.stringify({iss:this.issuer,sub:options.sub,aud:this.audience,iat:now,exp:now+3600})).toString("base64url");const signature=Buffer.from("invalid-signature-"+Date.now()).toString("base64url");return`${header}.${payload}.${signature}`}async getPublicJwks(){if(this.isHmac){throw new Error("getPublicJwks() is not available in HS256 mode (gateway tokens use a shared secret)")}await this.ensureKeys();if(!this.jwk){throw new Error("JWK not initialized")}return{keys:[this.jwk]}}getIssuer(){return this.issuer}getAudience(){return this.audience}};var import_protocol3=require("@frontmcp/protocol");var import_sdk=require("@frontmcp/sdk");var import_utils4=require("@frontmcp/utils");var DefaultMockRegistry=class{mocks=[];add(mock){const entry={definition:mock,callCount:0,calls:[],remainingUses:mock.times??Infinity};this.mocks.push(entry);return{remove:()=>{const index=this.mocks.indexOf(entry);if(index!==-1){this.mocks.splice(index,1)}},callCount:()=>entry.callCount,calls:()=>[...entry.calls]}}clear(){this.mocks=[]}getAll(){return this.mocks.map(e=>e.definition)}match(request){for(const entry of this.mocks){if(entry.remainingUses<=0)continue;const{definition}=entry;if(definition.method!==request.method)continue;if(definition.params!==void 0){const params=request.params??{};if(typeof definition.params==="function"){if(!definition.params(params))continue}else{if(!this.paramsMatch(definition.params,params))continue}}entry.callCount++;entry.calls.push(request);entry.remainingUses--;return definition}return void 0}paramsMatch(expected,actual){for(const[key,value]of Object.entries(expected)){if(!(key in actual))return false;const actualValue=actual[key];if(Array.isArray(value)){if(!Array.isArray(actualValue))return false;if(value.length!==actualValue.length)return false;for(let i=0;i<value.length;i++){const expectedItem=value[i];const actualItem=actualValue[i];if(typeof expectedItem==="object"&&expectedItem!==null){if(typeof actualItem!=="object"||actualItem===null)return false;if(!this.paramsMatch(expectedItem,actualItem)){return false}}else if(actualItem!==expectedItem){return false}}}else if(typeof value==="object"&&value!==null){if(typeof actualValue!=="object"||actualValue===null)return false;if(!this.paramsMatch(value,actualValue)){return false}}else if(actualValue!==value){return false}}return true}};var mockResponse={success(result,id=1){return{jsonrpc:"2.0",id,result}},error(code,message,data,id=1){return{jsonrpc:"2.0",id,error:{code,message,data}}},toolResult(content,id=1){return{jsonrpc:"2.0",id,result:{content}}},toolsList(tools,id=1){return{jsonrpc:"2.0",id,result:{tools}}},resourcesList(resources,id=1){return{jsonrpc:"2.0",id,result:{resources}}},resourceRead(contents,id=1){return{jsonrpc:"2.0",id,result:{contents}}},errors:{methodNotFound:(method,id=1)=>mockResponse.error(-32601,`Method not found: ${method}`,void 0,id),invalidParams:(message,id=1)=>mockResponse.error(-32602,message,void 0,id),internalError:(message,id=1)=>mockResponse.error(-32603,message,void 0,id),resourceNotFound:(uri,id=1)=>mockResponse.error(-32002,`Resource not found: ${uri}`,{uri},id),toolNotFound:(name,id=1)=>mockResponse.error(-32601,`Tool not found: ${name}`,{name},id),unauthorized:(id=1)=>mockResponse.error(-32001,"Unauthorized",void 0,id),forbidden:(id=1)=>mockResponse.error(-32003,"Forbidden",void 0,id)}};var DefaultInterceptorChain=class{request=[];response=[];mocks;constructor(){this.mocks=new DefaultMockRegistry}addRequestInterceptor(interceptor){this.request.push(interceptor);return()=>{const index=this.request.indexOf(interceptor);if(index!==-1){this.request.splice(index,1)}}}addResponseInterceptor(interceptor){this.response.push(interceptor);return()=>{const index=this.response.indexOf(interceptor);if(index!==-1){this.response.splice(index,1)}}}async processRequest(request,meta){let currentRequest=request;const mockDef=this.mocks.match(request);if(mockDef){if(mockDef.delay&&mockDef.delay>0){await sleep3(mockDef.delay)}let mockResponse2;if(typeof mockDef.response==="function"){mockResponse2=await mockDef.response(request)}else{mockResponse2=mockDef.response}return{type:"mock",response:{...mockResponse2,id:request.id??mockResponse2.id}}}for(const interceptor of this.request){const ctx={request:currentRequest,meta};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentRequest=result.request;break;case"mock":return{type:"mock",response:{...result.response,id:request.id??result.response.id}};case"error":return{type:"error",error:result.error}}}return{type:"continue",request:currentRequest}}async processResponse(request,response,durationMs){let currentResponse=response;for(const interceptor of this.response){const ctx={request,response:currentResponse,durationMs};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentResponse=result.response;break}}return currentResponse}clear(){this.request=[];this.response=[];this.mocks.clear()}};function sleep3(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function errorName(err){if(typeof err!=="object"||err===null)return void 0;const name=err.name;return typeof name==="string"?name:void 0}function isAbortError(err){return errorName(err)==="AbortError"}function errorMessage(err,fallback="Unknown error"){if(typeof err==="string"&&err)return err;if(typeof err==="object"&&err!==null){const message=err.message;if(typeof message==="string"&&message)return message}return fallback}var interceptedErrors=new WeakSet;function markInterceptedError(err){interceptedErrors.add(err);return err}function isInterceptedError(err){return typeof err==="object"&&err!==null&&interceptedErrors.has(err)}var import_protocol=require("@frontmcp/protocol");var import_utils=require("@frontmcp/utils");var SENTINEL_PREFIX="=?base64?";var SENTINEL_SUFFIX="?=";var NAME_PARAM_BY_METHOD={"tools/call":"name","prompts/get":"name","resources/read":"uri","events/poll":"name","events/stream":"name","events/subscribe":"name","events/unsubscribe":"name"};function isStatelessRequest(protocolVersion,method){if(protocolVersion===import_protocol.PROTOCOL_2026_07_28)return true;return import_protocol.MCP_20260728_ADDED_METHODS.includes(method??"")}function encodeHeaderValue(value){const needsEncoding=/[^\x20-\x7e]/.test(value)||value!==value.trim()||value.startsWith(SENTINEL_PREFIX);if(!needsEncoding)return value;return`${SENTINEL_PREFIX}${(0,import_utils.base64Encode)(new TextEncoder().encode(value))}${SENTINEL_SUFFIX}`}function withRequestMeta(message,meta){const params=message.params??{};const callerMeta=params["_meta"];return{...message,params:{...params,_meta:{...meta,...callerMeta}}}}function revisionHeaders(message,toolInputSchema){const headers={"MCP-Protocol-Version":import_protocol.PROTOCOL_2026_07_28};if(!message)return headers;headers["Mcp-Method"]=message.method;const nameParam=NAME_PARAM_BY_METHOD[message.method];const name=nameParam?message.params?.[nameParam]:void 0;if(typeof name==="string")headers["Mcp-Name"]=encodeHeaderValue(name);if(message.method==="tools/call"){Object.assign(headers,paramHeaders(toolInputSchema,message.params?.["arguments"]))}return headers}function paramHeaders(schema,args){const headers={};const properties=schema?.properties??{};const values=typeof args==="object"&&args!==null?args:{};for(const[key,property]of Object.entries(properties)){const value=values[key];const headerName=property?.["x-mcp-header"];if(typeof headerName==="string"&&headerName&&isHeaderValue(value)){headers[`Mcp-Param-${headerName}`]=encodeHeaderValue(String(value))}Object.assign(headers,paramHeaders(property,value))}return headers}function isHeaderValue(value){return typeof value==="string"||typeof value==="boolean"||Number.isSafeInteger(value)}function jsonRpcErrorIn(body){try{const parsed=JSON.parse(body);const error=parsed.error;if(typeof error?.code!=="number"||typeof error.message!=="string")return void 0;return{jsonrpc:"2.0",id:parsed.id??null,error}}catch{return void 0}}function acknowledgedFilterIn(eventData){try{const message=JSON.parse(eventData);if(message.method!==import_protocol.SUBSCRIPTIONS_ACKNOWLEDGED_METHOD)return void 0;return message.params?.notifications??{}}catch{return void 0}}var import_utils2=require("@frontmcp/utils");var DEFAULT_TIMEOUT=3e4;var SseTransport=class{baseUrl;entryPath;timeout;authHeaders;publicMode;debug;clientInfo;notificationHandler;interceptors;elicitationHandler;state="disconnected";authToken;sessionId;messageEndpoint;stream;pending=new Map;connectionCount=0;reconnectCount=0;lastRequestHeaders={};constructor(config){this.baseUrl=config.baseUrl.replace(/\/$/,"");this.entryPath=config.entryPath;this.timeout=config.timeout??DEFAULT_TIMEOUT;this.authHeaders=config.auth?.headers??{};this.authToken=config.auth?.token;this.publicMode=config.publicMode??false;this.debug=config.debug??false;this.clientInfo=config.clientInfo;this.notificationHandler=config.notificationHandler;this.interceptors=config.interceptors;this.elicitationHandler=config.elicitationHandler}async connect(){this.state="connecting";this.connectionCount++;try{if(!this.publicMode&&!this.authToken){await this.requestAnonymousToken()}await this.openStream();this.state="connected";this.log(`Connected; messages go to ${this.messageEndpoint}`)}catch(error){this.state="error";this.stream?.abort();this.stream=void 0;throw error}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const intercepted=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"sse",sessionId:this.sessionId});switch(intercepted.type){case"mock":return await this.interceptors.processResponse(message,intercepted.response,Date.now()-startTime);case"error":throw markInterceptedError(intercepted.error);case"continue":message=intercepted.request;break}}let response;if(message.id===void 0){await this.post(JSON.stringify(message));response={jsonrpc:"2.0",id:null,result:void 0}}else{response=await this.postAndAwait(message.id,JSON.stringify(message))}if(this.interceptors){response=await this.interceptors.processResponse(message,response,Date.now()-startTime)}return response}async notify(message){this.ensureConnected();const result=await this.post(JSON.stringify(message));if(!result.ok)this.log(`HTTP ${result.status} on notification: ${result.body}`)}async sendRaw(data){this.ensureConnected();let id;try{const parsed=JSON.parse(data);if(typeof parsed.id==="string"||typeof parsed.id==="number")id=parsed.id}catch{}if(id!==void 0)return this.postAndAwait(id,data);const result=await this.post(data);if(!result.ok){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:result.body}}}return{jsonrpc:"2.0",id:null,result:void 0}}async close(){this.closeStream("Transport closed");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0;this.log("SSE transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.timeout=ms}getMessageEndpoint(){return this.messageEndpoint}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}async simulateDisconnect(){this.closeStream("Simulated disconnect");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0}async waitForReconnect(timeoutMs){this.reconnectCount++;let timer;try{await Promise.race([this.connect(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("Timeout waiting for reconnection")),timeoutMs)})])}finally{clearTimeout(timer)}}async openStream(){const controller=new AbortController;this.stream=controller;const url=this.sseUrl();const{"Content-Type":_contentType,...headers}=this.buildHeaders();this.log(`GET ${url}`);const connectTimer=setTimeout(()=>controller.abort(),this.timeout);let response;try{response=await fetch(url,{method:"GET",headers:{...headers,Accept:"text/event-stream"},signal:controller.signal})}catch(error){clearTimeout(connectTimer);throw new Error(isAbortError(error)?`SSE connection to ${url} timed out after ${this.timeout}ms`:`SSE connection to ${url} failed: ${errorMessage(error)}`,{cause:error})}const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){clearTimeout(connectTimer);const body=await response.text().catch(()=>"");throw new Error(`SSE connection to ${url} failed: HTTP ${response.status} ${response.statusText}${body?` \u2014 ${body}`:""}. The legacy HTTP+SSE transport needs a server that serves it (@FrontMcp({ transport: { protocol: { legacy: true } } })).`)}const endpoint=new Promise((resolve,reject)=>{const reader=response.body?.getReader();if(!reader){reject(new Error(`SSE connection to ${url} has no body`));return}void this.readStream(controller,reader,resolve,reject)});try{const data=await endpoint;const messageUrl=new URL(data,url);this.messageEndpoint=messageUrl.toString();this.sessionId=messageUrl.searchParams.get("sessionId")??void 0}finally{clearTimeout(connectTimer)}}async readStream(controller,reader,onEndpoint,onEndpointError){const decoder=new TextDecoder;let buffer="";let endpointSeen=false;try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){const{completeEvents,remainder}=splitSSEEvents(buffer+decoder.decode(chunk.value,{stream:true}));buffer=remainder;for(const text of completeEvents){const event=parseSSEEvent(text);if(!event)continue;if(event.type==="endpoint"){if(!endpointSeen){endpointSeen=true;onEndpoint(event.data)}continue}await this.handleMessage(event.data)}}}catch(error){if(!controller.signal.aborted)this.log("SSE stream failed:",error)}finally{reader.releaseLock()}if(!endpointSeen){onEndpointError(new Error(controller.signal.aborted?`SSE stream at ${this.sseUrl()} sent no endpoint event within ${this.timeout}ms`:`SSE stream at ${this.sseUrl()} ended before the server sent its endpoint`))}if(this.stream===controller){this.stream=void 0;this.rejectPending("SSE stream closed by the server");if(this.state==="connected")this.state="disconnected"}}async handleMessage(data){let message;try{message=JSON.parse(data)}catch{this.log("Ignoring SSE event that is not JSON:",data);return}if(!message||typeof message!=="object")return;if(typeof message.method==="string"){const request=message;if(request.id===void 0||request.id===null){this.notificationHandler?.(request);return}await this.answerServerRequest(request);return}if(message.id!==void 0&&message.id!==null){const pending=this.pending.get(message.id);if(pending){clearTimeout(pending.timer);this.pending.delete(message.id);pending.resolve(message)}}}async answerServerRequest(request){const id=request.id;let reply;if(request.method==="elicitation/create"){reply={jsonrpc:"2.0",id,result:await this.elicit(request.params)}}else if(request.method==="ping"){reply={jsonrpc:"2.0",id,result:{}}}else{reply={jsonrpc:"2.0",id,error:{code:-32601,message:`Method not found: ${request.method}`}}}const result=await this.post(JSON.stringify(reply));if(!result.ok)this.log(`HTTP ${result.status} answering ${request.method}: ${result.body}`)}async elicit(params){if(!this.elicitationHandler)return{action:"decline"};try{return await this.elicitationHandler(params)}catch(error){this.log("Elicitation handler error:",error);return{action:"cancel"}}}closeStream(reason){const controller=this.stream;this.stream=void 0;controller?.abort();this.rejectPending(reason)}rejectPending(reason){for(const[id,pending]of this.pending){clearTimeout(pending.timer);pending.resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:reason}})}this.pending.clear()}async postAndAwait(id,body){const answer=new Promise(resolve=>{const timer=setTimeout(()=>{this.pending.delete(id);resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:`Request timeout after ${this.timeout}ms`}})},this.timeout);this.pending.set(id,{resolve,timer})});const result=await this.post(body);if(!result.ok){const pending=this.pending.get(id);if(pending){clearTimeout(pending.timer);this.pending.delete(id)}return{jsonrpc:"2.0",id,error:{code:-32e3,message:`HTTP ${result.status}: ${result.statusText}`,data:result.body}}}return answer}async post(body){const endpoint=this.messageEndpoint;if(!endpoint)throw new Error("SSE transport has no message endpoint. Call connect() first.");const headers=this.buildHeaders();this.lastRequestHeaders=headers;this.log(`POST ${endpoint}`,body);const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),this.timeout);try{const response=await fetch(endpoint,{method:"POST",headers,body,signal:controller.signal});const text=await response.text();return{ok:response.ok,status:response.status,statusText:response.statusText,body:text}}catch(error){if(isAbortError(error)){return{ok:false,status:0,statusText:`timeout after ${this.timeout}ms`,body:""}}throw error}finally{clearTimeout(timer)}}async requestAnonymousToken(){const url=new URL(this.baseUrl);url.pathname=`${(0,import_utils2.trimTrailing)(url.pathname,"/")}/oauth/token`;url.search="";const tokenUrl=url.toString();try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:crypto.randomUUID(),resource:this.baseUrl})});if(!response.ok){this.log(`No anonymous token (HTTP ${response.status})`);return}const token=await response.json();if(token.access_token)this.authToken=token.access_token}catch(error){this.log("Error requesting anonymous token:",error)}}sseUrl(){const url=new URL(this.baseUrl);const entry=(0,import_utils2.trimSlashes)(this.entryPath);const basePath=(0,import_utils2.trimTrailing)(url.pathname,"/");url.pathname=entry?`${basePath}/${entry}/sse`:`${basePath}/sse`;return url.toString()}buildHeaders(){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.clientInfo)headers["User-Agent"]=`${this.clientInfo.name}/${this.clientInfo.version}`;if(this.authToken)headers["Authorization"]=`Bearer ${this.authToken}`;if(this.sessionId)headers["mcp-session-id"]=this.sessionId;Object.assign(headers,this.authHeaders);return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.debug){console.log(`[SSE] ${message}`,data??"")}}};function splitSSEEvents(buffer){const endsWithCarriageReturn=buffer.endsWith("\r");const normalized=(endsWithCarriageReturn?buffer.slice(0,-1):buffer).replace(/\r\n?/g,"\n");const completeEvents=normalized.split("\n\n");const remainder=completeEvents.pop()??"";return{completeEvents,remainder:endsWithCarriageReturn?`${remainder}\r`:remainder}}function parseSSEEvent(text){let type="message";const data=[];for(const line of text.split("\n")){if(line.startsWith(":"))continue;const colon=line.indexOf(":");const field=colon===-1?line:line.slice(0,colon);const value=colon===-1?"":line.slice(colon+1).replace(/^ /,"");if(field==="event")type=value;else if(field==="data")data.push(value)}return data.length>0?{type,data:data.join("\n")}:void 0}var import_protocol2=require("@frontmcp/protocol");var import_utils3=require("@frontmcp/utils");var DEFAULT_TIMEOUT2=3e4;var NOTIFICATION_STREAM_REOPEN_DELAY_MS=250;var StreamableHttpTransport=class{config;state="disconnected";sessionId;authToken;connectionCount=0;reconnectCount=0;lastRequestHeaders={};interceptors;publicMode;elicitationHandler;notificationHandler;notificationStream;notificationProtocolVersion="";notificationStreamReopenTimer;subscriptionStream;protocolVersion;requestMeta;toolInputSchemas=new Map;constructor(config){this.config={baseUrl:config.baseUrl.replace(/\/$/,""),entryPath:config.entryPath,timeout:config.timeout??DEFAULT_TIMEOUT2,auth:config.auth??{},publicMode:config.publicMode??false,debug:config.debug??false,interceptors:config.interceptors,clientInfo:config.clientInfo};this.authToken=config.auth?.token;this.interceptors=config.interceptors;this.publicMode=config.publicMode??false;this.elicitationHandler=config.elicitationHandler;this.notificationHandler=config.notificationHandler;this.protocolVersion=config.protocolVersion;this.requestMeta={[import_protocol2.MCP_20260728_META.protocolVersion]:import_protocol2.PROTOCOL_2026_07_28,...config.clientInfo&&{[import_protocol2.MCP_20260728_META.clientInfo]:config.clientInfo},[import_protocol2.MCP_20260728_META.clientCapabilities]:config.capabilities??{},...config.logLevel&&{[import_protocol2.MCP_20260728_META.logLevel]:config.logLevel}}}async connect(){this.state="connecting";this.connectionCount++;try{if(this.publicMode){this.log("Public mode: connecting without authentication");this.state="connected";return}if(!this.authToken){await this.requestAnonymousToken()}this.state="connected";this.log("Connected to StreamableHTTP transport")}catch(error){this.state="error";throw error}}async requestAnonymousToken(){const clientId=crypto.randomUUID();const tokenUrl=`${this.config.baseUrl}/oauth/token`;this.log(`Requesting anonymous token from ${tokenUrl}`);try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:clientId,resource:this.config.baseUrl})});if(!response.ok){const errorText=await response.text();this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);return}const tokenResponse=await response.json();if(tokenResponse.access_token){this.authToken=tokenResponse.access_token;this.log("Anonymous token acquired successfully")}}catch(error){this.log(`Error requesting anonymous token: ${error}`)}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const interceptResult=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"streamable-http",sessionId:this.sessionId});switch(interceptResult.type){case"mock":{const mockResponse2=await this.interceptors.processResponse(message,interceptResult.response,Date.now()-startTime);return mockResponse2}case"error":throw markInterceptedError(interceptResult.error);case"continue":message=interceptResult.request;break}}const stateless=isStatelessRequest(this.protocolVersion,message.method);const outgoing=stateless?withRequestMeta(message,this.requestMeta):message;const headers=this.buildHeaders(stateless,outgoing);this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url}`,outgoing);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(outgoing),signal:controller.signal});const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}let jsonResponse;if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status}: ${errorText}`);const rpcError=stateless&&!isAuthStatus(response.status)?jsonRpcErrorIn(errorText):void 0;jsonResponse=rpcError??{jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`HTTP ${response.status}: ${response.statusText}`,data:errorText}}}else{const contentType=response.headers.get("content-type")??"";if(contentType.includes("text/event-stream")){jsonResponse=await this.handleSSEResponseWithElicitation(response,message)}else{const text=await response.text();this.log("Response:",text);if(!text.trim()){jsonResponse={jsonrpc:"2.0",id:message.id??null,result:void 0}}else{jsonResponse=JSON.parse(text)}}}if(stateless&&message.method==="tools/list")this.rememberToolInputSchemas(jsonResponse.result);if(this.interceptors){jsonResponse=await this.interceptors.processResponse(message,jsonResponse,Date.now()-startTime)}clearTimeout(timeoutId);return jsonResponse}catch(error){clearTimeout(timeoutId);if(isAbortError(error)){return{jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`Request timeout after ${this.config.timeout}ms`}}}throw error}}async notify(message){this.ensureConnected();const headers=this.buildHeaders(isStatelessRequest(this.protocolVersion,message.method),message);this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (notification)`,message);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(message),signal:controller.signal});clearTimeout(timeoutId);const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status} on notification: ${errorText}`)}}catch(error){clearTimeout(timeoutId);if(!isAbortError(error)){throw error}}}async sendRaw(data){this.ensureConnected();const headers=this.buildHeaders(isStatelessRequest(this.protocolVersion,void 0));this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (raw)`,data);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:data,signal:controller.signal});clearTimeout(timeoutId);const text=await response.text();if(!text.trim()){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}}}return JSON.parse(text)}catch(error){clearTimeout(timeoutId);return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:errorMessage(error)}}}}async openNotificationStream(protocolVersion){this.notificationProtocolVersion=protocolVersion;await this.connectNotificationStream()}async listen(id,notifications){this.ensureConnected();this.closeSubscriptionStream();const controller=new AbortController;this.subscriptionStream=controller;const message=withRequestMeta({jsonrpc:"2.0",id,method:"subscriptions/listen",params:{notifications}},this.requestMeta);let ackTimer;const acknowledged=await new Promise(resolve=>{ackTimer=setTimeout(()=>resolve(void 0),this.config.timeout);void this.readSubscriptionStream(controller,message,resolve)});clearTimeout(ackTimer);if(!acknowledged&&this.subscriptionStream===controller)this.closeSubscriptionStream();return acknowledged}async streamRequest(message,onNotification,signal){this.ensureConnected();const stateless=isStatelessRequest(this.protocolVersion,message.method);const outgoing=stateless?withRequestMeta(message,this.requestMeta):message;let response;try{response=await fetch(this.mcpUrl(),{method:"POST",headers:this.buildHeaders(stateless,outgoing),body:JSON.stringify(outgoing),signal})}catch(error){if(isAbortError(error))return void 0;throw error}const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!isEventStream||!response.body){const text=await response.text();const parsed=parsedJsonRpc(text);if(response.ok&&parsed&&"result"in parsed)return parsed;const error={code:-32e3,message:`HTTP ${response.status}: ${response.statusText}`,data:text};return jsonRpcErrorIn(text)??{jsonrpc:"2.0",id:message.id??null,error}}let finalResponse;await this.readEventStream(response.body.getReader(),async event=>{const parsed=parsedJsonRpc(event.data);if(parsed&&"method"in parsed&&parsed["id"]===void 0)onNotification(parsed);else if(parsed&&("result"in parsed||"error"in parsed))finalResponse=parsed});return finalResponse}async close(){this.closeNotificationStream();this.closeSubscriptionStream();this.state="disconnected";this.sessionId=void 0;this.log("StreamableHTTP transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.config.timeout=ms}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}async simulateDisconnect(){this.closeNotificationStream();this.closeSubscriptionStream();this.state="disconnected";this.sessionId=void 0}async waitForReconnect(timeoutMs){const deadline=Date.now()+timeoutMs;this.reconnectCount++;await this.connect();while(Date.now()<deadline){if(this.state==="connected"){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for reconnection")}closeNotificationStream(){clearTimeout(this.notificationStreamReopenTimer);this.notificationStream?.abort();this.notificationStream=void 0}async connectNotificationStream(){if(!this.sessionId||this.notificationStream)return;const controller=new AbortController;this.notificationStream=controller;const{"Content-Type":_contentType,...headers}=this.buildHeaders();const established=fetch(this.mcpUrl(),{method:"GET",headers:{...headers,Accept:"text/event-stream","MCP-Protocol-Version":this.notificationProtocolVersion},signal:controller.signal}).then(async response=>{const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){await response.body?.cancel();this.log(`Server offers no notification stream (HTTP ${response.status})`);this.releaseNotificationStream(controller);return}void this.readNotificationStream(controller,response.body.getReader())},error=>{this.log("Failed to open the notification stream:",error);this.releaseNotificationStream(controller)});let establishTimer;const establishDeadline=new Promise(resolve=>{establishTimer=setTimeout(resolve,this.config.timeout)});await Promise.race([established,establishDeadline]);clearTimeout(establishTimer)}releaseNotificationStream(controller){if(this.notificationStream===controller)this.notificationStream=void 0}closeSubscriptionStream(){this.subscriptionStream?.abort();this.subscriptionStream=void 0}async readSubscriptionStream(controller,message,acknowledge){try{const response=await fetch(this.mcpUrl(),{method:"POST",headers:this.buildHeaders(true,message),body:JSON.stringify(message),signal:controller.signal});const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){await response.body?.cancel();this.log(`Server opened no subscriptions/listen stream (HTTP ${response.status})`)}else{await this.readEventStream(response.body.getReader(),async event=>{const filter=acknowledgedFilterIn(event.data);if(filter)acknowledge(filter);else await this.handleSSEEvent(event)})}}catch(error){this.log("subscriptions/listen failed:",error)}acknowledge(void 0)}async readNotificationStream(controller,reader){await this.readEventStream(reader,event=>this.handleSSEEvent(event));if(controller.signal.aborted||this.notificationStream!==controller)return;this.releaseNotificationStream(controller);this.notificationStreamReopenTimer=setTimeout(()=>void this.connectNotificationStream(),NOTIFICATION_STREAM_REOPEN_DELAY_MS)}async readEventStream(reader,onEvent){const decoder=new TextDecoder;let buffer="";try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){const{completeEvents,remainder}=splitSSEEvents2(buffer+decoder.decode(chunk.value,{stream:true}));buffer=remainder;for(const eventText of completeEvents){for(const event of this.parseSSEEvents(eventText,void 0).events){await onEvent(event)}}}}catch(error){this.log("Event stream ended:",error)}finally{reader.releaseLock()}}rememberToolInputSchemas(result){const tools=result?.tools;if(!Array.isArray(tools))return;for(const tool of tools){if(typeof tool?.name==="string")this.toolInputSchemas.set(tool.name,tool.inputSchema)}}async handleSSEResponseWithElicitation(response,originalRequest){this.log("handleSSEResponseWithElicitation: starting",{requestId:originalRequest.id});const reader=response.body?.getReader();if(!reader){this.log("handleSSEResponseWithElicitation: no response body");return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No response body"}}}const decoder=new TextDecoder;let buffer="";let finalResponse=null;let sseSessionId;try{let readCount=0;while(true){readCount++;this.log(`handleSSEResponseWithElicitation: reading chunk ${readCount}`);const{done,value}=await reader.read();this.log(`handleSSEResponseWithElicitation: read result`,{done,valueLength:value?.length});if(done){if(buffer.trim()){const parsed=this.parseSSEEvents(buffer,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}break}buffer+=decoder.decode(value,{stream:true});const eventEndPattern=/\n\n/g;let lastEventEnd=0;let match;while((match=eventEndPattern.exec(buffer))!==null){const eventText=buffer.slice(lastEventEnd,match.index);lastEventEnd=match.index+2;if(eventText.trim()){const parsed=this.parseSSEEvents(eventText,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}}buffer=buffer.slice(lastEventEnd)}}finally{reader.releaseLock()}if(sseSessionId&&!this.sessionId){this.sessionId=sseSessionId;this.log("Session ID from SSE:",this.sessionId)}if(finalResponse){return finalResponse}return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No final response received in SSE stream"}}}parseSSEEvents(text,_requestId){const lines=text.split("\n");const events=[];let currentEvent={type:"message",data:[]};let sessionId;for(const line of lines){if(line.startsWith("event: ")){currentEvent.type=line.slice(7)}else if(line.startsWith("data: ")){currentEvent.data.push(line.slice(6))}else if(line==="data:"){currentEvent.data.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);currentEvent.id=idValue;const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sessionId=idValue.substring(0,colonIndex)}else{sessionId=idValue}}else if(line===""&&currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id});currentEvent={type:"message",data:[]}}}if(currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id})}return{events,sessionId}}async handleSSEEvent(event){this.log("SSE Event:",{type:event.type,data:event.data.slice(0,200)});try{const parsed=JSON.parse(event.data);if("method"in parsed&&parsed.method==="elicitation/create"){await this.handleElicitationRequest(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("method"in parsed&&parsed.id===void 0){this.notificationHandler?.(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("result"in parsed||"error"in parsed){return{isFinal:true,response:parsed}}return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}catch{this.log("Failed to parse SSE event data:",event.data);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}}async handleElicitationRequest(request){const params=request.params;this.log("Elicitation request received:",{mode:params?.mode,message:params?.message?.slice(0,100)});const requestId=request.id;if(requestId===void 0||requestId===null){this.log("Elicitation request has no ID, cannot respond");return}if(!this.elicitationHandler){this.log("No elicitation handler registered, sending error");await this.sendElicitationResponse(requestId,{action:"decline"});return}try{const response=await this.elicitationHandler(params);this.log("Elicitation handler response:",response);await this.sendElicitationResponse(requestId,response)}catch(error){this.log("Elicitation handler error:",error);await this.sendElicitationResponse(requestId,{action:"cancel"})}}async sendElicitationResponse(requestId,response){const headers=this.buildHeaders();const url=this.mcpUrl();const rpcResponse={jsonrpc:"2.0",id:requestId,result:response};this.log("Sending elicitation response:",rpcResponse);try{const fetchResponse=await fetch(url,{method:"POST",headers,body:JSON.stringify(rpcResponse)});if(!fetchResponse.ok){this.log(`Elicitation response HTTP error: ${fetchResponse.status}`)}}catch(error){this.log("Failed to send elicitation response:",error)}}mcpUrl(){const url=new URL(this.config.baseUrl);const entry=(0,import_utils3.trimSlashes)(this.config.entryPath);const basePath=(0,import_utils3.trimTrailing)(url.pathname,"/");url.pathname=entry?`${basePath}/${entry}`:`${basePath}/`;return url.toString()}buildHeaders(stateless=false,message){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.config.clientInfo){headers["User-Agent"]=`${this.config.clientInfo.name}/${this.config.clientInfo.version}`}if(this.authToken){headers["Authorization"]=`Bearer ${this.authToken}`}if(this.sessionId&&!stateless){headers["mcp-session-id"]=this.sessionId}if(stateless){const toolName=message?.params?.["name"];Object.assign(headers,revisionHeaders(message,typeof toolName==="string"?this.toolInputSchemas.get(toolName):void 0))}if(this.config.auth.headers){Object.assign(headers,this.config.auth.headers)}return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.config.debug){console.log(`[StreamableHTTP] ${message}`,data??"")}}parseSSEResponseWithSession(text,requestId){const lines=text.split("\n");const dataLines=[];let sseSessionId;for(const line of lines){if(line.startsWith("data: ")){dataLines.push(line.slice(6))}else if(line==="data:"){dataLines.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sseSessionId=idValue.substring(0,colonIndex)}else{sseSessionId=idValue}}}if(dataLines.length>0){const jsonData=dataLines.join("\n");try{return{response:JSON.parse(jsonData),sseSessionId}}catch{this.log("Failed to parse SSE data as JSON:",jsonData)}}return{response:{jsonrpc:"2.0",id:requestId??null,error:{code:-32700,message:"Failed to parse SSE response",data:text}},sseSessionId}}};function parsedJsonRpc(data){try{const parsed=JSON.parse(data);return typeof parsed==="object"&&parsed!==null?parsed:void 0}catch{return void 0}}function isAuthStatus(status){return status===401||status===403}function splitSSEEvents2(buffer){const endsWithCarriageReturn=buffer.endsWith("\r");const normalized=(endsWithCarriageReturn?buffer.slice(0,-1):buffer).replace(/\r\n?/g,"\n");const completeEvents=normalized.split("\n\n");const remainder=completeEvents.pop()??"";return{completeEvents,remainder:endsWithCarriageReturn?`${remainder}\r`:remainder}}var MCP_APPS_EXTENSION_KEY="io.modelcontextprotocol/ui";function getPlatformClientInfo(platform){switch(platform){case"openai":return{name:"ChatGPT",version:"1.0"};case"ext-apps":return{name:"mcp-ext-apps",version:"1.0"};case"claude":return{name:"claude-desktop",version:"1.0"};case"claude-code":return{name:"claude-code",version:"1.0"};case"codex":return{name:"codex-mcp-client",version:"1.0"};case"cursor":return{name:"cursor",version:"1.0"};case"continue":return{name:"continue",version:"1.0"};case"cody":return{name:"cody",version:"1.0"};case"gemini":return{name:"gemini",version:"1.0"};case"generic-mcp":return{name:"generic-mcp-client",version:"1.0"};case"unknown":default:return{name:"mcp-test-client",version:"1.0"}}}function getPlatformCapabilities(platform){const baseCapabilities={sampling:{},elicitation:{form:{}}};if(platform==="ext-apps"){return{...baseCapabilities,experimental:{[MCP_APPS_EXTENSION_KEY]:{mimeTypes:["text/html;profile=mcp-app"]}}}}return baseCapabilities}var McpTestClientBuilder=class{config;constructor(config){this.config={...config}}withAuth(auth){this.config.auth={...this.config.auth,...auth};return this}withToken(token){this.config.auth={...this.config.auth,token};return this}withHeaders(headers){this.config.auth={...this.config.auth,headers:{...this.config.auth?.headers,...headers}};return this}withTransport(transport){this.config.transport=transport;return this}withTimeout(timeoutMs){this.config.timeout=timeoutMs;return this}withDebug(enabled=true){this.config.debug=enabled;return this}withPublicMode(enabled=true){this.config.publicMode=enabled;return this}withProtocolVersion(version){this.config.protocolVersion=version;return this}withMcpLogLevel(level){this.config.mcpLogLevel=level;return this}withClientInfo(info){this.config.clientInfo=info;return this}withPlatform(platform){this.config.platform=platform;this.config.clientInfo=getPlatformClientInfo(platform);this.config.capabilities=getPlatformCapabilities(platform);return this}withCapabilities(capabilities){this.config.capabilities=capabilities;return this}withQueryParams(params){this.config.queryParams={...this.config.queryParams,...params};return this}withEvents(options){this.config.events=options;return this}build(){return new McpTestClient(this.config)}async buildAndConnect(){const client=this.build();await client.connect();return client}};var DEFAULT_TIMEOUT3=3e4;var DEFAULT_PROTOCOL_VERSION="2025-06-18";var DEFAULT_MCP_LOG_LEVEL="debug";var MAX_INPUT_ROUNDS=10;var LIST_CHANGED_SUBSCRIPTIONS={toolsListChanged:true,promptsListChanged:true,resourcesListChanged:true};var DEFAULT_CLIENT_INFO={name:"@frontmcp/testing",version:"0.4.0"};var MAX_LIST_PAGES=1e3;function isAuthFailure(error){return typeof error?.message==="string"&&/^HTTP (401|403)\b/.test(error.message)}function describeInitializeError(error){const message=error?.message??"Unknown error";const data=error?.data;const detail=typeof data==="string"?data.trim():"";return detail?`${message} - ${detail.slice(0,500)}`:message}function initializeResultFrom(discovered){const serverInfo=discovered._meta?.[import_protocol3.MCP_20260728_META.serverInfo]??{name:"",version:""};return{protocolVersion:import_protocol3.PROTOCOL_2026_07_28,capabilities:discovered.capabilities,serverInfo,...discovered.instructions!==void 0&&{instructions:discovered.instructions}}}function isInputRequired(result){return result?.resultType==="input_required"}function extractEntryPaths(data){let payload=data;if(typeof payload==="string"){try{payload=JSON.parse(payload)}catch{return void 0}}if(!payload||typeof payload!=="object")return void 0;const paths=payload.entryPaths;if(!Array.isArray(paths))return void 0;const strings=paths.filter(p=>typeof p==="string");return strings.length>0?strings:void 0}var McpTestClient=class{config;resourceSubscriptions=new Set;toolsListed=false;transport=null;initResult=null;requestIdCounter=0;_lastRequestId=0;_sessionId;triedDiscoveredEntryPath=false;_sessionInfo=null;_authState={isAnonymous:true,scopes:[]};_logs=[];_traces=[];_notifications=[];_progressUpdates=[];collectingProgress=false;progressTokenCounter=0;_interceptors;_elicitationHandler;eventsClient;constructor(config){if(config.protocolVersion===import_protocol3.PROTOCOL_2026_07_28&&config.transport==="sse"){throw new Error(`Protocol version ${import_protocol3.PROTOCOL_2026_07_28} has no HTTP+SSE transport: use 'streamable-http', or a protocol version before it with 'sse'.`)}this.config={baseUrl:config.baseUrl,entryPath:config.entryPath,transport:config.transport??"streamable-http",auth:config.auth??{},publicMode:config.publicMode??false,timeout:config.timeout??DEFAULT_TIMEOUT3,debug:config.debug??false,protocolVersion:config.protocolVersion??DEFAULT_PROTOCOL_VERSION,mcpLogLevel:config.mcpLogLevel??DEFAULT_MCP_LOG_LEVEL,clientInfo:config.clientInfo??DEFAULT_CLIENT_INFO,platform:config.platform,capabilities:config.capabilities,queryParams:config.queryParams,events:config.events};if(config.auth?.token){this._authState={isAnonymous:false,token:config.auth.token,scopes:this.parseScopesFromToken(config.auth.token),user:this.parseUserFromToken(config.auth.token)}}this._interceptors=new DefaultInterceptorChain}static create(config){return new McpTestClientBuilder(config)}async connect(){this.log("debug",`Connecting to ${this.config.baseUrl}...`);this.triedDiscoveredEntryPath=false;this.initResult=null;this.toolsListed=false;this.transport=this.createTransport();await this.transport.connect();const maxRetries=3;const retryDelayMs=500;let lastError;let reportedEntryPaths;let attemptsMade=0;for(let attempt=1;attempt<=maxRetries;attempt++){attemptsMade=attempt;const initResponse=this.isStateless?await this.discoverServer():await this.initialize();if(initResponse.success&&initResponse.data){this.initResult=initResponse.data;break}lastError=describeInitializeError(initResponse.error);reportedEntryPaths=extractEntryPaths(initResponse.error?.data)??reportedEntryPaths;if(reportedEntryPaths?.length===1&&!this.triedDiscoveredEntryPath){this.triedDiscoveredEntryPath=true;const discovered=reportedEntryPaths[0];this.log("info",`Server serves MCP at ${discovered}; reconnecting there (configured: ${this.mcpPathLabel()})`);this.config.entryPath=discovered;await this.transport.close();this.transport=this.createTransport();await this.transport.connect();continue}if(isAuthFailure(initResponse.error))break;if(attempt<maxRetries){this.log("debug",`MCP init attempt ${attempt} failed (${lastError}), retrying in ${retryDelayMs}ms...`);await new Promise(resolve=>setTimeout(resolve,retryDelayMs))}}if(!this.initResult){const served=reportedEntryPaths?.length?` The server reports it serves MCP at ${reportedEntryPaths.join(", ")}; set \`entryPath\` in test.use() (or \`http.entryPath\` on the server) to match.`:"";throw new Error(`Failed to initialize MCP connection to ${this.config.baseUrl}${this.mcpPathLabel()} after ${attemptsMade} attempt${attemptsMade===1?"":"s"}: ${lastError}.${served}`)}this._sessionId=this.transport.getSessionId();this._sessionInfo={id:this._sessionId??`session-${Date.now()}`,createdAt:new Date,lastActivityAt:new Date,requestCount:1};if(this.isStateless){await this.listen()}else{await this.transport.notify({jsonrpc:"2.0",method:"notifications/initialized"});await this.transport.openNotificationStream?.(this.initResult.protocolVersion);await this.setServerLogLevel()}this.log("info",`Connected to ${this.initResult.serverInfo?.name??"MCP Server"}`);return this.initResult}async disconnect(){await this.eventsClient?.close();if(this.transport){await this.transport.close();this.transport=null}this.initResult=null;this.log("info","Disconnected from MCP server")}async reconnect(options){await this.disconnect();if(options?.sessionId&&this.transport){this._sessionId=options.sessionId}await this.connect()}isConnected(){return this.transport?.isConnected()??false}get sessionId(){return this._sessionId??""}get session(){const info=this._sessionInfo??{id:"",createdAt:new Date,lastActivityAt:new Date,requestCount:0};return{...info,expire:async()=>{this._sessionId=void 0;this._sessionInfo=null}}}get auth(){return this._authState}async authenticate(token){if(typeof token!=="string"||token.trim()===""){throw new Error("authenticate() requires a non-empty token")}const previousAuthState=this._authState;const previousConfigAuth=this.config.auth;this.config.auth={...previousConfigAuth,token};this._authState={isAnonymous:false,token,scopes:this.parseScopesFromToken(token),user:this.parseUserFromToken(token)};const previousTransport=this.transport;if(!previousTransport){this.log("debug","Authentication updated (not connected yet)");return}const previousInit=this.initResult;const previousSessionId=this._sessionId;const previousSessionInfo=this._sessionInfo;try{await this.connect()}catch(err){await this.transport?.close().catch(()=>void 0);this.transport=previousTransport;this.initResult=previousInit;this._sessionId=previousSessionId;this._sessionInfo=previousSessionInfo;this.config.auth=previousConfigAuth;this._authState=previousAuthState;throw err}await previousTransport.close().catch(()=>void 0);this.log("debug","Authentication updated")}get serverInfo(){return{name:this.initResult?.serverInfo?.name??"",version:this.initResult?.serverInfo?.version??""}}get protocolVersion(){return this.initResult?.protocolVersion??""}get instructions(){return this.initResult?.instructions??""}get capabilities(){return this.initResult?.capabilities??{}}hasCapability(name){return!!this.capabilities[name]}async discover(){const response=await this.request("server/discover",{});if(!response.success||!response.data)throw new Error(`server/discover failed: ${response.error?.message}`);return response.data}tools={list:async()=>{const tools=await this.listAllPages("tools/list","tools",cursor=>this.listTools(cursor),page=>page.tools);this.toolsListed=true;return tools},call:async(name,args,options={})=>{await this.learnToolSchemas();const response=await this.callTool(name,args,this.progressTokenFor(options));return this.wrapToolResult(response)}};resources={list:async()=>this.listAllPages("resources/list","resources",cursor=>this.listResources(cursor),page=>page.resources),listTemplates:async()=>this.listAllPages("resources/templates/list","resource templates",cursor=>this.listResourceTemplates(cursor),page=>page.resourceTemplates),read:async uri=>{const response=await this.readResource(uri);return this.wrapResourceContent(response)},subscribe:async uri=>{if(this.isStateless)return this.listenToResource(uri);const response=await this.request("resources/subscribe",{uri});if(!response.success)throw new Error(`Failed to subscribe to ${uri}: ${response.error?.message}`)},unsubscribe:async uri=>{if(this.isStateless){this.resourceSubscriptions.delete(uri);await this.listen();return}const response=await this.request("resources/unsubscribe",{uri});if(!response.success)throw new Error(`Failed to unsubscribe from ${uri}: ${response.error?.message}`)}};prompts={list:async()=>this.listAllPages("prompts/list","prompts",cursor=>this.listPrompts(cursor),page=>page.prompts),get:async(name,args)=>{const response=await this.getPrompt(name,args);return this.wrapPromptResult(response)}};get events(){this.eventsClient??=new import_sdk.EventsClient(this.eventsTransport(),this.config.events);return this.eventsClient}eventsTransport(){const transport={request:async(method,params)=>{const response=await this.request(method,params);if(!response.success){const{code,message,data}=response.error;throw new import_sdk.EventRequestError(method,code,message,data)}return response.data}};if(this.config.transport==="streamable-http"){transport.openStream=(params,onNotification,signal)=>this.openEventStream(params,onNotification,signal)}return transport}async openEventStream(params,onNotification,signal){const transport=this.getConnectedTransport();const id=++this.requestIdCounter;const message={jsonrpc:"2.0",id,method:"events/stream",params};const response=await transport.streamRequest?.(message,onNotification,signal);if(response?.error){throw new import_sdk.EventRequestError("events/stream",response.error.code,response.error.message,response.error.data)}if(signal.aborted&&!isStatelessRequest(this.config.protocolVersion,"events/stream")){await transport.notify({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id}}).catch(()=>void 0)}}raw={request:async message=>{const transport=this.getConnectedTransport();const start=Date.now();const response=await transport.request(message);this.traceRequest(message.method,message.params,message.id,response,Date.now()-start);return response},notify:async message=>{const transport=this.getConnectedTransport();await transport.notify(message)},sendRaw:async data=>{const transport=this.getConnectedTransport();return transport.sendRaw(data)}};get lastRequestId(){return this._lastRequestId}get transport_info(){return{type:this.config.transport,isConnected:()=>this.transport?.isConnected()??false,messageEndpoint:this.transport?.getMessageEndpoint?.(),connectionCount:this.transport?.getConnectionCount?.()??0,reconnectCount:this.transport?.getReconnectCount?.()??0,lastRequestHeaders:this.transport?.getLastRequestHeaders?.()??{},simulateDisconnect:async()=>{await this.transport?.simulateDisconnect?.()},waitForReconnect:async timeoutMs=>{await this.transport?.waitForReconnect?.(timeoutMs)}}}get transport_(){return this.transport_info}notifications={collect:()=>{return new NotificationCollector(this._notifications)},collectProgress:()=>{this.collectingProgress=true;return new ProgressCollector(this._progressUpdates)},send:async(method,params)=>{await this.raw.notify({jsonrpc:"2.0",method,params})}};onElicitation(handler){this._elicitationHandler=handler;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(handler)}this.log("debug","Elicitation handler registered")}clearElicitationHandler(){this._elicitationHandler=void 0;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(void 0)}this.log("debug","Elicitation handler cleared")}logs={all:()=>[...this._logs],filter:level=>this._logs.filter(l=>l.level===level),search:text=>this._logs.filter(l=>l.message.includes(text)),last:()=>this._logs[this._logs.length-1],clear:()=>{this._logs=[]}};trace={all:()=>[...this._traces],last:()=>this._traces[this._traces.length-1],clear:()=>{this._traces=[]}};mock={add:mock=>{return this._interceptors.mocks.add(mock)},tool:(name,result,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.toolResult([{type:"text",text:typeof result==="string"?result:JSON.stringify(result)}]),times:options?.times,delay:options?.delay})},toolError:(name,code,message,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.error(code,message),times:options?.times})},resource:(uri,content,options)=>{const contentObj=typeof content==="string"?{uri,text:content}:{uri,...content};return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.resourceRead([contentObj]),times:options?.times,delay:options?.delay})},resourceError:(uri,options)=>{return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.errors.resourceNotFound(uri),times:options?.times})},toolsList:(tools,options)=>{return this._interceptors.mocks.add({method:"tools/list",response:mockResponse.toolsList(tools),times:options?.times})},resourcesList:(resources,options)=>{return this._interceptors.mocks.add({method:"resources/list",response:mockResponse.resourcesList(resources),times:options?.times})},clear:()=>{this._interceptors.mocks.clear()},all:()=>{return this._interceptors.mocks.getAll()}};intercept={request:interceptor=>{return this._interceptors.addRequestInterceptor(interceptor)},response:interceptor=>{return this._interceptors.addResponseInterceptor(interceptor)},delay:ms=>{return this._interceptors.addRequestInterceptor(async()=>{await new Promise(r=>setTimeout(r,ms));return{action:"passthrough"}})},failMethod:(method,error)=>{return this._interceptors.addRequestInterceptor(ctx=>{if(ctx.request.method===method){return{action:"error",error:new Error(error??`Intercepted: ${method}`)}}return{action:"passthrough"}})},clear:()=>{this._interceptors.request=[];this._interceptors.response=[]},clearAll:()=>{this._interceptors.clear()}};setTimeout(ms){this.config.timeout=ms;if(this.transport){this.transport.setTimeout(ms)}}get isStateless(){return this.config.protocolVersion===import_protocol3.PROTOCOL_2026_07_28}get clientCapabilities(){return this.config.capabilities??{sampling:{},elicitation:{form:{}}}}async initialize(){return this.request("initialize",{protocolVersion:this.config.protocolVersion,capabilities:this.clientCapabilities,clientInfo:this.config.clientInfo})}async discoverServer(){const response=await this.request("server/discover",{});const data=response.data&&initializeResultFrom(response.data);return{...response,data}}async setServerLogLevel(){const level=this.config.mcpLogLevel;if(level===false||!this.hasCapability("logging"))return;const response=await this.request("logging/setLevel",{level});if(!response.success)this.log("warn",`logging/setLevel ${level} failed: ${response.error?.message}`)}async listen(){const resourceSubscriptions=[...this.resourceSubscriptions];const acknowledged=await this.transport?.listen?.(++this.requestIdCounter,{...LIST_CHANGED_SUBSCRIPTIONS,...resourceSubscriptions.length>0&&{resourceSubscriptions}});if(!acknowledged)this.log("warn","The server opened no subscriptions/listen stream");return acknowledged}async listenToResource(uri){this.resourceSubscriptions.add(uri);const acknowledged=await this.listen();if(acknowledged?.resourceSubscriptions?.includes(uri))return;this.resourceSubscriptions.delete(uri);throw new Error(`Failed to subscribe to ${uri}: the server did not acknowledge it in subscriptions/listen`)}async learnToolSchemas(){if(!this.isStateless||this.toolsListed)return;this.toolsListed=true;await this.tools.list().catch(error=>{this.log("warn",`Listing the tools before the first call failed: ${errorMessage(error)}`)})}async listTools(cursor){return this.request("tools/list",cursor?{cursor}:{})}async listAllPages(method,label,fetchPage,itemsOf){const items=[];const seenCursors=new Set;let cursor;for(let page=0;page<MAX_LIST_PAGES;page++){const response=await fetchPage(cursor);if(!response.success||!response.data){throw new Error(`Failed to list ${label}: ${response.error?.message}`)}items.push(...itemsOf(response.data)??[]);const next=response.data.nextCursor;if(!next)return items;if(seenCursors.has(next)){throw new Error(`Failed to list ${label}: ${method} returned the cursor "${next}" twice`)}seenCursors.add(next);cursor=next}throw new Error(`Failed to list ${label}: ${method} did not finish within ${MAX_LIST_PAGES} pages`)}async callTool(name,args,progressToken){return this.request("tools/call",{name,arguments:args??{},...progressToken!==void 0&&{_meta:{progressToken}}})}progressTokenFor(options){if(options.progressToken!==void 0)return options.progressToken;return this.collectingProgress?`progress-${++this.progressTokenCounter}`:void 0}recordNotification=notification=>{const timestamp=new Date;this._notifications.push({method:notification.method,params:notification.params,timestamp});if(notification.method!=="notifications/progress")return;const{progress,total,progressToken,message}=notification.params??{};this._progressUpdates.push({progress:Number(progress),total:typeof total==="number"?total:void 0,message:typeof message==="string"?message:void 0,progressToken:typeof progressToken==="string"||typeof progressToken==="number"?progressToken:void 0,timestamp})};async listResources(cursor){return this.request("resources/list",cursor?{cursor}:{})}async listResourceTemplates(cursor){return this.request("resources/templates/list",cursor?{cursor}:{})}async readResource(uri){return this.request("resources/read",{uri})}async listPrompts(cursor){return this.request("prompts/list",cursor?{cursor}:{})}async getPrompt(name,args){return this.request("prompts/get",{name,arguments:args??{}})}mcpPathLabel(){const entry=(0,import_utils4.trimSlashes)(this.config.entryPath);return entry?`/${entry}`:"/"}createTransport(){let baseUrl=this.config.baseUrl;if(this.config.queryParams&&Object.keys(this.config.queryParams).length>0){const url=new URL(baseUrl);Object.entries(this.config.queryParams).forEach(([key,value])=>{url.searchParams.set(key,String(value))});baseUrl=url.toString()}switch(this.config.transport){case"streamable-http":return new StreamableHttpTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification,protocolVersion:this.config.protocolVersion,capabilities:this.clientCapabilities,logLevel:this.config.mcpLogLevel||void 0});case"sse":return new SseTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification});default:throw new Error(`Unknown transport type: ${this.config.transport}`)}}async request(method,params){let response=await this.send(method,params);for(let round=1;response.success&&isInputRequired(response.data);round++){const{inputRequests,requestState}=response.data;const inputResponses=round>MAX_INPUT_ROUNDS?`the server asked for input more than ${MAX_INPUT_ROUNDS} times`:await this.answerInputRequests(inputRequests);if(typeof inputResponses==="string"){return{...response,success:false,data:void 0,error:{code:-32603,message:`${method}: ${inputResponses}`}}}const retried=await this.send(method,{...params,inputResponses,...requestState!==void 0&&{requestState}});response={...retried,durationMs:response.durationMs+retried.durationMs}}return response}async answerInputRequests(inputRequests={}){const answers={};for(const[key,inputRequest]of Object.entries(inputRequests)){if(inputRequest.method!=="elicitation/create"){return`the server asked for ${inputRequest.method}, which McpTestClient doesn't answer`}answers[key]={...await this.answerElicitation(inputRequest.params??{})}}return answers}async answerElicitation(params){if(!this._elicitationHandler)return{action:"decline"};try{return await this._elicitationHandler({mode:"form",...params})}catch(error){this.log("warn",`The elicitation handler threw: ${errorMessage(error)}`);return{action:"cancel"}}}async send(method,params){const transport=this.getConnectedTransport();const id=++this.requestIdCounter;this._lastRequestId=id;const start=Date.now();try{const response=await transport.request({jsonrpc:"2.0",id,method,params});const durationMs=Date.now()-start;this.updateSessionActivity();if("error"in response&&response.error){const error=response.error;this.traceRequest(method,params,id,response,durationMs);return{success:false,error,durationMs,requestId:id}}this.traceRequest(method,params,id,response,durationMs);return{success:true,data:response.result,durationMs,requestId:id}}catch(err){if(isInterceptedError(err))throw err;const durationMs=Date.now()-start;const error={code:-32603,message:errorMessage(err)};return{success:false,error,durationMs,requestId:id}}}getConnectedTransport(){if(!this.transport||!this.transport.isConnected()){throw new Error("Not connected to MCP server. Call connect() first.")}return this.transport}updateSessionActivity(){if(this._sessionInfo){this._sessionInfo.lastActivityAt=new Date;this._sessionInfo.requestCount++}}wrapToolResult(response){const raw=response.data??{content:[]};const isError=!response.success||raw.isError===true;const meta=raw._meta;const hasUI=meta?.["ui/html"]!==void 0||meta?.["ui/component"]!==void 0;const structuredContent=raw["structuredContent"];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(hasUI&&structuredContent!==void 0){return structuredContent}const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return JSON.parse(textContent.text)}throw new Error("No text content to parse as JSON")},text(){const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return textContent.text}return void 0},hasTextContent(){return raw.content?.some(c=>c.type==="text")??false},hasImageContent(){return raw.content?.some(c=>c.type==="image")??false},hasResourceContent(){return raw.content?.some(c=>c.type==="resource")??false},hasToolUI(){return hasUI}}}wrapResourceContent(response){const raw=response.data??{contents:[]};const isError=!response.success;const firstContent=raw.contents?.[0];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(firstContent&&"text"in firstContent){return JSON.parse(firstContent.text)}throw new Error("No text content to parse as JSON")},text(){if(firstContent&&"text"in firstContent){return firstContent.text}return void 0},mimeType(){return firstContent?.mimeType},hasMimeType(type){return firstContent?.mimeType===type}}}wrapPromptResult(response){const raw=response.data??{messages:[]};const isError=!response.success;return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,messages:raw.messages??[],description:raw.description}}log(level,message,data){const entry={level,message,timestamp:new Date,data};this._logs.push(entry);if(this.config.debug){console.log(`[${level.toUpperCase()}] ${message}`,data??"")}}traceRequest(method,params,id,response,durationMs){this._traces.push({request:{method,params,id},response:{result:"result"in response?response.result:void 0,error:"error"in response?response.error:void 0},durationMs,timestamp:new Date})}parseScopesFromToken(token){try{const payload=this.decodeJwtPayload(token);if(!payload)return[];const scope=payload["scope"];const scopes=payload["scopes"];if(typeof scope==="string"){return scope.split(" ")}if(Array.isArray(scopes)){return scopes}return[]}catch{return[]}}parseUserFromToken(token){try{const payload=this.decodeJwtPayload(token);const sub=payload?.["sub"];if(!sub||typeof sub!=="string")return void 0;return{sub,email:payload["email"],name:payload["name"]}}catch{return void 0}}decodeJwtPayload(token){try{const parts=token.split(".");if(parts.length!==3)return null;const payload=Buffer.from(parts[1],"base64url").toString("utf-8");return JSON.parse(payload)}catch{return null}}};var NotificationCollector=class{constructor(notifications){this.notifications=notifications}notifications;get received(){return[...this.notifications]}has(method){return this.notifications.some(n=>n.method===method)}async waitFor(method,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const found=this.notifications.find(n=>n.method===method);if(found)return found;await new Promise(r=>setTimeout(r,50))}throw new Error(`Timeout waiting for notification: ${method}`)}};var ProgressCollector=class{constructor(updates){this.updates=updates}updates;get all(){return[...this.updates]}async waitForComplete(timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const last=this.updates[this.updates.length-1];if(last&&last.total!==void 0&&last.progress>=last.total){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for progress to complete")}};var import_child_process=require("child_process");var import_net2=require("net");var import_utils5=require("@frontmcp/utils");var TestClientError=class extends Error{constructor(message){super(message);this.name="TestClientError";Object.setPrototypeOf(this,new.target.prototype)}};var ServerStartError=class extends TestClientError{constructor(message,cause){super(message);this.cause=cause;this.name="ServerStartError";Object.setPrototypeOf(this,new.target.prototype)}cause};var import_net=require("net");var E2E_PORT_RANGES={"demo-e2e-public":{start:5e4,size:10},"demo-e2e-cache":{start:50010,size:10},"demo-e2e-config":{start:50020,size:10},"demo-e2e-direct":{start:50030,size:10},"demo-e2e-errors":{start:50040,size:10},"demo-e2e-hooks":{start:50050,size:10},"demo-e2e-multiapp":{start:50060,size:10},"demo-e2e-notifications":{start:50070,size:10},"demo-e2e-providers":{start:50080,size:10},"demo-e2e-standalone":{start:50090,size:10},"demo-e2e-orchestrated":{start:50100,size:10},"demo-e2e-transparent":{start:50110,size:10},"demo-e2e-cimd":{start:50120,size:10},"demo-e2e-remote-proxy":{start:50130,size:10},"demo-e2e-skills":{start:50200,size:10},"demo-e2e-remote":{start:50210,size:10},"demo-e2e-openapi":{start:50220,size:10},"demo-e2e-ui":{start:50230,size:10},"demo-e2e-codecall":{start:50240,size:10},"demo-e2e-remember":{start:50250,size:10},"demo-e2e-elicitation":{start:50260,size:10},"demo-e2e-agents":{start:50270,size:10},"demo-e2e-transport-recreation":{start:50280,size:10},"demo-e2e-jobs":{start:50290,size:10},"demo-e2e-redis":{start:50300,size:10},"demo-e2e-serverless":{start:50310,size:10},"demo-e2e-uipack":{start:50320,size:10},"demo-e2e-agent-adapters":{start:50330,size:10},"demo-e2e-guard":{start:50340,size:10},"demo-e2e-cli-exec":{start:50350,size:10},"demo-e2e-env-awareness":{start:50360,size:10},"demo-e2e-esm":{start:50370,size:10},"demo-e2e-feature-flags":{start:50380,size:10},"demo-e2e-resource-providers":{start:50390,size:10},"esm-package-server":{start:50400,size:10},"esm-package-server-hot-reload":{start:50410,size:10},"esm-package-server-cli":{start:50420,size:10},"demo-e2e-unix-socket":{start:50430,size:10},"demo-e2e-distributed":{start:50440,size:20},"demo-e2e-protocol-20260728":{start:50460,size:20},"demo-e2e-testing":{start:50480,size:20},"demo-e2e-answer-shaping":{start:50500,size:10},"demo-e2e-events":{start:50530,size:10},"demo-e2e-events-appointments":{start:50540,size:10},"demo-e2e-events-daemon":{start:50550,size:10},"demo-e2e-events-mail-triage":{start:50560,size:10},"mock-oauth":{start:50900,size:10},"mock-api":{start:50910,size:10},"mock-cimd":{start:50920,size:10},default:{start:51e3,size:100}};var reservedPorts=new Map;var lockedPorts=new Set;var LOCK_MAX_AGE_MS=10*60*1e3;function lockDir(){try{const os=require("node:os");const path=require("node:path");return path.join(os.tmpdir(),"frontmcp-testing-ports")}catch{return void 0}}function pidIsAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function acquirePortLock(port){if(lockedPorts.has(port))return false;let fs;let file;try{fs=require("node:fs");const dir=lockDir();if(!dir)return true;fs.mkdirSync(dir,{recursive:true});file=require("node:path").join(dir,`${port}.lock`)}catch{return true}const payload=JSON.stringify({pid:process.pid,at:Date.now()});for(let attempt=0;attempt<2;attempt++){try{fs.writeFileSync(file,payload,{flag:"wx"});lockedPorts.add(port);return true}catch(error){if(error.code!=="EEXIST")return true;try{const held=JSON.parse(fs.readFileSync(file,"utf8"));const fresh=typeof held.at==="number"&&Date.now()-held.at<LOCK_MAX_AGE_MS;if(fresh&&typeof held.pid==="number"&&pidIsAlive(held.pid))return false;fs.unlinkSync(file)}catch{}}}return false}function releasePortLock(port){if(!lockedPorts.delete(port))return;try{const fs=require("node:fs");const dir=lockDir();if(dir)fs.unlinkSync(require("node:path").join(dir,`${port}.lock`))}catch{}}var projectPortIndex=new Map;function getPortRange(project){const key=project;if(key in E2E_PORT_RANGES){return E2E_PORT_RANGES[key]}return E2E_PORT_RANGES.default}async function reservePort(project,preferredPort){const range=getPortRange(project);const handle=port=>({port,releaseSocket:async()=>{await releasePort(port)},release:async()=>{await releasePort(port);releasePortLock(port)}});const wantsSpecificPort=preferredPort!==void 0&&Number.isInteger(preferredPort)&&preferredPort>0;if(wantsSpecificPort){const reservation=await tryReservePort(preferredPort,project);if(reservation){return handle(preferredPort)}console.warn(`[PortRegistry] Preferred port ${preferredPort} not available for ${project}, allocating from range`)}let index=projectPortIndex.get(project)??0;const maxAttempts=range.size;for(let attempt=0;attempt<maxAttempts;attempt++){const port=range.start+index%range.size;index=(index+1)%range.size;if(reservedPorts.has(port)||lockedPorts.has(port)){continue}const reservation=await tryReservePort(port,project);if(reservation){projectPortIndex.set(project,index);return handle(port)}}for(let port=51e3;port<52e3;port++){if(reservedPorts.has(port)||lockedPorts.has(port))continue;if(await tryReservePort(port,project)){return handle(port)}}throw new Error(`[PortRegistry] Could not reserve a port for ${project}. Range: ${range.start}-${range.start+range.size-1}. Currently reserved: ${Array.from(reservedPorts.keys()).join(", ")}`)}async function tryReservePort(port,project){if(!acquirePortLock(port)){return false}return new Promise(resolve=>{const server=(0,import_net.createServer)();server.once("error",()=>{releasePortLock(port);resolve(false)});server.listen(port,()=>{reservedPorts.set(port,{port,project,holder:server,reservedAt:Date.now()});resolve(true)})})}async function releasePort(port){const reservation=reservedPorts.get(port);if(!reservation){return}return new Promise(resolve=>{reservation.holder.close(()=>{reservedPorts.delete(port);resolve()})})}var SERVER_EXIT_TIMEOUT_MS=12e3;var DEBUG_SERVER=process.env["DEBUG_SERVER"]==="1"||process.env["DEBUG"]==="1";var TestServer=class _TestServer{process=null;options;_info;logs=[];portRelease=null;portReleaseSocket=null;constructor(options,port,portRelease,portReleaseSocket){this.options={port,project:options.project,command:options.command??"",cwd:options.cwd??process.cwd(),env:options.env??{},startupTimeout:options.startupTimeout??3e4,healthCheckPath:options.healthCheckPath??"/health",debug:options.debug??DEBUG_SERVER};this.portRelease=portRelease??null;this.portReleaseSocket=portReleaseSocket??portRelease??null;this._info={baseUrl:`http://localhost:${port}`,port}}static async start(options){const project=options.project??"default";const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const server=new _TestServer(options,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep4(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static async startNx(project,options={}){if(!/^[\w-]+$/.test(project)){throw new Error(`Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`)}const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const serverOptions={...options,port,project,command:`npx nx serve ${project} --port ${port}`,cwd:options.cwd??process.cwd()};const server=new _TestServer(serverOptions,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep4(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static connect(baseUrl){const url=new URL(baseUrl);const port=parseInt(url.port,10)||(url.protocol==="https:"?443:80);const server=new _TestServer({command:"",port},port);server._info={baseUrl:baseUrl.replace(/\/$/,""),port};return server}get info(){return{...this._info}}async stop(){try{await this.stopProcess()}finally{if(this.portRelease){await this.portRelease();this.portRelease=null}this.portReleaseSocket=null}}async stopProcess(){if(this.process){this.log("Stopping server...");const serverPid=this._info.pid!==this._info.shellPid?this._info.pid:void 0;if(this.process.exitCode!==null||this.process.signalCode!==null){this.log(`Server already exited (code: ${this.process.exitCode}, signal: ${this.process.signalCode})`);this.process=null;if(serverPid!==void 0)signalIfRunning(serverPid,"SIGTERM");await this.waitForServerGone(serverPid);return}const pid=this.process.pid;try{if(pid!==void 0){process.kill(-pid,"SIGTERM")}else{this.process.kill("SIGTERM")}}catch{this.process.kill("SIGTERM")}const exitPromise=new Promise(resolve=>{if(this.process){this.process.once("exit",()=>resolve())}else{resolve()}});const killTimeout=setTimeout(()=>{if(this.process){this.log("Force killing server after timeout...");const killPid=this.process.pid;try{if(killPid!==void 0){process.kill(-killPid,"SIGKILL")}else{this.process.kill("SIGKILL")}}catch{this.process.kill("SIGKILL")}}},5e3);await exitPromise;clearTimeout(killTimeout);this.process=null;await this.waitForServerGone(serverPid);this.log("Server stopped")}}async waitForServerGone(serverPid){const deadline=Date.now()+SERVER_EXIT_TIMEOUT_MS;while(Date.now()<deadline){const serverRunning=serverPid!==void 0&&pidIsAlive(serverPid);if(!serverRunning&&!await acceptsConnections(this._info.port))return;await sleep4(100)}if(serverPid!==void 0&&pidIsAlive(serverPid)){this.log("Force killing server process after timeout...");signalIfRunning(serverPid,"SIGKILL")}}async waitForReady(timeout){const timeoutMs=timeout??this.options.startupTimeout;const deadline=Date.now()+timeoutMs;const checkInterval=100;while(Date.now()<deadline){try{const response=await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`,{method:"GET",signal:AbortSignal.timeout(1e3)});if(response.ok||response.status===404){this.log("Server is ready");return}}catch{}await sleep4(checkInterval)}throw new Error(`Server did not become ready within ${timeoutMs}ms`)}async restart(){await this.stopProcess();await this.startProcess()}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}async startProcess(){if(!this.options.command){await this.waitForReady();return}this.log(`Starting server: ${this.options.command}`);const env={...process.env,...this.options.env,PORT:String(this.options.port)};const runtimeEnv=withWorkspaceProtocolFallback(env,this.options.cwd);if(this.portReleaseSocket){await this.portReleaseSocket();this.portReleaseSocket=null;await sleep4(300)}this.process=(0,import_child_process.spawn)(this.options.command,[],{cwd:this.options.cwd,env:runtimeEnv,shell:true,detached:true,stdio:["pipe","pipe","pipe"]});this._info.pid=this.process.pid;this._info.shellPid=this.process.pid;let processExited=false;let exitCode=null;let exitError=null;this.process.stdout?.on("data",data=>{const text=data.toString();this.logs.push(text);if(this.options.debug){console.log("[SERVER]",text)}});this.process.stderr?.on("data",data=>{const text=data.toString();this.logs.push(`[ERROR] ${text}`);if(this.options.debug){console.error("[SERVER ERROR]",text)}});this.process.on("error",err=>{this.logs.push(`[SPAWN ERROR] ${err.message}`);exitError=err;if(this.options.debug){console.error("[SERVER SPAWN ERROR]",err)}});this.process.once("exit",code=>{processExited=true;exitCode=code;this.log(`Server process exited with code ${code}`)});try{await this.waitForReadyWithExitDetection(()=>{if(exitError){return{exited:true,error:exitError}}if(processExited){const allLogs=this.logs.join("\n");const errorLogs=this.logs.filter(l=>l.includes("[ERROR]")||l.toLowerCase().includes("error")).join("\n");return{exited:true,error:new ServerStartError(`Server process exited unexpectedly with code ${exitCode}.
16
+ ${intervalSummary}${perfStats}`}return{hasLeak,leakSizePerIteration:hasLeak?growthRate:0,totalGrowth,growthRate,rSquared,samples,message,intervals,graphData,durationMs,requestsPerSecond}}generateIntervals(samples,intervalSize){const intervals=[];const safeIntervalSize=intervalSize<=0?1:intervalSize;const numIntervals=Math.ceil(samples.length/safeIntervalSize);for(let i=0;i<numIntervals;i++){const startIdx=i*safeIntervalSize;const endIdx=Math.min((i+1)*safeIntervalSize-1,samples.length-1);if(startIdx>=samples.length)break;const heapAtStart=samples[startIdx];const heapAtEnd=samples[endIdx];const delta=heapAtEnd-heapAtStart;const iterationsInInterval=endIdx-startIdx+1;const growthRatePerIteration=iterationsInInterval>1?delta/(iterationsInInterval-1):0;intervals.push({startIteration:startIdx,endIteration:endIdx,heapAtStart,heapAtEnd,delta,deltaFormatted:formatBytes(delta),growthRatePerIteration})}return intervals}generateGraphData(samples){if(samples.length===0)return[];const baselineHeap=samples[0];return samples.map((heapUsed,iteration)=>({iteration,heapUsed,heapUsedFormatted:formatBytes(heapUsed),cumulativeDelta:heapUsed-baselineHeap,cumulativeDeltaFormatted:formatBytes(heapUsed-baselineHeap)}))}};function sleep2(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function assertNoLeak(operation,options){const detector=new LeakDetector;const result=await detector.detectLeak(operation,options);if(result.hasLeak){throw new Error(`Memory leak detected: ${result.message}`)}return result}function createLeakDetector(){return new LeakDetector}function createPerfFixtures(testName,project){return new PerfFixturesImpl(testName,project)}var PerfFixturesImpl=class{constructor(testName,project){this.testName=testName;this.project=project;this.collector=new MetricsCollector;this.leakDetector=new LeakDetector}testName;project;collector;leakDetector;baselineSnapshot=null;startTime=0;issues=[];leakResults=[];async baseline(){this.startTime=Date.now();this.baselineSnapshot=await this.collector.captureBaseline();return this.baselineSnapshot}measure(label){return this.collector.captureSnapshot(label)}async checkLeak(operation,options){const result=await this.leakDetector.detectLeak(operation,options);this.leakResults.push(result);if(result.hasLeak){this.issues.push({type:"memory-leak",severity:"error",message:result.message,metric:"heapUsed",actual:result.totalGrowth,expected:options?.threshold??1024*1024})}return result}async checkLeakParallel(operationFactory,options){const result=await this.leakDetector.detectLeakParallel(operationFactory,options);this.leakResults.push(result);if(result.hasLeak){this.issues.push({type:"memory-leak",severity:"error",message:result.message,metric:"heapUsed",actual:result.totalGrowth,expected:options?.threshold??1024*1024})}return result}assertThresholds(thresholds){const finalSnapshot=this.collector.captureSnapshot("final");const baseline=this.collector.getBaseline();if(!baseline){throw new Error("Cannot assert thresholds without baseline. Call baseline() first.")}const duration=Date.now()-this.startTime;const memoryDelta=this.collector.calculateMemoryDelta(finalSnapshot.memory);if(thresholds.maxHeapDelta!==void 0&&memoryDelta){if(memoryDelta.heapUsed>thresholds.maxHeapDelta){const issue={type:"threshold-exceeded",severity:"error",message:`Heap delta ${formatBytes(memoryDelta.heapUsed)} exceeds threshold ${formatBytes(thresholds.maxHeapDelta)}`,metric:"heapUsed",actual:memoryDelta.heapUsed,expected:thresholds.maxHeapDelta};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxDurationMs!==void 0){if(duration>thresholds.maxDurationMs){const issue={type:"threshold-exceeded",severity:"error",message:`Duration ${formatDuration(duration)} exceeds threshold ${formatDuration(thresholds.maxDurationMs)}`,metric:"durationMs",actual:duration,expected:thresholds.maxDurationMs};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxCpuTime!==void 0){const cpuUsage=this.collector.getCpuUsage();if(cpuUsage.total>thresholds.maxCpuTime){const issue={type:"threshold-exceeded",severity:"error",message:`CPU time ${cpuUsage.total}\xB5s exceeds threshold ${thresholds.maxCpuTime}\xB5s`,metric:"cpuTime",actual:cpuUsage.total,expected:thresholds.maxCpuTime};this.issues.push(issue);throw new Error(issue.message)}}if(thresholds.maxRssDelta!==void 0&&memoryDelta){if(memoryDelta.rss>thresholds.maxRssDelta){const issue={type:"threshold-exceeded",severity:"error",message:`RSS delta ${formatBytes(memoryDelta.rss)} exceeds threshold ${formatBytes(thresholds.maxRssDelta)}`,metric:"rss",actual:memoryDelta.rss,expected:thresholds.maxRssDelta};this.issues.push(issue);throw new Error(issue.message)}}}getMeasurements(){return this.collector.getMeasurements()}getTestName(){return this.testName}getProject(){return this.project}getIssues(){return[...this.issues]}buildMeasurement(){const endTime=Date.now();const finalSnapshot=this.collector.captureSnapshot("final");const baseline=this.collector.getBaseline();const memoryDelta=baseline?this.collector.calculateMemoryDelta(finalSnapshot.memory):void 0;return{name:this.testName,project:this.project,baseline:baseline??finalSnapshot,measurements:this.collector.getMeasurements(),final:finalSnapshot,timing:{startTime:this.startTime||endTime,endTime,durationMs:endTime-(this.startTime||endTime)},memoryDelta:memoryDelta??void 0,issues:this.getIssues(),leakDetectionResults:this.leakResults.length>0?this.leakResults:void 0}}reset(){this.collector.reset();this.baselineSnapshot=null;this.startTime=0;this.issues=[];this.leakResults=[]}};var MEASUREMENTS_KEY="__FRONTMCP_PERF_MEASUREMENTS__";function getGlobalMeasurementsArray(){if(!globalThis[MEASUREMENTS_KEY]){globalThis[MEASUREMENTS_KEY]=[]}return globalThis[MEASUREMENTS_KEY]}function addGlobalMeasurement(measurement){getGlobalMeasurementsArray().push(measurement)}function getGlobalMeasurements(){return[...getGlobalMeasurementsArray()]}function clearGlobalMeasurements(){const arr=getGlobalMeasurementsArray();arr.length=0}function getMeasurementsForProject(project){return getGlobalMeasurementsArray().filter(m=>m.project===project)}var import_jose=require("jose");var TestTokenFactory=class{issuer;audience;privateKey=null;publicKey=null;jwk=null;keyId;hmacSecret;constructor(options={}){this.issuer=options.issuer??"https://test.frontmcp.local";this.audience=options.audience??"frontmcp-test";this.keyId=`test-key-${Date.now()}`;this.hmacSecret=options.hmacSecret?new TextEncoder().encode(options.hmacSecret):null}get isHmac(){return this.hmacSecret!==null}get alg(){return this.isHmac?"HS256":"RS256"}signingKey(){if(this.hmacSecret)return this.hmacSecret;if(!this.privateKey){throw new Error("Private key not initialized")}return this.privateKey}async ensureKeys(){if(this.isHmac)return;if(this.privateKey&&this.publicKey)return;const{publicKey,privateKey}=await(0,import_jose.generateKeyPair)("RS256",{extractable:true});this.privateKey=privateKey;this.publicKey=publicKey;this.jwk=await(0,import_jose.exportJWK)(publicKey);this.jwk.kid=this.keyId;this.jwk.use="sig";this.jwk.alg="RS256"}async createTestToken(options){await this.ensureKeys();const nowMs=Date.now();const iat=Math.floor(nowMs/1e3);const exp=options.exp??3600;const payload={iss:options.iss??this.issuer,sub:options.sub,aud:options.aud??this.audience,iat,exp:Math.ceil(nowMs/1e3)+exp,scope:options.scopes?.join(" "),...options.claims};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}async createAdminToken(sub="admin-001"){return this.createTestToken({sub,scopes:["admin:*","read","write","delete"],claims:{email:"admin@test.local",name:"Test Admin",role:"admin"}})}async createUserToken(sub="user-001",scopes=["read","write"]){return this.createTestToken({sub,scopes,claims:{email:"user@test.local",name:"Test User",role:"user"}})}async createAnonymousToken(expiresIn){return this.createTestToken({sub:`anon:${Date.now()}`,scopes:["anonymous"],exp:expiresIn,claims:{name:"Anonymous",role:"anonymous"}})}async createExpiredToken(options){await this.ensureKeys();const now=Math.floor(Date.now()/1e3);const payload={iss:this.issuer,sub:options.sub,aud:this.audience,iat:now-7200,exp:now-3600};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}createTokenWithInvalidSignature(options){const now=Math.floor(Date.now()/1e3);const headerObj=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const header=Buffer.from(JSON.stringify(headerObj)).toString("base64url");const payload=Buffer.from(JSON.stringify({iss:this.issuer,sub:options.sub,aud:this.audience,iat:now,exp:now+3600})).toString("base64url");const signature=Buffer.from("invalid-signature-"+Date.now()).toString("base64url");return`${header}.${payload}.${signature}`}async getPublicJwks(){if(this.isHmac){throw new Error("getPublicJwks() is not available in HS256 mode (gateway tokens use a shared secret)")}await this.ensureKeys();if(!this.jwk){throw new Error("JWK not initialized")}return{keys:[this.jwk]}}getIssuer(){return this.issuer}getAudience(){return this.audience}};var import_protocol3=require("@frontmcp/protocol");var import_sdk=require("@frontmcp/sdk");var import_utils4=require("@frontmcp/utils");var DefaultMockRegistry=class{mocks=[];add(mock){const entry={definition:mock,callCount:0,calls:[],remainingUses:mock.times??Infinity};this.mocks.push(entry);return{remove:()=>{const index=this.mocks.indexOf(entry);if(index!==-1){this.mocks.splice(index,1)}},callCount:()=>entry.callCount,calls:()=>[...entry.calls]}}clear(){this.mocks=[]}getAll(){return this.mocks.map(e=>e.definition)}match(request){for(const entry of this.mocks){if(entry.remainingUses<=0)continue;const{definition}=entry;if(definition.method!==request.method)continue;if(definition.params!==void 0){const params=request.params??{};if(typeof definition.params==="function"){if(!definition.params(params))continue}else{if(!this.paramsMatch(definition.params,params))continue}}entry.callCount++;entry.calls.push(request);entry.remainingUses--;return definition}return void 0}paramsMatch(expected,actual){for(const[key,value]of Object.entries(expected)){if(!(key in actual))return false;const actualValue=actual[key];if(Array.isArray(value)){if(!Array.isArray(actualValue))return false;if(value.length!==actualValue.length)return false;for(let i=0;i<value.length;i++){const expectedItem=value[i];const actualItem=actualValue[i];if(typeof expectedItem==="object"&&expectedItem!==null){if(typeof actualItem!=="object"||actualItem===null)return false;if(!this.paramsMatch(expectedItem,actualItem)){return false}}else if(actualItem!==expectedItem){return false}}}else if(typeof value==="object"&&value!==null){if(typeof actualValue!=="object"||actualValue===null)return false;if(!this.paramsMatch(value,actualValue)){return false}}else if(actualValue!==value){return false}}return true}};var mockResponse={success(result,id=1){return{jsonrpc:"2.0",id,result}},error(code,message,data,id=1){return{jsonrpc:"2.0",id,error:{code,message,data}}},toolResult(content,id=1){return{jsonrpc:"2.0",id,result:{content}}},toolsList(tools,id=1){return{jsonrpc:"2.0",id,result:{tools}}},resourcesList(resources,id=1){return{jsonrpc:"2.0",id,result:{resources}}},resourceRead(contents,id=1){return{jsonrpc:"2.0",id,result:{contents}}},errors:{methodNotFound:(method,id=1)=>mockResponse.error(-32601,`Method not found: ${method}`,void 0,id),invalidParams:(message,id=1)=>mockResponse.error(-32602,message,void 0,id),internalError:(message,id=1)=>mockResponse.error(-32603,message,void 0,id),resourceNotFound:(uri,id=1)=>mockResponse.error(-32002,`Resource not found: ${uri}`,{uri},id),toolNotFound:(name,id=1)=>mockResponse.error(-32601,`Tool not found: ${name}`,{name},id),unauthorized:(id=1)=>mockResponse.error(-32001,"Unauthorized",void 0,id),forbidden:(id=1)=>mockResponse.error(-32003,"Forbidden",void 0,id)}};var DefaultInterceptorChain=class{request=[];response=[];mocks;constructor(){this.mocks=new DefaultMockRegistry}addRequestInterceptor(interceptor){this.request.push(interceptor);return()=>{const index=this.request.indexOf(interceptor);if(index!==-1){this.request.splice(index,1)}}}addResponseInterceptor(interceptor){this.response.push(interceptor);return()=>{const index=this.response.indexOf(interceptor);if(index!==-1){this.response.splice(index,1)}}}async processRequest(request,meta){let currentRequest=request;const mockDef=this.mocks.match(request);if(mockDef){if(mockDef.delay&&mockDef.delay>0){await sleep3(mockDef.delay)}let mockResponse2;if(typeof mockDef.response==="function"){mockResponse2=await mockDef.response(request)}else{mockResponse2=mockDef.response}return{type:"mock",response:{...mockResponse2,id:request.id??mockResponse2.id}}}for(const interceptor of this.request){const ctx={request:currentRequest,meta};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentRequest=result.request;break;case"mock":return{type:"mock",response:{...result.response,id:request.id??result.response.id}};case"error":return{type:"error",error:result.error}}}return{type:"continue",request:currentRequest}}async processResponse(request,response,durationMs){let currentResponse=response;for(const interceptor of this.response){const ctx={request,response:currentResponse,durationMs};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentResponse=result.response;break}}return currentResponse}clear(){this.request=[];this.response=[];this.mocks.clear()}};function sleep3(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function errorName(err){if(typeof err!=="object"||err===null)return void 0;const name=err.name;return typeof name==="string"?name:void 0}function isAbortError(err){return errorName(err)==="AbortError"}function errorMessage(err,fallback="Unknown error"){if(typeof err==="string"&&err)return err;if(typeof err==="object"&&err!==null){const message=err.message;if(typeof message==="string"&&message)return message}return fallback}var interceptedErrors=new WeakSet;function markInterceptedError(err){interceptedErrors.add(err);return err}function isInterceptedError(err){return typeof err==="object"&&err!==null&&interceptedErrors.has(err)}var import_protocol=require("@frontmcp/protocol");var import_utils=require("@frontmcp/utils");var SENTINEL_PREFIX="=?base64?";var SENTINEL_SUFFIX="?=";var NAME_PARAM_BY_METHOD={"tools/call":"name","prompts/get":"name","resources/read":"uri","events/poll":"name","events/stream":"name","events/subscribe":"name","events/unsubscribe":"name"};function isStatelessRequest(protocolVersion,method){if(protocolVersion===import_protocol.PROTOCOL_2026_07_28)return true;return import_protocol.MCP_20260728_ADDED_METHODS.includes(method??"")}function encodeHeaderValue(value){const needsEncoding=/[^\x20-\x7e]/.test(value)||value!==value.trim()||value.startsWith(SENTINEL_PREFIX);if(!needsEncoding)return value;return`${SENTINEL_PREFIX}${(0,import_utils.base64Encode)(new TextEncoder().encode(value))}${SENTINEL_SUFFIX}`}function withRequestMeta(message,meta){const params=message.params??{};const callerMeta=params["_meta"];return{...message,params:{...params,_meta:{...meta,...callerMeta}}}}function revisionHeaders(message,toolInputSchema){const headers={"MCP-Protocol-Version":import_protocol.PROTOCOL_2026_07_28};if(!message)return headers;headers["Mcp-Method"]=message.method;const nameParam=NAME_PARAM_BY_METHOD[message.method];const name=nameParam?message.params?.[nameParam]:void 0;if(typeof name==="string")headers["Mcp-Name"]=encodeHeaderValue(name);if(message.method==="tools/call"){Object.assign(headers,paramHeaders(toolInputSchema,message.params?.["arguments"]))}return headers}function paramHeaders(schema,args){const headers={};const properties=schema?.properties??{};const values=typeof args==="object"&&args!==null?args:{};for(const[key,property]of Object.entries(properties)){const value=values[key];const headerName=property?.["x-mcp-header"];if(typeof headerName==="string"&&headerName&&isHeaderValue(value)){headers[`Mcp-Param-${headerName}`]=encodeHeaderValue(String(value))}Object.assign(headers,paramHeaders(property,value))}return headers}function isHeaderValue(value){return typeof value==="string"||typeof value==="boolean"||Number.isSafeInteger(value)}function jsonRpcErrorIn(body){try{const parsed=JSON.parse(body);const error=parsed.error;if(typeof error?.code!=="number"||typeof error.message!=="string")return void 0;return{jsonrpc:"2.0",id:parsed.id??null,error}}catch{return void 0}}function acknowledgedFilterIn(eventData){try{const message=JSON.parse(eventData);if(message.method!==import_protocol.SUBSCRIPTIONS_ACKNOWLEDGED_METHOD)return void 0;return message.params?.notifications??{}}catch{return void 0}}var import_utils2=require("@frontmcp/utils");var SseEventSplitter=class{pendingParts=[];pendingEndsWithLineFeed=false;carriageReturnHeld=false;push(chunk){let text=this.carriageReturnHeld?`\r${chunk}`:chunk;this.carriageReturnHeld=text.endsWith("\r");if(this.carriageReturnHeld)text=text.slice(0,-1);text=text.replace(/\r\n?/g,"\n");const events=[];let start=0;if(this.pendingEndsWithLineFeed&&text.startsWith("\n")){events.push(this.takePending().slice(0,-1));start=1}for(let end=text.indexOf("\n\n",start);end!==-1;end=text.indexOf("\n\n",start)){events.push(this.takePending()+text.slice(start,end));start=end+2}const rest=text.slice(start);if(rest){this.pendingParts.push(rest);this.pendingEndsWithLineFeed=rest.endsWith("\n")}return events}remainder(){return this.pendingParts.join("")+(this.carriageReturnHeld?"\r":"")}takePending(){const text=this.pendingParts.join("");this.pendingParts.length=0;this.pendingEndsWithLineFeed=false;return text}};var DEFAULT_TIMEOUT=3e4;var SseTransport=class{baseUrl;entryPath;timeout;authHeaders;publicMode;debug;clientInfo;notificationHandler;interceptors;elicitationHandler;state="disconnected";authToken;sessionId;messageEndpoint;stream;pending=new Map;connectionCount=0;reconnectCount=0;lastRequestHeaders={};constructor(config){this.baseUrl=config.baseUrl.replace(/\/$/,"");this.entryPath=config.entryPath;this.timeout=config.timeout??DEFAULT_TIMEOUT;this.authHeaders=config.auth?.headers??{};this.authToken=config.auth?.token;this.publicMode=config.publicMode??false;this.debug=config.debug??false;this.clientInfo=config.clientInfo;this.notificationHandler=config.notificationHandler;this.interceptors=config.interceptors;this.elicitationHandler=config.elicitationHandler}async connect(){this.state="connecting";this.connectionCount++;try{if(!this.publicMode&&!this.authToken){await this.requestAnonymousToken()}await this.openStream();this.state="connected";this.log(`Connected; messages go to ${this.messageEndpoint}`)}catch(error){this.state="error";this.stream?.abort();this.stream=void 0;throw error}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const intercepted=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"sse",sessionId:this.sessionId});switch(intercepted.type){case"mock":return await this.interceptors.processResponse(message,intercepted.response,Date.now()-startTime);case"error":throw markInterceptedError(intercepted.error);case"continue":message=intercepted.request;break}}let response;if(message.id===void 0){await this.post(JSON.stringify(message));response={jsonrpc:"2.0",id:null,result:void 0}}else{response=await this.postAndAwait(message.id,JSON.stringify(message))}if(this.interceptors){response=await this.interceptors.processResponse(message,response,Date.now()-startTime)}return response}async notify(message){this.ensureConnected();const result=await this.post(JSON.stringify(message));if(!result.ok)this.log(`HTTP ${result.status} on notification: ${result.body}`)}async sendRaw(data){this.ensureConnected();let id;try{const parsed=JSON.parse(data);if(typeof parsed.id==="string"||typeof parsed.id==="number")id=parsed.id}catch{}if(id!==void 0)return this.postAndAwait(id,data);const result=await this.post(data);if(!result.ok){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:result.body}}}return{jsonrpc:"2.0",id:null,result:void 0}}async close(){this.closeStream("Transport closed");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0;this.log("SSE transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.timeout=ms}getMessageEndpoint(){return this.messageEndpoint}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}async simulateDisconnect(){this.closeStream("Simulated disconnect");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0}async waitForReconnect(timeoutMs){this.reconnectCount++;let timer;try{await Promise.race([this.connect(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("Timeout waiting for reconnection")),timeoutMs)})])}finally{clearTimeout(timer)}}async openStream(){const controller=new AbortController;this.stream=controller;const url=this.sseUrl();const{"Content-Type":_contentType,...headers}=this.buildHeaders();this.log(`GET ${url}`);const connectTimer=setTimeout(()=>controller.abort(),this.timeout);let response;try{response=await fetch(url,{method:"GET",headers:{...headers,Accept:"text/event-stream"},signal:controller.signal})}catch(error){clearTimeout(connectTimer);throw new Error(isAbortError(error)?`SSE connection to ${url} timed out after ${this.timeout}ms`:`SSE connection to ${url} failed: ${errorMessage(error)}`,{cause:error})}const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){clearTimeout(connectTimer);const body=await response.text().catch(()=>"");throw new Error(`SSE connection to ${url} failed: HTTP ${response.status} ${response.statusText}${body?` \u2014 ${body}`:""}. The legacy HTTP+SSE transport needs a server that serves it (@FrontMcp({ transport: { protocol: { legacy: true } } })).`)}const endpoint=new Promise((resolve,reject)=>{const reader=response.body?.getReader();if(!reader){reject(new Error(`SSE connection to ${url} has no body`));return}void this.readStream(controller,reader,resolve,reject)});try{const data=await endpoint;const messageUrl=new URL(data,url);if(messageUrl.origin!==new URL(url).origin){throw new Error(`SSE server at ${url} named a message endpoint on another origin (${messageUrl.origin}); the legacy SSE transport only posts to the origin it connected to.`)}this.messageEndpoint=messageUrl.toString();this.sessionId=messageUrl.searchParams.get("sessionId")??void 0}finally{clearTimeout(connectTimer)}}async readStream(controller,reader,onEndpoint,onEndpointError){const decoder=new TextDecoder;const splitter=new SseEventSplitter;let endpointSeen=false;try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){for(const text of splitter.push(decoder.decode(chunk.value,{stream:true}))){const event=parseSSEEvent(text);if(!event)continue;if(event.type==="endpoint"){if(!endpointSeen){endpointSeen=true;onEndpoint(event.data)}continue}await this.handleMessage(event.data)}}}catch(error){if(!controller.signal.aborted)this.log("SSE stream failed:",error)}finally{reader.releaseLock()}if(!endpointSeen){onEndpointError(new Error(controller.signal.aborted?`SSE stream at ${this.sseUrl()} sent no endpoint event within ${this.timeout}ms`:`SSE stream at ${this.sseUrl()} ended before the server sent its endpoint`))}if(this.stream===controller){this.stream=void 0;this.rejectPending("SSE stream closed by the server");if(this.state==="connected")this.state="disconnected"}}async handleMessage(data){let message;try{message=JSON.parse(data)}catch{this.log("Ignoring SSE event that is not JSON:",data);return}if(!message||typeof message!=="object")return;if(typeof message.method==="string"){const request=message;if(request.id===void 0||request.id===null){this.notificationHandler?.(request);return}await this.answerServerRequest(request);return}if(message.id!==void 0&&message.id!==null){const pending=this.pending.get(message.id);if(pending){clearTimeout(pending.timer);this.pending.delete(message.id);pending.resolve(message)}}}async answerServerRequest(request){const id=request.id;let reply;if(request.method==="elicitation/create"){reply={jsonrpc:"2.0",id,result:await this.elicit(request.params)}}else if(request.method==="ping"){reply={jsonrpc:"2.0",id,result:{}}}else{reply={jsonrpc:"2.0",id,error:{code:-32601,message:`Method not found: ${request.method}`}}}const result=await this.post(JSON.stringify(reply));if(!result.ok)this.log(`HTTP ${result.status} answering ${request.method}: ${result.body}`)}async elicit(params){if(!this.elicitationHandler)return{action:"decline"};try{return await this.elicitationHandler(params)}catch(error){this.log("Elicitation handler error:",error);return{action:"cancel"}}}closeStream(reason){const controller=this.stream;this.stream=void 0;controller?.abort();this.rejectPending(reason)}rejectPending(reason){for(const[id,pending]of this.pending){clearTimeout(pending.timer);pending.resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:reason}})}this.pending.clear()}async postAndAwait(id,body){const answer=new Promise(resolve=>{const timer=setTimeout(()=>{this.pending.delete(id);resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:`Request timeout after ${this.timeout}ms`}})},this.timeout);this.pending.set(id,{resolve,timer})});const result=await this.post(body);if(!result.ok){const pending=this.pending.get(id);if(pending){clearTimeout(pending.timer);this.pending.delete(id)}return{jsonrpc:"2.0",id,error:{code:-32e3,message:`HTTP ${result.status}: ${result.statusText}`,data:result.body}}}return answer}async post(body){const endpoint=this.messageEndpoint;if(!endpoint)throw new Error("SSE transport has no message endpoint. Call connect() first.");const headers=this.buildHeaders();this.lastRequestHeaders=headers;this.log(`POST ${endpoint}`,body);const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),this.timeout);try{const response=await fetch(endpoint,{method:"POST",headers,body,signal:controller.signal});const text=await response.text();return{ok:response.ok,status:response.status,statusText:response.statusText,body:text}}catch(error){if(isAbortError(error)){return{ok:false,status:0,statusText:`timeout after ${this.timeout}ms`,body:""}}throw error}finally{clearTimeout(timer)}}async requestAnonymousToken(){const url=new URL(this.baseUrl);url.pathname=`${(0,import_utils2.trimTrailing)(url.pathname,"/")}/oauth/token`;url.search="";const tokenUrl=url.toString();try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:crypto.randomUUID(),resource:this.baseUrl})});if(!response.ok){this.log(`No anonymous token (HTTP ${response.status})`);return}const token=await response.json();if(token.access_token)this.authToken=token.access_token}catch(error){this.log("Error requesting anonymous token:",error)}}sseUrl(){const url=new URL(this.baseUrl);const entry=(0,import_utils2.trimSlashes)(this.entryPath);const basePath=(0,import_utils2.trimTrailing)(url.pathname,"/");url.pathname=entry?`${basePath}/${entry}/sse`:`${basePath}/sse`;return url.toString()}buildHeaders(){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.clientInfo)headers["User-Agent"]=`${this.clientInfo.name}/${this.clientInfo.version}`;if(this.authToken)headers["Authorization"]=`Bearer ${this.authToken}`;if(this.sessionId)headers["mcp-session-id"]=this.sessionId;Object.assign(headers,this.authHeaders);return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.debug){console.log(`[SSE] ${message}`,data??"")}}};function parseSSEEvent(text){let type="message";const data=[];for(const line of text.split("\n")){if(line.startsWith(":"))continue;const colon=line.indexOf(":");const field=colon===-1?line:line.slice(0,colon);const value=colon===-1?"":line.slice(colon+1).replace(/^ /,"");if(field==="event")type=value;else if(field==="data")data.push(value)}return data.length>0?{type,data:data.join("\n")}:void 0}var import_protocol2=require("@frontmcp/protocol");var import_utils3=require("@frontmcp/utils");var DEFAULT_TIMEOUT2=3e4;var NOTIFICATION_STREAM_REOPEN_DELAY_MS=250;var StreamableHttpTransport=class{config;state="disconnected";sessionId;authToken;connectionCount=0;reconnectCount=0;lastRequestHeaders={};interceptors;publicMode;elicitationHandler;notificationHandler;notificationStream;notificationProtocolVersion="";notificationStreamReopenTimer;subscriptionStream;protocolVersion;requestMeta;toolInputSchemas=new Map;constructor(config){this.config={baseUrl:config.baseUrl.replace(/\/$/,""),entryPath:config.entryPath,timeout:config.timeout??DEFAULT_TIMEOUT2,auth:config.auth??{},publicMode:config.publicMode??false,debug:config.debug??false,interceptors:config.interceptors,clientInfo:config.clientInfo};this.authToken=config.auth?.token;this.interceptors=config.interceptors;this.publicMode=config.publicMode??false;this.elicitationHandler=config.elicitationHandler;this.notificationHandler=config.notificationHandler;this.protocolVersion=config.protocolVersion;this.requestMeta={[import_protocol2.MCP_20260728_META.protocolVersion]:import_protocol2.PROTOCOL_2026_07_28,...config.clientInfo&&{[import_protocol2.MCP_20260728_META.clientInfo]:config.clientInfo},[import_protocol2.MCP_20260728_META.clientCapabilities]:config.capabilities??{},...config.logLevel&&{[import_protocol2.MCP_20260728_META.logLevel]:config.logLevel}}}async connect(){this.state="connecting";this.connectionCount++;try{if(this.publicMode){this.log("Public mode: connecting without authentication");this.state="connected";return}if(!this.authToken){await this.requestAnonymousToken()}this.state="connected";this.log("Connected to StreamableHTTP transport")}catch(error){this.state="error";throw error}}async requestAnonymousToken(){const clientId=crypto.randomUUID();const tokenUrl=`${this.config.baseUrl}/oauth/token`;this.log(`Requesting anonymous token from ${tokenUrl}`);try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:clientId,resource:this.config.baseUrl})});if(!response.ok){const errorText=await response.text();this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);return}const tokenResponse=await response.json();if(tokenResponse.access_token){this.authToken=tokenResponse.access_token;this.log("Anonymous token acquired successfully")}}catch(error){this.log(`Error requesting anonymous token: ${error}`)}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const interceptResult=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"streamable-http",sessionId:this.sessionId});switch(interceptResult.type){case"mock":{const mockResponse2=await this.interceptors.processResponse(message,interceptResult.response,Date.now()-startTime);return mockResponse2}case"error":throw markInterceptedError(interceptResult.error);case"continue":message=interceptResult.request;break}}const stateless=isStatelessRequest(this.protocolVersion,message.method);const outgoing=stateless?withRequestMeta(message,this.requestMeta):message;const headers=this.buildHeaders(stateless,outgoing);this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url}`,outgoing);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(outgoing),signal:controller.signal});const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}let jsonResponse;if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status}: ${errorText}`);const rpcError=stateless&&!isAuthStatus(response.status)?jsonRpcErrorIn(errorText):void 0;jsonResponse=rpcError??{jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`HTTP ${response.status}: ${response.statusText}`,data:errorText}}}else{const contentType=response.headers.get("content-type")??"";if(contentType.includes("text/event-stream")){jsonResponse=await this.handleSSEResponseWithElicitation(response,message)}else{const text=await response.text();this.log("Response:",text);if(!text.trim()){jsonResponse={jsonrpc:"2.0",id:message.id??null,result:void 0}}else{jsonResponse=JSON.parse(text)}}}if(stateless&&message.method==="tools/list")this.rememberToolInputSchemas(jsonResponse.result);if(this.interceptors){jsonResponse=await this.interceptors.processResponse(message,jsonResponse,Date.now()-startTime)}clearTimeout(timeoutId);return jsonResponse}catch(error){clearTimeout(timeoutId);if(isAbortError(error)){return{jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`Request timeout after ${this.config.timeout}ms`}}}throw error}}async notify(message){this.ensureConnected();const headers=this.buildHeaders(isStatelessRequest(this.protocolVersion,message.method),message);this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (notification)`,message);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(message),signal:controller.signal});clearTimeout(timeoutId);const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status} on notification: ${errorText}`)}}catch(error){clearTimeout(timeoutId);if(!isAbortError(error)){throw error}}}async sendRaw(data){this.ensureConnected();const headers=this.buildHeaders(isStatelessRequest(this.protocolVersion,void 0));this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (raw)`,data);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:data,signal:controller.signal});clearTimeout(timeoutId);const text=await response.text();if(!text.trim()){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}}}return JSON.parse(text)}catch(error){clearTimeout(timeoutId);return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:errorMessage(error)}}}}async openNotificationStream(protocolVersion){this.notificationProtocolVersion=protocolVersion;await this.connectNotificationStream()}async listen(id,notifications){this.ensureConnected();this.closeSubscriptionStream();const controller=new AbortController;this.subscriptionStream=controller;const message=withRequestMeta({jsonrpc:"2.0",id,method:"subscriptions/listen",params:{notifications}},this.requestMeta);let ackTimer;const acknowledged=await new Promise(resolve=>{ackTimer=setTimeout(()=>resolve(void 0),this.config.timeout);void this.readSubscriptionStream(controller,message,resolve)});clearTimeout(ackTimer);if(!acknowledged&&this.subscriptionStream===controller)this.closeSubscriptionStream();return acknowledged}async streamRequest(message,onNotification,signal){this.ensureConnected();const stateless=isStatelessRequest(this.protocolVersion,message.method);const outgoing=stateless?withRequestMeta(message,this.requestMeta):message;let response;try{response=await fetch(this.mcpUrl(),{method:"POST",headers:this.buildHeaders(stateless,outgoing),body:JSON.stringify(outgoing),signal})}catch(error){if(isAbortError(error))return void 0;throw error}const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!isEventStream||!response.body){const text=await response.text();const parsed=parsedJsonRpc(text);if(response.ok&&parsed&&"result"in parsed)return parsed;const error={code:-32e3,message:`HTTP ${response.status}: ${response.statusText}`,data:text};return jsonRpcErrorIn(text)??{jsonrpc:"2.0",id:message.id??null,error}}let finalResponse;await this.readEventStream(response.body.getReader(),async event=>{const parsed=parsedJsonRpc(event.data);if(parsed&&"method"in parsed&&parsed["id"]===void 0)onNotification(parsed);else if(parsed&&("result"in parsed||"error"in parsed))finalResponse=parsed});return finalResponse}async close(){this.closeNotificationStream();this.closeSubscriptionStream();this.state="disconnected";this.sessionId=void 0;this.log("StreamableHTTP transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.config.timeout=ms}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}async simulateDisconnect(){this.closeNotificationStream();this.closeSubscriptionStream();this.state="disconnected";this.sessionId=void 0}async waitForReconnect(timeoutMs){const deadline=Date.now()+timeoutMs;this.reconnectCount++;await this.connect();while(Date.now()<deadline){if(this.state==="connected"){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for reconnection")}closeNotificationStream(){clearTimeout(this.notificationStreamReopenTimer);this.notificationStream?.abort();this.notificationStream=void 0}async connectNotificationStream(){if(!this.sessionId||this.notificationStream)return;const controller=new AbortController;this.notificationStream=controller;const{"Content-Type":_contentType,...headers}=this.buildHeaders();const established=fetch(this.mcpUrl(),{method:"GET",headers:{...headers,Accept:"text/event-stream","MCP-Protocol-Version":this.notificationProtocolVersion},signal:controller.signal}).then(async response=>{const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){await response.body?.cancel();this.log(`Server offers no notification stream (HTTP ${response.status})`);this.releaseNotificationStream(controller);return}void this.readNotificationStream(controller,response.body.getReader())},error=>{this.log("Failed to open the notification stream:",error);this.releaseNotificationStream(controller)});let establishTimer;const establishDeadline=new Promise(resolve=>{establishTimer=setTimeout(resolve,this.config.timeout)});await Promise.race([established,establishDeadline]);clearTimeout(establishTimer)}releaseNotificationStream(controller){if(this.notificationStream===controller)this.notificationStream=void 0}closeSubscriptionStream(){this.subscriptionStream?.abort();this.subscriptionStream=void 0}async readSubscriptionStream(controller,message,acknowledge){try{const response=await fetch(this.mcpUrl(),{method:"POST",headers:this.buildHeaders(true,message),body:JSON.stringify(message),signal:controller.signal});const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){await response.body?.cancel();this.log(`Server opened no subscriptions/listen stream (HTTP ${response.status})`)}else{await this.readEventStream(response.body.getReader(),async event=>{const filter=acknowledgedFilterIn(event.data);if(filter)acknowledge(filter);else await this.handleSSEEvent(event)})}}catch(error){this.log("subscriptions/listen failed:",error)}acknowledge(void 0)}async readNotificationStream(controller,reader){await this.readEventStream(reader,event=>this.handleSSEEvent(event));if(controller.signal.aborted||this.notificationStream!==controller)return;this.releaseNotificationStream(controller);this.notificationStreamReopenTimer=setTimeout(()=>void this.connectNotificationStream(),NOTIFICATION_STREAM_REOPEN_DELAY_MS)}async readEventStream(reader,onEvent){const decoder=new TextDecoder;const splitter=new SseEventSplitter;try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){for(const eventText of splitter.push(decoder.decode(chunk.value,{stream:true}))){for(const event of this.parseSSEEvents(eventText,void 0).events){await onEvent(event)}}}}catch(error){this.log("Event stream ended:",error)}finally{reader.releaseLock()}}rememberToolInputSchemas(result){const tools=result?.tools;if(!Array.isArray(tools))return;for(const tool of tools){if(typeof tool?.name==="string")this.toolInputSchemas.set(tool.name,tool.inputSchema)}}async handleSSEResponseWithElicitation(response,originalRequest){this.log("handleSSEResponseWithElicitation: starting",{requestId:originalRequest.id});const reader=response.body?.getReader();if(!reader){this.log("handleSSEResponseWithElicitation: no response body");return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No response body"}}}const decoder=new TextDecoder;const splitter=new SseEventSplitter;let finalResponse=null;let sseSessionId;try{let readCount=0;while(true){readCount++;this.log(`handleSSEResponseWithElicitation: reading chunk ${readCount}`);const{done,value}=await reader.read();this.log(`handleSSEResponseWithElicitation: read result`,{done,valueLength:value?.length});if(done){const remainder=splitter.remainder();if(remainder.trim()){const parsed=this.parseSSEEvents(remainder,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}break}for(const eventText of splitter.push(decoder.decode(value,{stream:true}))){if(eventText.trim()){const parsed=this.parseSSEEvents(eventText,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}}}}finally{reader.releaseLock()}if(sseSessionId&&!this.sessionId){this.sessionId=sseSessionId;this.log("Session ID from SSE:",this.sessionId)}if(finalResponse){return finalResponse}return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No final response received in SSE stream"}}}parseSSEEvents(text,_requestId){const lines=text.split("\n");const events=[];let currentEvent={type:"message",data:[]};let sessionId;for(const line of lines){if(line.startsWith("event: ")){currentEvent.type=line.slice(7)}else if(line.startsWith("data: ")){currentEvent.data.push(line.slice(6))}else if(line==="data:"){currentEvent.data.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);currentEvent.id=idValue;const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sessionId=idValue.substring(0,colonIndex)}else{sessionId=idValue}}else if(line===""&&currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id});currentEvent={type:"message",data:[]}}}if(currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id})}return{events,sessionId}}async handleSSEEvent(event){this.log("SSE Event:",{type:event.type,data:event.data.slice(0,200)});try{const parsed=JSON.parse(event.data);if("method"in parsed&&parsed.method==="elicitation/create"){await this.handleElicitationRequest(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("method"in parsed&&parsed.id===void 0){this.notificationHandler?.(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("result"in parsed||"error"in parsed){return{isFinal:true,response:parsed}}return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}catch{this.log("Failed to parse SSE event data:",event.data);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}}async handleElicitationRequest(request){const params=request.params;this.log("Elicitation request received:",{mode:params?.mode,message:params?.message?.slice(0,100)});const requestId=request.id;if(requestId===void 0||requestId===null){this.log("Elicitation request has no ID, cannot respond");return}if(!this.elicitationHandler){this.log("No elicitation handler registered, sending error");await this.sendElicitationResponse(requestId,{action:"decline"});return}try{const response=await this.elicitationHandler(params);this.log("Elicitation handler response:",response);await this.sendElicitationResponse(requestId,response)}catch(error){this.log("Elicitation handler error:",error);await this.sendElicitationResponse(requestId,{action:"cancel"})}}async sendElicitationResponse(requestId,response){const headers=this.buildHeaders();const url=this.mcpUrl();const rpcResponse={jsonrpc:"2.0",id:requestId,result:response};this.log("Sending elicitation response:",rpcResponse);try{const fetchResponse=await fetch(url,{method:"POST",headers,body:JSON.stringify(rpcResponse)});if(!fetchResponse.ok){this.log(`Elicitation response HTTP error: ${fetchResponse.status}`)}}catch(error){this.log("Failed to send elicitation response:",error)}}mcpUrl(){const url=new URL(this.config.baseUrl);const entry=(0,import_utils3.trimSlashes)(this.config.entryPath);const basePath=(0,import_utils3.trimTrailing)(url.pathname,"/");url.pathname=entry?`${basePath}/${entry}`:`${basePath}/`;return url.toString()}buildHeaders(stateless=false,message){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.config.clientInfo){headers["User-Agent"]=`${this.config.clientInfo.name}/${this.config.clientInfo.version}`}if(this.authToken){headers["Authorization"]=`Bearer ${this.authToken}`}if(this.sessionId&&!stateless){headers["mcp-session-id"]=this.sessionId}if(stateless){const toolName=message?.params?.["name"];Object.assign(headers,revisionHeaders(message,typeof toolName==="string"?this.toolInputSchemas.get(toolName):void 0))}if(this.config.auth.headers){Object.assign(headers,this.config.auth.headers)}return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.config.debug){console.log(`[StreamableHTTP] ${message}`,data??"")}}parseSSEResponseWithSession(text,requestId){const lines=text.split("\n");const dataLines=[];let sseSessionId;for(const line of lines){if(line.startsWith("data: ")){dataLines.push(line.slice(6))}else if(line==="data:"){dataLines.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sseSessionId=idValue.substring(0,colonIndex)}else{sseSessionId=idValue}}}if(dataLines.length>0){const jsonData=dataLines.join("\n");try{return{response:JSON.parse(jsonData),sseSessionId}}catch{this.log("Failed to parse SSE data as JSON:",jsonData)}}return{response:{jsonrpc:"2.0",id:requestId??null,error:{code:-32700,message:"Failed to parse SSE response",data:text}},sseSessionId}}};function parsedJsonRpc(data){try{const parsed=JSON.parse(data);return typeof parsed==="object"&&parsed!==null?parsed:void 0}catch{return void 0}}function isAuthStatus(status){return status===401||status===403}var MCP_APPS_EXTENSION_KEY="io.modelcontextprotocol/ui";function getPlatformClientInfo(platform){switch(platform){case"openai":return{name:"ChatGPT",version:"1.0"};case"ext-apps":return{name:"mcp-ext-apps",version:"1.0"};case"claude":return{name:"claude-desktop",version:"1.0"};case"claude-code":return{name:"claude-code",version:"1.0"};case"codex":return{name:"codex-mcp-client",version:"1.0"};case"cursor":return{name:"cursor",version:"1.0"};case"continue":return{name:"continue",version:"1.0"};case"cody":return{name:"cody",version:"1.0"};case"gemini":return{name:"gemini",version:"1.0"};case"generic-mcp":return{name:"generic-mcp-client",version:"1.0"};case"unknown":default:return{name:"mcp-test-client",version:"1.0"}}}function getPlatformCapabilities(platform){const baseCapabilities={sampling:{},elicitation:{form:{}}};if(platform==="ext-apps"){return{...baseCapabilities,experimental:{[MCP_APPS_EXTENSION_KEY]:{mimeTypes:["text/html;profile=mcp-app"]}}}}return baseCapabilities}var McpTestClientBuilder=class{config;constructor(config){this.config={...config}}withAuth(auth){this.config.auth={...this.config.auth,...auth};return this}withToken(token){this.config.auth={...this.config.auth,token};return this}withHeaders(headers){this.config.auth={...this.config.auth,headers:{...this.config.auth?.headers,...headers}};return this}withTransport(transport){this.config.transport=transport;return this}withTimeout(timeoutMs){this.config.timeout=timeoutMs;return this}withDebug(enabled=true){this.config.debug=enabled;return this}withPublicMode(enabled=true){this.config.publicMode=enabled;return this}withProtocolVersion(version){this.config.protocolVersion=version;return this}withMcpLogLevel(level){this.config.mcpLogLevel=level;return this}withClientInfo(info){this.config.clientInfo=info;return this}withPlatform(platform){this.config.platform=platform;this.config.clientInfo=getPlatformClientInfo(platform);this.config.capabilities=getPlatformCapabilities(platform);return this}withCapabilities(capabilities){this.config.capabilities=capabilities;return this}withQueryParams(params){this.config.queryParams={...this.config.queryParams,...params};return this}withEvents(options){this.config.events=options;return this}build(){return new McpTestClient(this.config)}async buildAndConnect(){const client=this.build();await client.connect();return client}};var DEFAULT_TIMEOUT3=3e4;var DEFAULT_PROTOCOL_VERSION="2025-06-18";var DEFAULT_MCP_LOG_LEVEL="debug";var MAX_INPUT_ROUNDS=10;var LIST_CHANGED_SUBSCRIPTIONS={toolsListChanged:true,promptsListChanged:true,resourcesListChanged:true};var DEFAULT_CLIENT_INFO={name:"@frontmcp/testing",version:"0.4.0"};var MAX_LIST_PAGES=1e3;function isAuthFailure(error){return typeof error?.message==="string"&&/^HTTP (401|403)\b/.test(error.message)}function describeInitializeError(error){const message=error?.message??"Unknown error";const data=error?.data;const detail=typeof data==="string"?data.trim():"";return detail?`${message} - ${detail.slice(0,500)}`:message}function initializeResultFrom(discovered){const serverInfo=discovered._meta?.[import_protocol3.MCP_20260728_META.serverInfo]??{name:"",version:""};return{protocolVersion:import_protocol3.PROTOCOL_2026_07_28,capabilities:discovered.capabilities,serverInfo,...discovered.instructions!==void 0&&{instructions:discovered.instructions}}}function isInputRequired(result){return result?.resultType==="input_required"}function extractEntryPaths(data){let payload=data;if(typeof payload==="string"){try{payload=JSON.parse(payload)}catch{return void 0}}if(!payload||typeof payload!=="object")return void 0;const paths=payload.entryPaths;if(!Array.isArray(paths))return void 0;const strings=paths.filter(p=>typeof p==="string");return strings.length>0?strings:void 0}var McpTestClient=class{config;resourceSubscriptions=new Set;toolsListed=false;transport=null;initResult=null;requestIdCounter=0;_lastRequestId=0;_sessionId;triedDiscoveredEntryPath=false;_sessionInfo=null;_authState={isAnonymous:true,scopes:[]};_logs=[];_traces=[];_notifications=[];_progressUpdates=[];collectingProgress=false;progressTokenCounter=0;_interceptors;_elicitationHandler;eventsClient;constructor(config){if(config.protocolVersion===import_protocol3.PROTOCOL_2026_07_28&&config.transport==="sse"){throw new Error(`Protocol version ${import_protocol3.PROTOCOL_2026_07_28} has no HTTP+SSE transport: use 'streamable-http', or a protocol version before it with 'sse'.`)}this.config={baseUrl:config.baseUrl,entryPath:config.entryPath,transport:config.transport??"streamable-http",auth:config.auth??{},publicMode:config.publicMode??false,timeout:config.timeout??DEFAULT_TIMEOUT3,debug:config.debug??false,protocolVersion:config.protocolVersion??DEFAULT_PROTOCOL_VERSION,mcpLogLevel:config.mcpLogLevel??DEFAULT_MCP_LOG_LEVEL,clientInfo:config.clientInfo??DEFAULT_CLIENT_INFO,platform:config.platform,capabilities:config.capabilities,queryParams:config.queryParams,events:config.events};if(config.auth?.token){this._authState={isAnonymous:false,token:config.auth.token,scopes:this.parseScopesFromToken(config.auth.token),user:this.parseUserFromToken(config.auth.token)}}this._interceptors=new DefaultInterceptorChain}static create(config){return new McpTestClientBuilder(config)}async connect(){this.log("debug",`Connecting to ${this.config.baseUrl}...`);this.triedDiscoveredEntryPath=false;this.initResult=null;this.toolsListed=false;this.transport=this.createTransport();await this.transport.connect();const maxRetries=3;const retryDelayMs=500;let lastError;let reportedEntryPaths;let attemptsMade=0;for(let attempt=1;attempt<=maxRetries;attempt++){attemptsMade=attempt;const initResponse=this.isStateless?await this.discoverServer():await this.initialize();if(initResponse.success&&initResponse.data){this.initResult=initResponse.data;break}lastError=describeInitializeError(initResponse.error);reportedEntryPaths=extractEntryPaths(initResponse.error?.data)??reportedEntryPaths;if(reportedEntryPaths?.length===1&&!this.triedDiscoveredEntryPath){this.triedDiscoveredEntryPath=true;const discovered=reportedEntryPaths[0];this.log("info",`Server serves MCP at ${discovered}; reconnecting there (configured: ${this.mcpPathLabel()})`);this.config.entryPath=discovered;await this.transport.close();this.transport=this.createTransport();await this.transport.connect();continue}if(isAuthFailure(initResponse.error))break;if(attempt<maxRetries){this.log("debug",`MCP init attempt ${attempt} failed (${lastError}), retrying in ${retryDelayMs}ms...`);await new Promise(resolve=>setTimeout(resolve,retryDelayMs))}}if(!this.initResult){const served=reportedEntryPaths?.length?` The server reports it serves MCP at ${reportedEntryPaths.join(", ")}; set \`entryPath\` in test.use() (or \`http.entryPath\` on the server) to match.`:"";throw new Error(`Failed to initialize MCP connection to ${this.config.baseUrl}${this.mcpPathLabel()} after ${attemptsMade} attempt${attemptsMade===1?"":"s"}: ${lastError}.${served}`)}this._sessionId=this.transport.getSessionId();this._sessionInfo={id:this._sessionId??`session-${Date.now()}`,createdAt:new Date,lastActivityAt:new Date,requestCount:1};if(this.isStateless){await this.listen()}else{await this.transport.notify({jsonrpc:"2.0",method:"notifications/initialized"});await this.transport.openNotificationStream?.(this.initResult.protocolVersion);await this.setServerLogLevel()}this.log("info",`Connected to ${this.initResult.serverInfo?.name??"MCP Server"}`);return this.initResult}async disconnect(){await this.eventsClient?.close();if(this.transport){await this.transport.close();this.transport=null}this.initResult=null;this.log("info","Disconnected from MCP server")}async reconnect(options){await this.disconnect();if(options?.sessionId&&this.transport){this._sessionId=options.sessionId}await this.connect()}isConnected(){return this.transport?.isConnected()??false}get sessionId(){return this._sessionId??""}get session(){const info=this._sessionInfo??{id:"",createdAt:new Date,lastActivityAt:new Date,requestCount:0};return{...info,expire:async()=>{this._sessionId=void 0;this._sessionInfo=null}}}get auth(){return this._authState}async authenticate(token){if(typeof token!=="string"||token.trim()===""){throw new Error("authenticate() requires a non-empty token")}const previousAuthState=this._authState;const previousConfigAuth=this.config.auth;this.config.auth={...previousConfigAuth,token};this._authState={isAnonymous:false,token,scopes:this.parseScopesFromToken(token),user:this.parseUserFromToken(token)};const previousTransport=this.transport;if(!previousTransport){this.log("debug","Authentication updated (not connected yet)");return}const previousInit=this.initResult;const previousSessionId=this._sessionId;const previousSessionInfo=this._sessionInfo;try{await this.connect()}catch(err){await this.transport?.close().catch(()=>void 0);this.transport=previousTransport;this.initResult=previousInit;this._sessionId=previousSessionId;this._sessionInfo=previousSessionInfo;this.config.auth=previousConfigAuth;this._authState=previousAuthState;throw err}await previousTransport.close().catch(()=>void 0);this.log("debug","Authentication updated")}get serverInfo(){return{name:this.initResult?.serverInfo?.name??"",version:this.initResult?.serverInfo?.version??""}}get protocolVersion(){return this.initResult?.protocolVersion??""}get instructions(){return this.initResult?.instructions??""}get capabilities(){return this.initResult?.capabilities??{}}hasCapability(name){return!!this.capabilities[name]}async discover(){const response=await this.request("server/discover",{});if(!response.success||!response.data)throw new Error(`server/discover failed: ${response.error?.message}`);return response.data}tools={list:async()=>{const tools=await this.listAllPages("tools/list","tools",cursor=>this.listTools(cursor),page=>page.tools);this.toolsListed=true;return tools},call:async(name,args,options={})=>{await this.learnToolSchemas();const response=await this.callTool(name,args,this.progressTokenFor(options));return this.wrapToolResult(response)}};resources={list:async()=>this.listAllPages("resources/list","resources",cursor=>this.listResources(cursor),page=>page.resources),listTemplates:async()=>this.listAllPages("resources/templates/list","resource templates",cursor=>this.listResourceTemplates(cursor),page=>page.resourceTemplates),read:async uri=>{const response=await this.readResource(uri);return this.wrapResourceContent(response)},subscribe:async uri=>{if(this.isStateless)return this.listenToResource(uri);const response=await this.request("resources/subscribe",{uri});if(!response.success)throw new Error(`Failed to subscribe to ${uri}: ${response.error?.message}`)},unsubscribe:async uri=>{if(this.isStateless){this.resourceSubscriptions.delete(uri);await this.listen();return}const response=await this.request("resources/unsubscribe",{uri});if(!response.success)throw new Error(`Failed to unsubscribe from ${uri}: ${response.error?.message}`)}};prompts={list:async()=>this.listAllPages("prompts/list","prompts",cursor=>this.listPrompts(cursor),page=>page.prompts),get:async(name,args)=>{const response=await this.getPrompt(name,args);return this.wrapPromptResult(response)}};get events(){this.eventsClient??=new import_sdk.EventsClient(this.eventsTransport(),this.config.events);return this.eventsClient}eventsTransport(){const transport={request:async(method,params)=>{const response=await this.request(method,params);if(!response.success){const{code,message,data}=response.error;throw new import_sdk.EventRequestError(method,code,message,data)}return response.data}};if(this.config.transport==="streamable-http"){transport.openStream=(params,onNotification,signal)=>this.openEventStream(params,onNotification,signal)}return transport}async openEventStream(params,onNotification,signal){const transport=this.getConnectedTransport();const id=++this.requestIdCounter;const message={jsonrpc:"2.0",id,method:"events/stream",params};const response=await transport.streamRequest?.(message,onNotification,signal);if(response?.error){throw new import_sdk.EventRequestError("events/stream",response.error.code,response.error.message,response.error.data)}if(signal.aborted&&!isStatelessRequest(this.config.protocolVersion,"events/stream")){await transport.notify({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id}}).catch(()=>void 0)}}raw={request:async message=>{const transport=this.getConnectedTransport();const start=Date.now();const response=await transport.request(message);this.traceRequest(message.method,message.params,message.id,response,Date.now()-start);return response},notify:async message=>{const transport=this.getConnectedTransport();await transport.notify(message)},sendRaw:async data=>{const transport=this.getConnectedTransport();return transport.sendRaw(data)}};get lastRequestId(){return this._lastRequestId}get transport_info(){return{type:this.config.transport,isConnected:()=>this.transport?.isConnected()??false,messageEndpoint:this.transport?.getMessageEndpoint?.(),connectionCount:this.transport?.getConnectionCount?.()??0,reconnectCount:this.transport?.getReconnectCount?.()??0,lastRequestHeaders:this.transport?.getLastRequestHeaders?.()??{},simulateDisconnect:async()=>{await this.transport?.simulateDisconnect?.()},waitForReconnect:async timeoutMs=>{await this.transport?.waitForReconnect?.(timeoutMs)}}}get transport_(){return this.transport_info}notifications={collect:()=>{return new NotificationCollector(this._notifications)},collectProgress:()=>{this.collectingProgress=true;return new ProgressCollector(this._progressUpdates)},send:async(method,params)=>{await this.raw.notify({jsonrpc:"2.0",method,params})}};onElicitation(handler){this._elicitationHandler=handler;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(handler)}this.log("debug","Elicitation handler registered")}clearElicitationHandler(){this._elicitationHandler=void 0;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(void 0)}this.log("debug","Elicitation handler cleared")}logs={all:()=>[...this._logs],filter:level=>this._logs.filter(l=>l.level===level),search:text=>this._logs.filter(l=>l.message.includes(text)),last:()=>this._logs[this._logs.length-1],clear:()=>{this._logs=[]}};trace={all:()=>[...this._traces],last:()=>this._traces[this._traces.length-1],clear:()=>{this._traces=[]}};mock={add:mock=>{return this._interceptors.mocks.add(mock)},tool:(name,result,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.toolResult([{type:"text",text:typeof result==="string"?result:JSON.stringify(result)}]),times:options?.times,delay:options?.delay})},toolError:(name,code,message,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.error(code,message),times:options?.times})},resource:(uri,content,options)=>{const contentObj=typeof content==="string"?{uri,text:content}:{uri,...content};return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.resourceRead([contentObj]),times:options?.times,delay:options?.delay})},resourceError:(uri,options)=>{return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.errors.resourceNotFound(uri),times:options?.times})},toolsList:(tools,options)=>{return this._interceptors.mocks.add({method:"tools/list",response:mockResponse.toolsList(tools),times:options?.times})},resourcesList:(resources,options)=>{return this._interceptors.mocks.add({method:"resources/list",response:mockResponse.resourcesList(resources),times:options?.times})},clear:()=>{this._interceptors.mocks.clear()},all:()=>{return this._interceptors.mocks.getAll()}};intercept={request:interceptor=>{return this._interceptors.addRequestInterceptor(interceptor)},response:interceptor=>{return this._interceptors.addResponseInterceptor(interceptor)},delay:ms=>{return this._interceptors.addRequestInterceptor(async()=>{await new Promise(r=>setTimeout(r,ms));return{action:"passthrough"}})},failMethod:(method,error)=>{return this._interceptors.addRequestInterceptor(ctx=>{if(ctx.request.method===method){return{action:"error",error:new Error(error??`Intercepted: ${method}`)}}return{action:"passthrough"}})},clear:()=>{this._interceptors.request=[];this._interceptors.response=[]},clearAll:()=>{this._interceptors.clear()}};setTimeout(ms){this.config.timeout=ms;if(this.transport){this.transport.setTimeout(ms)}}get isStateless(){return this.config.protocolVersion===import_protocol3.PROTOCOL_2026_07_28}get clientCapabilities(){return this.config.capabilities??{sampling:{},elicitation:{form:{}}}}async initialize(){return this.request("initialize",{protocolVersion:this.config.protocolVersion,capabilities:this.clientCapabilities,clientInfo:this.config.clientInfo})}async discoverServer(){const response=await this.request("server/discover",{});const data=response.data&&initializeResultFrom(response.data);return{...response,data}}async setServerLogLevel(){const level=this.config.mcpLogLevel;if(level===false||!this.hasCapability("logging"))return;const response=await this.request("logging/setLevel",{level});if(!response.success)this.log("warn",`logging/setLevel ${level} failed: ${response.error?.message}`)}async listen(){const resourceSubscriptions=[...this.resourceSubscriptions];const acknowledged=await this.transport?.listen?.(++this.requestIdCounter,{...LIST_CHANGED_SUBSCRIPTIONS,...resourceSubscriptions.length>0&&{resourceSubscriptions}});if(!acknowledged)this.log("warn","The server opened no subscriptions/listen stream");return acknowledged}async listenToResource(uri){this.resourceSubscriptions.add(uri);const acknowledged=await this.listen();if(acknowledged?.resourceSubscriptions?.includes(uri))return;this.resourceSubscriptions.delete(uri);throw new Error(`Failed to subscribe to ${uri}: the server did not acknowledge it in subscriptions/listen`)}async learnToolSchemas(){if(!this.isStateless||this.toolsListed)return;this.toolsListed=true;await this.tools.list().catch(error=>{this.log("warn",`Listing the tools before the first call failed: ${errorMessage(error)}`)})}async listTools(cursor){return this.request("tools/list",cursor?{cursor}:{})}async listAllPages(method,label,fetchPage,itemsOf){const items=[];const seenCursors=new Set;let cursor;for(let page=0;page<MAX_LIST_PAGES;page++){const response=await fetchPage(cursor);if(!response.success||!response.data){throw new Error(`Failed to list ${label}: ${response.error?.message}`)}items.push(...itemsOf(response.data)??[]);const next=response.data.nextCursor;if(!next)return items;if(seenCursors.has(next)){throw new Error(`Failed to list ${label}: ${method} returned the cursor "${next}" twice`)}seenCursors.add(next);cursor=next}throw new Error(`Failed to list ${label}: ${method} did not finish within ${MAX_LIST_PAGES} pages`)}async callTool(name,args,progressToken){return this.request("tools/call",{name,arguments:args??{},...progressToken!==void 0&&{_meta:{progressToken}}})}progressTokenFor(options){if(options.progressToken!==void 0)return options.progressToken;return this.collectingProgress?`progress-${++this.progressTokenCounter}`:void 0}recordNotification=notification=>{const timestamp=new Date;this._notifications.push({method:notification.method,params:notification.params,timestamp});if(notification.method!=="notifications/progress")return;const{progress,total,progressToken,message}=notification.params??{};this._progressUpdates.push({progress:Number(progress),total:typeof total==="number"?total:void 0,message:typeof message==="string"?message:void 0,progressToken:typeof progressToken==="string"||typeof progressToken==="number"?progressToken:void 0,timestamp})};async listResources(cursor){return this.request("resources/list",cursor?{cursor}:{})}async listResourceTemplates(cursor){return this.request("resources/templates/list",cursor?{cursor}:{})}async readResource(uri){return this.request("resources/read",{uri})}async listPrompts(cursor){return this.request("prompts/list",cursor?{cursor}:{})}async getPrompt(name,args){return this.request("prompts/get",{name,arguments:args??{}})}mcpPathLabel(){const entry=(0,import_utils4.trimSlashes)(this.config.entryPath);return entry?`/${entry}`:"/"}createTransport(){let baseUrl=this.config.baseUrl;if(this.config.queryParams&&Object.keys(this.config.queryParams).length>0){const url=new URL(baseUrl);Object.entries(this.config.queryParams).forEach(([key,value])=>{url.searchParams.set(key,String(value))});baseUrl=url.toString()}switch(this.config.transport){case"streamable-http":return new StreamableHttpTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification,protocolVersion:this.config.protocolVersion,capabilities:this.clientCapabilities,logLevel:this.config.mcpLogLevel||void 0});case"sse":return new SseTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification});default:throw new Error(`Unknown transport type: ${this.config.transport}`)}}async request(method,params){let response=await this.send(method,params);for(let round=1;response.success&&isInputRequired(response.data);round++){const{inputRequests,requestState}=response.data;const inputResponses=round>MAX_INPUT_ROUNDS?`the server asked for input more than ${MAX_INPUT_ROUNDS} times`:await this.answerInputRequests(inputRequests);if(typeof inputResponses==="string"){return{...response,success:false,data:void 0,error:{code:-32603,message:`${method}: ${inputResponses}`}}}const retried=await this.send(method,{...params,inputResponses,...requestState!==void 0&&{requestState}});response={...retried,durationMs:response.durationMs+retried.durationMs}}return response}async answerInputRequests(inputRequests={}){const answers={};for(const[key,inputRequest]of Object.entries(inputRequests)){if(inputRequest.method!=="elicitation/create"){return`the server asked for ${inputRequest.method}, which McpTestClient doesn't answer`}answers[key]={...await this.answerElicitation(inputRequest.params??{})}}return answers}async answerElicitation(params){if(!this._elicitationHandler)return{action:"decline"};try{return await this._elicitationHandler({mode:"form",...params})}catch(error){this.log("warn",`The elicitation handler threw: ${errorMessage(error)}`);return{action:"cancel"}}}async send(method,params){const transport=this.getConnectedTransport();const id=++this.requestIdCounter;this._lastRequestId=id;const start=Date.now();try{const response=await transport.request({jsonrpc:"2.0",id,method,params});const durationMs=Date.now()-start;this.updateSessionActivity();if("error"in response&&response.error){const error=response.error;this.traceRequest(method,params,id,response,durationMs);return{success:false,error,durationMs,requestId:id}}this.traceRequest(method,params,id,response,durationMs);return{success:true,data:response.result,durationMs,requestId:id}}catch(err){if(isInterceptedError(err))throw err;const durationMs=Date.now()-start;const error={code:-32603,message:errorMessage(err)};return{success:false,error,durationMs,requestId:id}}}getConnectedTransport(){if(!this.transport||!this.transport.isConnected()){throw new Error("Not connected to MCP server. Call connect() first.")}return this.transport}updateSessionActivity(){if(this._sessionInfo){this._sessionInfo.lastActivityAt=new Date;this._sessionInfo.requestCount++}}wrapToolResult(response){const raw=response.data??{content:[]};const isError=!response.success||raw.isError===true;const meta=raw._meta;const hasUI=meta?.["ui/html"]!==void 0||meta?.["ui/component"]!==void 0;const structuredContent=raw["structuredContent"];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(hasUI&&structuredContent!==void 0){return structuredContent}const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return JSON.parse(textContent.text)}throw new Error("No text content to parse as JSON")},text(){const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return textContent.text}return void 0},hasTextContent(){return raw.content?.some(c=>c.type==="text")??false},hasImageContent(){return raw.content?.some(c=>c.type==="image")??false},hasResourceContent(){return raw.content?.some(c=>c.type==="resource")??false},hasToolUI(){return hasUI}}}wrapResourceContent(response){const raw=response.data??{contents:[]};const isError=!response.success;const firstContent=raw.contents?.[0];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(firstContent&&"text"in firstContent){return JSON.parse(firstContent.text)}throw new Error("No text content to parse as JSON")},text(){if(firstContent&&"text"in firstContent){return firstContent.text}return void 0},mimeType(){return firstContent?.mimeType},hasMimeType(type){return firstContent?.mimeType===type}}}wrapPromptResult(response){const raw=response.data??{messages:[]};const isError=!response.success;return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,messages:raw.messages??[],description:raw.description}}log(level,message,data){const entry={level,message,timestamp:new Date,data};this._logs.push(entry);if(this.config.debug){console.log(`[${level.toUpperCase()}] ${message}`,data??"")}}traceRequest(method,params,id,response,durationMs){this._traces.push({request:{method,params,id},response:{result:"result"in response?response.result:void 0,error:"error"in response?response.error:void 0},durationMs,timestamp:new Date})}parseScopesFromToken(token){try{const payload=this.decodeJwtPayload(token);if(!payload)return[];const scope=payload["scope"];const scopes=payload["scopes"];if(typeof scope==="string"){return scope.split(" ")}if(Array.isArray(scopes)){return scopes}return[]}catch{return[]}}parseUserFromToken(token){try{const payload=this.decodeJwtPayload(token);const sub=payload?.["sub"];if(!sub||typeof sub!=="string")return void 0;return{sub,email:payload["email"],name:payload["name"]}}catch{return void 0}}decodeJwtPayload(token){try{const parts=token.split(".");if(parts.length!==3)return null;const payload=Buffer.from(parts[1],"base64url").toString("utf-8");return JSON.parse(payload)}catch{return null}}};var NotificationCollector=class{constructor(notifications){this.notifications=notifications}notifications;get received(){return[...this.notifications]}has(method){return this.notifications.some(n=>n.method===method)}async waitFor(method,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const found=this.notifications.find(n=>n.method===method);if(found)return found;await new Promise(r=>setTimeout(r,50))}throw new Error(`Timeout waiting for notification: ${method}`)}};var ProgressCollector=class{constructor(updates){this.updates=updates}updates;get all(){return[...this.updates]}async waitForComplete(timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const last=this.updates[this.updates.length-1];if(last&&last.total!==void 0&&last.progress>=last.total){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for progress to complete")}};var import_child_process=require("child_process");var import_net2=require("net");var TestClientError=class extends Error{constructor(message){super(message);this.name="TestClientError";Object.setPrototypeOf(this,new.target.prototype)}};var ServerStartError=class extends TestClientError{constructor(message,cause){super(message);this.cause=cause;this.name="ServerStartError";Object.setPrototypeOf(this,new.target.prototype)}cause};var import_net=require("net");var E2E_PORT_RANGES={"demo-e2e-public":{start:5e4,size:10},"demo-e2e-cache":{start:50010,size:10},"demo-e2e-config":{start:50020,size:10},"demo-e2e-direct":{start:50030,size:10},"demo-e2e-errors":{start:50040,size:10},"demo-e2e-hooks":{start:50050,size:10},"demo-e2e-multiapp":{start:50060,size:10},"demo-e2e-notifications":{start:50070,size:10},"demo-e2e-providers":{start:50080,size:10},"demo-e2e-standalone":{start:50090,size:10},"demo-e2e-orchestrated":{start:50100,size:10},"demo-e2e-transparent":{start:50110,size:10},"demo-e2e-cimd":{start:50120,size:10},"demo-e2e-remote-proxy":{start:50130,size:10},"demo-e2e-skills":{start:50200,size:10},"demo-e2e-remote":{start:50210,size:10},"demo-e2e-openapi":{start:50220,size:10},"demo-e2e-ui":{start:50230,size:10},"demo-e2e-codecall":{start:50240,size:10},"demo-e2e-remember":{start:50250,size:10},"demo-e2e-elicitation":{start:50260,size:10},"demo-e2e-agents":{start:50270,size:10},"demo-e2e-transport-recreation":{start:50280,size:10},"demo-e2e-jobs":{start:50290,size:10},"demo-e2e-redis":{start:50300,size:10},"demo-e2e-serverless":{start:50310,size:10},"demo-e2e-uipack":{start:50320,size:10},"demo-e2e-agent-adapters":{start:50330,size:10},"demo-e2e-guard":{start:50340,size:10},"demo-e2e-cli-exec":{start:50350,size:10},"demo-e2e-env-awareness":{start:50360,size:10},"demo-e2e-esm":{start:50370,size:10},"demo-e2e-feature-flags":{start:50380,size:10},"demo-e2e-resource-providers":{start:50390,size:10},"esm-package-server":{start:50400,size:10},"esm-package-server-hot-reload":{start:50410,size:10},"esm-package-server-cli":{start:50420,size:10},"demo-e2e-unix-socket":{start:50430,size:10},"demo-e2e-distributed":{start:50440,size:20},"demo-e2e-protocol-20260728":{start:50460,size:20},"demo-e2e-testing":{start:50480,size:20},"demo-e2e-answer-shaping":{start:50500,size:10},"demo-e2e-events":{start:50530,size:10},"demo-e2e-events-appointments":{start:50540,size:10},"demo-e2e-events-daemon":{start:50550,size:10},"demo-e2e-events-mail-triage":{start:50560,size:10},"mock-oauth":{start:50900,size:10},"mock-api":{start:50910,size:10},"mock-cimd":{start:50920,size:10},default:{start:51e3,size:100}};var reservedPorts=new Map;var lockedPorts=new Set;var LOCK_MAX_AGE_MS=10*60*1e3;function lockDir(){try{const fs=require("node:fs");const os=require("node:os");const path=require("node:path");const uid=typeof process.getuid==="function"?process.getuid():void 0;const dir=path.join(os.tmpdir(),uid===void 0?"frontmcp-testing-ports":`frontmcp-testing-ports-${uid}`);fs.mkdirSync(dir,{recursive:true,mode:448});if(uid===void 0)return dir;const stats=fs.lstatSync(dir);return stats.isDirectory()&&stats.uid===uid&&(stats.mode&63)===0?dir:void 0}catch{return void 0}}function pidIsAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function acquirePortLock(port){if(lockedPorts.has(port))return false;let fs;let file;try{fs=require("node:fs");const dir=lockDir();if(!dir)return true;file=require("node:path").join(dir,`${port}.lock`)}catch{return true}const payload=JSON.stringify({pid:process.pid,at:Date.now()});for(let attempt=0;attempt<2;attempt++){try{fs.writeFileSync(file,payload,{flag:"wx"});lockedPorts.add(port);return true}catch(error){if(error.code!=="EEXIST")return true;try{const held=JSON.parse(fs.readFileSync(file,"utf8"));const fresh=typeof held.at==="number"&&Date.now()-held.at<LOCK_MAX_AGE_MS;if(fresh&&typeof held.pid==="number"&&pidIsAlive(held.pid))return false;fs.unlinkSync(file)}catch{}}}return false}function releasePortLock(port){if(!lockedPorts.delete(port))return;try{const fs=require("node:fs");const dir=lockDir();if(dir)fs.unlinkSync(require("node:path").join(dir,`${port}.lock`))}catch{}}var projectPortIndex=new Map;function getPortRange(project){const key=project;if(key in E2E_PORT_RANGES){return E2E_PORT_RANGES[key]}return E2E_PORT_RANGES.default}async function reservePort(project,preferredPort){const range=getPortRange(project);const handle=port=>({port,releaseSocket:async()=>{await releasePort(port)},release:async()=>{await releasePort(port);releasePortLock(port)}});const wantsSpecificPort=preferredPort!==void 0&&Number.isInteger(preferredPort)&&preferredPort>0;if(wantsSpecificPort){const reservation=await tryReservePort(preferredPort,project);if(reservation){return handle(preferredPort)}console.warn(`[PortRegistry] Preferred port ${preferredPort} not available for ${project}, allocating from range`)}let index=projectPortIndex.get(project)??0;const maxAttempts=range.size;for(let attempt=0;attempt<maxAttempts;attempt++){const port=range.start+index%range.size;index=(index+1)%range.size;if(reservedPorts.has(port)||lockedPorts.has(port)){continue}const reservation=await tryReservePort(port,project);if(reservation){projectPortIndex.set(project,index);return handle(port)}}for(let port=51e3;port<52e3;port++){if(reservedPorts.has(port)||lockedPorts.has(port))continue;if(await tryReservePort(port,project)){return handle(port)}}throw new Error(`[PortRegistry] Could not reserve a port for ${project}. Range: ${range.start}-${range.start+range.size-1}. Currently reserved: ${Array.from(reservedPorts.keys()).join(", ")}`)}async function tryReservePort(port,project){if(!acquirePortLock(port)){return false}return new Promise(resolve=>{const server=(0,import_net.createServer)();server.once("error",()=>{releasePortLock(port);resolve(false)});server.listen(port,()=>{reservedPorts.set(port,{port,project,holder:server,reservedAt:Date.now()});resolve(true)})})}async function releasePort(port){const reservation=reservedPorts.get(port);if(!reservation){return}return new Promise(resolve=>{reservation.holder.close(()=>{reservedPorts.delete(port);resolve()})})}var SERVER_EXIT_TIMEOUT_MS=12e3;var DEBUG_SERVER=process.env["DEBUG_SERVER"]==="1"||process.env["DEBUG"]==="1";var TestServer=class _TestServer{process=null;options;_info;logs=[];portRelease=null;portReleaseSocket=null;constructor(options,port,portRelease,portReleaseSocket){this.options={port,project:options.project,command:options.command??"",cwd:options.cwd??process.cwd(),env:options.env??{},startupTimeout:options.startupTimeout??3e4,healthCheckPath:options.healthCheckPath??"/health",debug:options.debug??DEBUG_SERVER};this.portRelease=portRelease??null;this.portReleaseSocket=portReleaseSocket??portRelease??null;this._info={baseUrl:`http://localhost:${port}`,port}}static async start(options){const project=options.project??"default";const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const server=new _TestServer(options,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep4(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static async startNx(project,options={}){if(!/^[\w-]+$/.test(project)){throw new Error(`Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`)}const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const serverOptions={...options,port,project,command:`npx nx serve ${project} --port ${port}`,cwd:options.cwd??process.cwd()};const server=new _TestServer(serverOptions,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep4(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static connect(baseUrl){const url=new URL(baseUrl);const port=parseInt(url.port,10)||(url.protocol==="https:"?443:80);const server=new _TestServer({command:"",port},port);server._info={baseUrl:baseUrl.replace(/\/$/,""),port};return server}get info(){return{...this._info}}async stop(){try{await this.stopProcess()}finally{if(this.portRelease){await this.portRelease();this.portRelease=null}this.portReleaseSocket=null}}async stopProcess(){if(this.process){this.log("Stopping server...");const serverPid=this._info.pid!==this._info.shellPid?this._info.pid:void 0;if(this.process.exitCode!==null||this.process.signalCode!==null){this.log(`Server already exited (code: ${this.process.exitCode}, signal: ${this.process.signalCode})`);this.process=null;if(serverPid!==void 0)signalIfRunning(serverPid,"SIGTERM");await this.waitForServerGone(serverPid);return}const pid=this.process.pid;try{if(pid!==void 0){process.kill(-pid,"SIGTERM")}else{this.process.kill("SIGTERM")}}catch{this.process.kill("SIGTERM")}const exitPromise=new Promise(resolve=>{if(this.process){this.process.once("exit",()=>resolve())}else{resolve()}});const killTimeout=setTimeout(()=>{if(this.process){this.log("Force killing server after timeout...");const killPid=this.process.pid;try{if(killPid!==void 0){process.kill(-killPid,"SIGKILL")}else{this.process.kill("SIGKILL")}}catch{this.process.kill("SIGKILL")}}},5e3);await exitPromise;clearTimeout(killTimeout);this.process=null;await this.waitForServerGone(serverPid);this.log("Server stopped")}}async waitForServerGone(serverPid){const deadline=Date.now()+SERVER_EXIT_TIMEOUT_MS;while(Date.now()<deadline){const serverRunning=serverPid!==void 0&&pidIsAlive(serverPid);if(!serverRunning&&!await acceptsConnections(this._info.port))return;await sleep4(100)}if(serverPid!==void 0&&pidIsAlive(serverPid)){this.log("Force killing server process after timeout...");signalIfRunning(serverPid,"SIGKILL")}}async waitForReady(timeout){const timeoutMs=timeout??this.options.startupTimeout;const deadline=Date.now()+timeoutMs;const checkInterval=100;while(Date.now()<deadline){try{const response=await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`,{method:"GET",signal:AbortSignal.timeout(1e3)});if(response.ok||response.status===404){this.log("Server is ready");return}}catch{}await sleep4(checkInterval)}throw new Error(`Server did not become ready within ${timeoutMs}ms`)}async restart(){await this.stopProcess();await this.startProcess()}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}async startProcess(){if(!this.options.command){await this.waitForReady();return}this.log(`Starting server: ${this.options.command}`);const env={...process.env,...this.options.env,PORT:String(this.options.port)};const runtimeEnv=withWorkspaceProtocolFallback(env,this.options.cwd);if(this.portReleaseSocket){await this.portReleaseSocket();this.portReleaseSocket=null;await sleep4(300)}this.process=(0,import_child_process.spawn)(this.options.command,[],{cwd:this.options.cwd,env:runtimeEnv,shell:true,detached:true,stdio:["pipe","pipe","pipe"]});this._info.pid=this.process.pid;this._info.shellPid=this.process.pid;let processExited=false;let exitCode=null;let exitError=null;this.process.stdout?.on("data",data=>{const text=data.toString();this.logs.push(text);if(this.options.debug){console.log("[SERVER]",text)}});this.process.stderr?.on("data",data=>{const text=data.toString();this.logs.push(`[ERROR] ${text}`);if(this.options.debug){console.error("[SERVER ERROR]",text)}});this.process.on("error",err=>{this.logs.push(`[SPAWN ERROR] ${err.message}`);exitError=err;if(this.options.debug){console.error("[SERVER SPAWN ERROR]",err)}});this.process.once("exit",code=>{processExited=true;exitCode=code;this.log(`Server process exited with code ${code}`)});try{await this.waitForReadyWithExitDetection(()=>{if(exitError){return{exited:true,error:exitError}}if(processExited){const allLogs=this.logs.join("\n");const errorLogs=this.logs.filter(l=>l.includes("[ERROR]")||l.toLowerCase().includes("error")).join("\n");return{exited:true,error:new ServerStartError(`Server process exited unexpectedly with code ${exitCode}.
17
17
 
18
18
  Command: ${this.options.command}
19
19
  CWD: ${this.options.cwd}
@@ -38,13 +38,13 @@ Last health check error: ${lastHealthCheckError??"none"}
38
38
  === Server Logs ===
39
39
  ${allLogs||"No logs captured"}
40
40
 
41
- TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`)}log(message){if(this.options.debug){console.log(`[TestServer] ${message}`)}}};function sleep4(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function signalIfRunning(pid,signal){try{process.kill(pid,signal)}catch(error){if(error.code!=="ESRCH")throw error}}function acceptsConnections(port){return new Promise(resolve=>{const socket=(0,import_net2.connect)(port,"127.0.0.1");socket.once("connect",()=>{socket.destroy();resolve(true)});socket.once("error",()=>resolve(false))})}function findListeningPid(port){if(process.platform==="win32")return Promise.resolve(void 0);return new Promise(resolve=>{(0,import_child_process.execFile)("lsof",["-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{timeout:2e3},(error,stdout)=>{if(error){resolve(void 0);return}const pid=parseInt(String(stdout).split("\n")[0]??"",10);resolve(Number.isInteger(pid)&&pid>0?pid:void 0)})})}function withWorkspaceProtocolFallback(env,cwd){if(findInstalledProtocolPackageDir(cwd)){return env}try{const workspacePackageDir=findWorkspaceProtocolDir(cwd);if(!workspacePackageDir){return env}ensureWorkspaceProtocolLink(cwd,workspacePackageDir);if(findInstalledProtocolPackageDir(cwd)){return env}return withProtocolNodePathAlias(env,cwd,workspacePackageDir)}catch(err){if(DEBUG_SERVER){console.error(`[TestServer] Workspace protocol fallback failed: ${err instanceof Error?err.message:String(err)}`)}return env}}function ensureWorkspaceProtocolLink(cwd,workspacePackageDir){const fs=require("node:fs");const path=require("node:path");const nodeModulesDir=findWorkspaceNodeModulesDir(cwd);if(!nodeModulesDir){return}const scopeDir=path.join(nodeModulesDir,"@frontmcp");const aliasPackageDir=path.join(scopeDir,"protocol");if(fs.existsSync(aliasPackageDir)){return}fs.mkdirSync(scopeDir,{recursive:true});try{fs.symlinkSync(workspacePackageDir,aliasPackageDir,process.platform==="win32"?"junction":"dir")}catch(error){const err=error;if(err.code!=="EEXIST"){throw error}}}function withProtocolNodePathAlias(env,cwd,workspacePackageDir){const fs=require("node:fs");const os=require("node:os");const path=require("node:path");const aliasRoot=path.join(os.tmpdir(),"frontmcp-test-node-path",(0,import_utils5.sha256Hex)(cwd).slice(0,12));const scopeDir=path.join(aliasRoot,"@frontmcp");const aliasPackageDir=path.join(scopeDir,"protocol");fs.mkdirSync(scopeDir,{recursive:true});try{if(!fs.existsSync(aliasPackageDir)){fs.symlinkSync(workspacePackageDir,aliasPackageDir,process.platform==="win32"?"junction":"dir")}}catch(error){const err=error;if(err.code!=="EEXIST")throw error}const existingNodePath=env["NODE_PATH"];const nodePathEntries=[aliasRoot,...existingNodePath?existingNodePath.split(path.delimiter):[]].filter(Boolean);return{...env,NODE_PATH:[...new Set(nodePathEntries)].join(path.delimiter)}}function findUp(startDir,testFn){const path=require("node:path");let currentDir=startDir;while(true){const result=testFn(currentDir);if(result!==void 0)return result;const parentDir=path.dirname(currentDir);if(parentDir===currentDir)return void 0;currentDir=parentDir}}function findWorkspaceProtocolDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"libs","protocol");return fs.existsSync(path.join(candidate,"dist","index.js"))?candidate:void 0})}function findInstalledProtocolPackageDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules","@frontmcp","protocol");return fs.existsSync(path.join(candidate,"package.json"))?candidate:void 0})}function findWorkspaceNodeModulesDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules");return fs.existsSync(candidate)?candidate:void 0})}var currentConfig={};var serverInstance=null;var tokenFactory=null;var serverStartedByUs=false;async function initializeSharedResources(){if(!tokenFactory){tokenFactory=new TestTokenFactory}if(!serverInstance){if(currentConfig.baseUrl){serverInstance=TestServer.connect(currentConfig.baseUrl);serverStartedByUs=false}else if(currentConfig.server){const serverCommand=resolveServerCommand(currentConfig.server);const isDebug=process.env["DEBUG"]==="1"||process.env["DEBUG_SERVER"]==="1";if(isDebug){console.log(`[PerfTest] Starting server: ${serverCommand}`)}try{serverInstance=await TestServer.start({project:currentConfig.project,port:currentConfig.port,command:serverCommand,env:currentConfig.env,startupTimeout:currentConfig.startupTimeout??3e4,debug:isDebug});serverStartedByUs=true;if(isDebug){console.log(`[PerfTest] Server started at ${serverInstance.info.baseUrl}`)}}catch(error){const errMsg=error instanceof Error?error.message:String(error);throw new Error(`Failed to start test server.
41
+ TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`)}log(message){if(this.options.debug){console.log(`[TestServer] ${message}`)}}};function sleep4(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function signalIfRunning(pid,signal){try{process.kill(pid,signal)}catch(error){if(error.code!=="ESRCH")throw error}}function acceptsConnections(port){return new Promise(resolve=>{const socket=(0,import_net2.connect)(port,"127.0.0.1");socket.once("connect",()=>{socket.destroy();resolve(true)});socket.once("error",()=>resolve(false))})}function findListeningPid(port){if(process.platform==="win32")return Promise.resolve(void 0);return new Promise(resolve=>{(0,import_child_process.execFile)("lsof",["-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{timeout:2e3},(error,stdout)=>{if(error){resolve(void 0);return}const pid=parseInt(String(stdout).split("\n")[0]??"",10);resolve(Number.isInteger(pid)&&pid>0?pid:void 0)})})}function withWorkspaceProtocolFallback(env,cwd){if(findInstalledProtocolPackageDir(cwd)){return env}try{const workspacePackageDir=findWorkspaceProtocolDir(cwd);if(!workspacePackageDir){return env}ensureWorkspaceProtocolLink(cwd,workspacePackageDir);if(findInstalledProtocolPackageDir(cwd)){return env}return withProtocolNodePathAlias(env,workspacePackageDir)}catch(err){if(DEBUG_SERVER){console.error(`[TestServer] Workspace protocol fallback failed: ${err instanceof Error?err.message:String(err)}`)}return env}}function ensureWorkspaceProtocolLink(cwd,workspacePackageDir){const fs=require("node:fs");const path=require("node:path");const nodeModulesDir=findWorkspaceNodeModulesDir(cwd);if(!nodeModulesDir){return}const scopeDir=path.join(nodeModulesDir,"@frontmcp");const aliasPackageDir=path.join(scopeDir,"protocol");if(fs.existsSync(aliasPackageDir)){return}fs.mkdirSync(scopeDir,{recursive:true});try{fs.symlinkSync(workspacePackageDir,aliasPackageDir,process.platform==="win32"?"junction":"dir")}catch(error){const err=error;if(err.code!=="EEXIST"){throw error}}}function withProtocolNodePathAlias(env,workspacePackageDir){const path=require("node:path");const aliasRoot=protocolAliasRoot(workspacePackageDir);const existingNodePath=env["NODE_PATH"];const nodePathEntries=[aliasRoot,...existingNodePath?existingNodePath.split(path.delimiter):[]].filter(Boolean);return{...env,NODE_PATH:[...new Set(nodePathEntries)].join(path.delimiter)}}var protocolAliasRoots=new Map;function protocolAliasRoot(workspacePackageDir){const fs=require("node:fs");const os=require("node:os");const path=require("node:path");const existingRoot=protocolAliasRoots.get(workspacePackageDir);if(existingRoot){return existingRoot}const aliasRoot=fs.mkdtempSync(path.join(os.tmpdir(),"frontmcp-test-node-path-"));if(protocolAliasRoots.size===0){process.once("exit",removeProtocolAliasRoots)}protocolAliasRoots.set(workspacePackageDir,aliasRoot);const scopeDir=path.join(aliasRoot,"@frontmcp");fs.mkdirSync(scopeDir);fs.symlinkSync(workspacePackageDir,path.join(scopeDir,"protocol"),process.platform==="win32"?"junction":"dir");return aliasRoot}function removeProtocolAliasRoots(){const fs=require("node:fs");for(const aliasRoot of protocolAliasRoots.values()){try{fs.rmSync(aliasRoot,{recursive:true,force:true})}catch{}}protocolAliasRoots.clear()}function findUp(startDir,testFn){const path=require("node:path");let currentDir=startDir;while(true){const result=testFn(currentDir);if(result!==void 0)return result;const parentDir=path.dirname(currentDir);if(parentDir===currentDir)return void 0;currentDir=parentDir}}function findWorkspaceProtocolDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"libs","protocol");return fs.existsSync(path.join(candidate,"dist","index.js"))?candidate:void 0})}function findInstalledProtocolPackageDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules","@frontmcp","protocol");return fs.existsSync(path.join(candidate,"package.json"))?candidate:void 0})}function findWorkspaceNodeModulesDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules");return fs.existsSync(candidate)?candidate:void 0})}var currentConfig={};var serverInstance=null;var tokenFactory=null;var serverStartedByUs=false;async function initializeSharedResources(){if(!tokenFactory){tokenFactory=new TestTokenFactory}if(!serverInstance){if(currentConfig.baseUrl){serverInstance=TestServer.connect(currentConfig.baseUrl);serverStartedByUs=false}else if(currentConfig.server){const serverCommand=resolveServerCommand(currentConfig.server);const isDebug=process.env["DEBUG"]==="1"||process.env["DEBUG_SERVER"]==="1";if(isDebug){console.log(`[PerfTest] Starting server: ${serverCommand}`)}try{serverInstance=await TestServer.start({project:currentConfig.project,port:currentConfig.port,command:serverCommand,env:currentConfig.env,startupTimeout:currentConfig.startupTimeout??3e4,debug:isDebug});serverStartedByUs=true;if(isDebug){console.log(`[PerfTest] Server started at ${serverInstance.info.baseUrl}`)}}catch(error){const errMsg=error instanceof Error?error.message:String(error);throw new Error(`Failed to start test server.
42
42
 
43
43
  Server entry: ${currentConfig.server}
44
44
  Project: ${currentConfig.project??"default"}
45
45
  Command: ${serverCommand}
46
46
 
47
- Error: ${errMsg}`,{cause:error})}}else{throw new Error('perfTest.use() requires either "server" (entry file path) or "baseUrl" option')}}}async function createTestFixtures(testName){await initializeSharedResources();if(!serverInstance){throw new Error("Server instance not initialized")}if(!tokenFactory){throw new Error("Token factory not initialized")}const clientInstance=await McpTestClient.create({baseUrl:serverInstance.info.baseUrl,transport:currentConfig.transport??"streamable-http",publicMode:currentConfig.publicMode}).buildAndConnect();const auth=createAuthFixture(tokenFactory);const server=createServerFixture(serverInstance);const perfImpl=createPerfFixtures(testName,currentConfig.project??"unknown");if(currentConfig.forceGcOnBaseline!==false){await perfImpl.baseline()}return{fixtures:{mcp:clientInstance,auth,server,perf:perfImpl},perfImpl}}async function cleanupTestFixtures(fixtures,perfImpl,testFailed=false){const measurement=perfImpl.buildMeasurement();addGlobalMeasurement(measurement);if(testFailed&&serverInstance){const logs=serverInstance.getLogs();if(logs.length>0){console.error("\n[PerfTest] === Server Logs (test failed) ===");const recentLogs=logs.slice(-50);if(logs.length>50){console.error(`[PerfTest] (showing last 50 of ${logs.length} log entries)`)}console.error(recentLogs.join("\n"));console.error("[PerfTest] === End Server Logs ===\n")}}if(fixtures.mcp.isConnected()){await fixtures.mcp.disconnect()}}async function cleanupSharedResources(){if(serverInstance&&serverStartedByUs){await serverInstance.stop()}serverInstance=null;tokenFactory=null;serverStartedByUs=false}function createAuthFixture(factory){const users={admin:{sub:"admin-001",scopes:["admin:*","read","write","delete"],email:"admin@test.local",name:"Test Admin"},user:{sub:"user-001",scopes:["read","write"],email:"user@test.local",name:"Test User"},readOnly:{sub:"readonly-001",scopes:["read"],email:"readonly@test.local",name:"Read Only User"}};return{createToken:opts=>factory.createTestToken({sub:opts.sub,scopes:opts.scopes,claims:{email:opts.email,name:opts.name,...opts.claims},exp:opts.expiresIn}),createExpiredToken:opts=>factory.createExpiredToken(opts),createInvalidToken:opts=>factory.createTokenWithInvalidSignature(opts),users:{admin:users["admin"],user:users["user"],readOnly:users["readOnly"]},getJwks:()=>factory.getPublicJwks(),getIssuer:()=>factory.getIssuer(),getAudience:()=>factory.getAudience()}}function createServerFixture(server){return{info:server.info,createClient:async opts=>{return McpTestClient.create({baseUrl:server.info.baseUrl,transport:opts?.transport??"streamable-http",auth:opts?.token?{token:opts.token}:void 0,clientInfo:opts?.clientInfo,publicMode:currentConfig.publicMode}).buildAndConnect()},createClientBuilder:()=>{return new McpTestClientBuilder({baseUrl:server.info.baseUrl,publicMode:currentConfig.publicMode})},restart:()=>server.restart(),getLogs:()=>server.getLogs(),clearLogs:()=>server.clearLogs()}}function resolveServerCommand(server){if(server.includes(" ")){return server}return`npx tsx ${server}`}function perfTestWithFixtures(name,fn){it(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function use(config){currentConfig={...currentConfig,...config};afterAll(async()=>{await cleanupSharedResources()})}function skip(name,fn){it.skip(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function only(name,fn){it.only(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function todo(name){it.todo(name)}var perfTest=perfTestWithFixtures;perfTest.use=use;for(const hook of["describe","beforeAll","beforeEach","afterEach","afterAll"]){Object.defineProperty(perfTest,hook,{get:()=>globalThis[hook],enumerable:true,configurable:true})}perfTest.skip=skip;perfTest.only=only;perfTest.todo=todo;var import_utils6=require("@frontmcp/utils");var BASELINE_START_MARKER="<!-- PERF_BASELINE_START -->";var BASELINE_END_MARKER="<!-- PERF_BASELINE_END -->";var DEFAULT_BASELINE_PATH="perf-results/baseline.json";var BaselineStore=class{baseline=null;baselinePath;constructor(baselinePath=DEFAULT_BASELINE_PATH){this.baselinePath=baselinePath}async load(){try{if(!await(0,import_utils6.fileExists)(this.baselinePath)){return null}const content=await(0,import_utils6.readFile)(this.baselinePath);this.baseline=JSON.parse(content);return this.baseline}catch{return null}}async save(baseline){const dir=this.baselinePath.substring(0,this.baselinePath.lastIndexOf("/"));await(0,import_utils6.ensureDir)(dir);await(0,import_utils6.writeFile)(this.baselinePath,JSON.stringify(baseline,null,2));this.baseline=baseline}getTestBaseline(testId){if(!this.baseline){return null}return this.baseline.tests[testId]??null}isLoaded(){return this.baseline!==null}getBaseline(){return this.baseline}static createFromMeasurements(measurements,release,commitHash){const tests={};const grouped=new Map;for(const m of measurements){const key=`${m.project}::${m.name}`;if(!grouped.has(key)){grouped.set(key,[])}const group=grouped.get(key);if(group){group.push(m)}}for(const[key,testMeasurements]of grouped){const[project]=key.split("::");const heapSamples=testMeasurements.map(m=>m.final?.memory.heapUsed??0);const durationSamples=testMeasurements.map(m=>m.timing.durationMs);const cpuSamples=testMeasurements.map(m=>m.final?.cpu.total??0);tests[key]={testId:key,project,heapUsed:calculateMetricBaseline(heapSamples),durationMs:calculateMetricBaseline(durationSamples),cpuTime:calculateMetricBaseline(cpuSamples),createdAt:new Date().toISOString(),commitHash}}return{release,timestamp:new Date().toISOString(),commitHash,tests}}};function parseBaselineFromComment(commentBody){const startIdx=commentBody.indexOf(BASELINE_START_MARKER);const endIdx=commentBody.indexOf(BASELINE_END_MARKER);if(startIdx===-1||endIdx===-1||startIdx>=endIdx){return null}const content=commentBody.substring(startIdx+BASELINE_START_MARKER.length,endIdx);const jsonMatch=content.match(/```json\s*([\s\S]*?)\s*```/);if(!jsonMatch){return null}try{return JSON.parse(jsonMatch[1])}catch{return null}}function formatBaselineAsComment(baseline){const json=JSON.stringify(baseline,null,2);return`## Performance Baseline
47
+ Error: ${errMsg}`,{cause:error})}}else{throw new Error('perfTest.use() requires either "server" (entry file path) or "baseUrl" option')}}}async function createTestFixtures(testName){await initializeSharedResources();if(!serverInstance){throw new Error("Server instance not initialized")}if(!tokenFactory){throw new Error("Token factory not initialized")}const clientInstance=await McpTestClient.create({baseUrl:serverInstance.info.baseUrl,transport:currentConfig.transport??"streamable-http",publicMode:currentConfig.publicMode}).buildAndConnect();const auth=createAuthFixture(tokenFactory);const server=createServerFixture(serverInstance);const perfImpl=createPerfFixtures(testName,currentConfig.project??"unknown");if(currentConfig.forceGcOnBaseline!==false){await perfImpl.baseline()}return{fixtures:{mcp:clientInstance,auth,server,perf:perfImpl},perfImpl}}async function cleanupTestFixtures(fixtures,perfImpl,testFailed=false){const measurement=perfImpl.buildMeasurement();addGlobalMeasurement(measurement);if(testFailed&&serverInstance){const logs=serverInstance.getLogs();if(logs.length>0){console.error("\n[PerfTest] === Server Logs (test failed) ===");const recentLogs=logs.slice(-50);if(logs.length>50){console.error(`[PerfTest] (showing last 50 of ${logs.length} log entries)`)}console.error(recentLogs.join("\n"));console.error("[PerfTest] === End Server Logs ===\n")}}if(fixtures.mcp.isConnected()){await fixtures.mcp.disconnect()}}async function cleanupSharedResources(){if(serverInstance&&serverStartedByUs){await serverInstance.stop()}serverInstance=null;tokenFactory=null;serverStartedByUs=false}function createAuthFixture(factory){const users={admin:{sub:"admin-001",scopes:["admin:*","read","write","delete"],email:"admin@test.local",name:"Test Admin"},user:{sub:"user-001",scopes:["read","write"],email:"user@test.local",name:"Test User"},readOnly:{sub:"readonly-001",scopes:["read"],email:"readonly@test.local",name:"Read Only User"}};return{createToken:opts=>factory.createTestToken({sub:opts.sub,scopes:opts.scopes,claims:{email:opts.email,name:opts.name,...opts.claims},exp:opts.expiresIn}),createExpiredToken:opts=>factory.createExpiredToken(opts),createInvalidToken:opts=>factory.createTokenWithInvalidSignature(opts),users:{admin:users["admin"],user:users["user"],readOnly:users["readOnly"]},getJwks:()=>factory.getPublicJwks(),getIssuer:()=>factory.getIssuer(),getAudience:()=>factory.getAudience()}}function createServerFixture(server){return{info:server.info,createClient:async opts=>{return McpTestClient.create({baseUrl:server.info.baseUrl,transport:opts?.transport??"streamable-http",auth:opts?.token?{token:opts.token}:void 0,clientInfo:opts?.clientInfo,publicMode:currentConfig.publicMode}).buildAndConnect()},createClientBuilder:()=>{return new McpTestClientBuilder({baseUrl:server.info.baseUrl,publicMode:currentConfig.publicMode})},restart:()=>server.restart(),getLogs:()=>server.getLogs(),clearLogs:()=>server.clearLogs()}}function resolveServerCommand(server){if(server.includes(" ")){return server}return`npx tsx ${server}`}function perfTestWithFixtures(name,fn){it(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function use(config){currentConfig={...currentConfig,...config};afterAll(async()=>{await cleanupSharedResources()})}function skip(name,fn){it.skip(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function only(name,fn){it.only(name,async()=>{const{fixtures,perfImpl}=await createTestFixtures(name);let testFailed=false;try{await fn(fixtures)}catch(error){testFailed=true;throw error}finally{await cleanupTestFixtures(fixtures,perfImpl,testFailed)}})}function todo(name){it.todo(name)}var perfTest=perfTestWithFixtures;perfTest.use=use;for(const hook of["describe","beforeAll","beforeEach","afterEach","afterAll"]){Object.defineProperty(perfTest,hook,{get:()=>globalThis[hook],enumerable:true,configurable:true})}perfTest.skip=skip;perfTest.only=only;perfTest.todo=todo;var import_utils5=require("@frontmcp/utils");var BASELINE_START_MARKER="<!-- PERF_BASELINE_START -->";var BASELINE_END_MARKER="<!-- PERF_BASELINE_END -->";var DEFAULT_BASELINE_PATH="perf-results/baseline.json";var BaselineStore=class{baseline=null;baselinePath;constructor(baselinePath=DEFAULT_BASELINE_PATH){this.baselinePath=baselinePath}async load(){try{if(!await(0,import_utils5.fileExists)(this.baselinePath)){return null}const content=await(0,import_utils5.readFile)(this.baselinePath);this.baseline=JSON.parse(content);return this.baseline}catch{return null}}async save(baseline){const dir=this.baselinePath.substring(0,this.baselinePath.lastIndexOf("/"));await(0,import_utils5.ensureDir)(dir);await(0,import_utils5.writeFile)(this.baselinePath,JSON.stringify(baseline,null,2));this.baseline=baseline}getTestBaseline(testId){if(!this.baseline){return null}return this.baseline.tests[testId]??null}isLoaded(){return this.baseline!==null}getBaseline(){return this.baseline}static createFromMeasurements(measurements,release,commitHash){const tests={};const grouped=new Map;for(const m of measurements){const key=`${m.project}::${m.name}`;if(!grouped.has(key)){grouped.set(key,[])}const group=grouped.get(key);if(group){group.push(m)}}for(const[key,testMeasurements]of grouped){const[project]=key.split("::");const heapSamples=testMeasurements.map(m=>m.final?.memory.heapUsed??0);const durationSamples=testMeasurements.map(m=>m.timing.durationMs);const cpuSamples=testMeasurements.map(m=>m.final?.cpu.total??0);tests[key]={testId:key,project,heapUsed:calculateMetricBaseline(heapSamples),durationMs:calculateMetricBaseline(durationSamples),cpuTime:calculateMetricBaseline(cpuSamples),createdAt:new Date().toISOString(),commitHash}}return{release,timestamp:new Date().toISOString(),commitHash,tests}}};function parseBaselineFromComment(commentBody){const startIdx=commentBody.indexOf(BASELINE_START_MARKER);const endIdx=commentBody.indexOf(BASELINE_END_MARKER);if(startIdx===-1||endIdx===-1||startIdx>=endIdx){return null}const content=commentBody.substring(startIdx+BASELINE_START_MARKER.length,endIdx);const fenceStart=content.indexOf("```json");if(fenceStart===-1){return null}const jsonStart=fenceStart+"```json".length;const fenceEnd=content.indexOf("```",jsonStart);if(fenceEnd===-1){return null}try{return JSON.parse(content.slice(jsonStart,fenceEnd).trim())}catch{return null}}function formatBaselineAsComment(baseline){const json=JSON.stringify(baseline,null,2);return`## Performance Baseline
48
48
 
49
49
  This comment contains the performance baseline for release ${baseline.release}.
50
50
 
@@ -56,4 +56,4 @@ ${BASELINE_END_MARKER}
56
56
 
57
57
  Generated at: ${baseline.timestamp}
58
58
  ${baseline.commitHash?`Commit: ${baseline.commitHash}`:""}
59
- `}function buildReleaseCommentsUrl(owner,repo,releaseId){return`https://api.github.com/repos/${owner}/${repo}/releases/${releaseId}/comments`}function calculateMetricBaseline(samples){if(samples.length===0){return{mean:0,stdDev:0,min:0,max:0,p95:0,sampleCount:0}}const sorted=[...samples].sort((a,b)=>a-b);const n=sorted.length;const sum=sorted.reduce((a,b)=>a+b,0);const mean=sum/n;const squaredDiffs=sorted.map(x=>Math.pow(x-mean,2));const variance=squaredDiffs.reduce((a,b)=>a+b,0)/n;const stdDev=Math.sqrt(variance);const min=sorted[0];const max=sorted[n-1];const p95Index=Math.ceil(n*.95)-1;const p95=sorted[Math.min(p95Index,n-1)];return{mean,stdDev,min,max,p95,sampleCount:n}}var globalBaselineStore=null;function getBaselineStore(baselinePath){if(!globalBaselineStore||baselinePath){globalBaselineStore=new BaselineStore(baselinePath)}return globalBaselineStore}function resetBaselineStore(){globalBaselineStore=null}var DEFAULT_CONFIG={warningThresholdPercent:10,errorThresholdPercent:25,minAbsoluteChange:1024};var RegressionDetector=class{config;constructor(config){this.config={...DEFAULT_CONFIG,...config}}detectRegression(measurement,baseline){const testId=`${measurement.project}::${measurement.name}`;const metrics=[];const currentHeap=measurement.final?.memory.heapUsed??0;const heapRegression=this.checkMetric("heapUsed",baseline.heapUsed.mean,currentHeap,formatBytes);metrics.push(heapRegression);const durationRegression=this.checkMetric("durationMs",baseline.durationMs.mean,measurement.timing.durationMs,formatDuration);metrics.push(durationRegression);const currentCpu=measurement.final?.cpu.total??0;const cpuRegression=this.checkMetric("cpuTime",baseline.cpuTime.mean,currentCpu,formatMicroseconds);metrics.push(cpuRegression);const hasRegression=metrics.some(m=>m.status==="regression");const hasWarning=metrics.some(m=>m.status==="warning");const status=hasRegression?"regression":hasWarning?"warning":"ok";const message=this.buildMessage(testId,metrics,status);return{testId,status,metrics,message}}detectRegressions(measurements,baselines){const results=[];for(const measurement of measurements){const testId=`${measurement.project}::${measurement.name}`;const baseline=baselines.tests[testId];if(baseline){results.push(this.detectRegression(measurement,baseline))}}return results}checkMetric(name,baseline,current,_formatter){const absoluteChange=current-baseline;const changePercent=baseline>0?absoluteChange/baseline*100:0;let status="ok";if(Math.abs(absoluteChange)>this.config.minAbsoluteChange){if(changePercent>=this.config.errorThresholdPercent){status="regression"}else if(changePercent>=this.config.warningThresholdPercent){status="warning"}}return{metric:name,baseline,current,changePercent,absoluteChange,status}}buildMessage(testId,metrics,status){if(status==="ok"){return`${testId}: All metrics within acceptable range`}const issues=metrics.filter(m=>m.status!=="ok").map(m=>{const direction=m.absoluteChange>0?"+":"";return`${m.metric}: ${direction}${m.changePercent.toFixed(1)}%`});const statusText=status==="regression"?"REGRESSION":"WARNING";return`${testId}: ${statusText} - ${issues.join(", ")}`}};function summarizeRegressions(results){const total=results.length;const ok=results.filter(r=>r.status==="ok").length;const warnings=results.filter(r=>r.status==="warning").length;const regressions=results.filter(r=>r.status==="regression").length;let summary;if(regressions>0){summary=`${regressions} regression(s) detected out of ${total} tests`}else if(warnings>0){summary=`${warnings} warning(s) detected out of ${total} tests`}else{summary=`All ${total} tests within acceptable range`}return{total,ok,warnings,regressions,summary}}function filterByStatus(results,status){return results.filter(r=>r.status===status)}function getMostSevereMetric(result){const regressions=result.metrics.filter(m=>m.status==="regression");if(regressions.length>0){return regressions.reduce((max,m)=>m.changePercent>max.changePercent?m:max)}const warnings=result.metrics.filter(m=>m.status==="warning");if(warnings.length>0){return warnings.reduce((max,m)=>m.changePercent>max.changePercent?m:max)}return null}var globalDetector=null;function getRegressionDetector(config){if(!globalDetector||config){globalDetector=new RegressionDetector(config)}return globalDetector}function resetRegressionDetector(){globalDetector=null}var import_utils7=require("@frontmcp/utils");var ReportGenerator=class{detector;constructor(){this.detector=new RegressionDetector}generateReport(measurements,baseline,gitInfo){const projectGroups=new Map;for(const m of measurements){if(!projectGroups.has(m.project)){projectGroups.set(m.project,[])}const group=projectGroups.get(m.project);if(group){group.push(m)}}const projects=[];for(const[projectName,projectMeasurements]of projectGroups){const summary=this.calculateSummary(projectMeasurements);const regressions=baseline?this.detector.detectRegressions(projectMeasurements,baseline):void 0;projects.push({project:projectName,summary,measurements:projectMeasurements,regressions})}const overallSummary=this.calculateSummary(measurements);return{timestamp:new Date().toISOString(),commitHash:gitInfo?.commitHash,branch:gitInfo?.branch,summary:overallSummary,projects,baseline:baseline?{release:baseline.release,timestamp:baseline.timestamp}:void 0}}generateMarkdownReport(report){const lines=[];lines.push("## Performance Test Results");lines.push("");const statusEmoji=this.getStatusEmoji(report.summary);lines.push(`**Status:** ${statusEmoji} ${this.getSummaryText(report.summary)}`);lines.push("");lines.push("### Summary");lines.push("");lines.push("| Metric | Value |");lines.push("|--------|-------|");lines.push(`| Total Tests | ${report.summary.totalTests} |`);lines.push(`| Passed | ${report.summary.passedTests} |`);lines.push(`| Warnings | ${report.summary.warningTests} |`);lines.push(`| Failed | ${report.summary.failedTests} |`);lines.push(`| Memory Leaks | ${report.summary.leakTests} |`);lines.push("");if(report.baseline){lines.push(`**Baseline:** ${report.baseline.release} (${report.baseline.timestamp})`);lines.push("")}lines.push("### Project Breakdown");lines.push("");for(const project of report.projects){lines.push(`#### ${project.project}`);lines.push("");lines.push(this.generateProjectTable(project));lines.push("");const leakTests=project.measurements.filter(m=>m.leakDetectionResults&&m.leakDetectionResults.length>0);if(leakTests.length>0){const parallelTests=leakTests.filter(m=>m.leakDetectionResults?.some(r=>this.isParallelResult(r)));if(parallelTests.length>0){lines.push("**Parallel Stress Test Results:**");lines.push("");lines.push("| Test | Workers | Iterations | Duration | Total req/s |");lines.push("|------|---------|------------|----------|-------------|");for(const m of parallelTests){for(const result of m.leakDetectionResults||[]){if(this.isParallelResult(result)){const parallelResult=result;const durationStr=parallelResult.durationMs?`${(parallelResult.durationMs/1e3).toFixed(2)}s`:"N/A";lines.push(`| ${m.name} | ${parallelResult.workersUsed} | ${parallelResult.totalIterations} | ${durationStr} | ${parallelResult.totalRequestsPerSecond.toFixed(1)} |`)}}}lines.push("")}lines.push("**Memory Interval Analysis:**");lines.push("");for(const m of leakTests){for(const result of m.leakDetectionResults||[]){if(result.intervals&&result.intervals.length>0){lines.push(`*${m.name}:*`);lines.push("");if(this.isParallelResult(result)){const parallelResult=result;lines.push("| Worker | req/s | Iterations |");lines.push("|--------|-------|------------|");for(const worker of parallelResult.perWorkerStats){lines.push(`| ${worker.workerId} | ${worker.requestsPerSecond.toFixed(1)} | ${worker.iterationsCompleted} |`)}lines.push("")}lines.push("| Interval | Heap Start | Heap End | Delta | Rate/iter |");lines.push("|----------|------------|----------|-------|-----------|");for(const interval of result.intervals){lines.push(`| ${interval.startIteration}-${interval.endIteration} | ${formatBytes(interval.heapAtStart)} | ${formatBytes(interval.heapAtEnd)} | ${interval.deltaFormatted} | ${formatBytes(interval.growthRatePerIteration)}/iter |`)}lines.push("");const durationStr=result.durationMs?`${(result.durationMs/1e3).toFixed(2)}s`:"N/A";const rpsStr=result.requestsPerSecond?`${result.requestsPerSecond.toFixed(1)} req/s`:"N/A";lines.push(`Total: ${formatBytes(result.totalGrowth)}, R\xB2=${result.rSquared.toFixed(3)} | ${result.samples.length} iterations in ${durationStr} (${rpsStr})`);lines.push("")}}}}if(project.regressions&&project.regressions.length>0){const regressionsWithIssues=project.regressions.filter(r=>r.status!=="ok");if(regressionsWithIssues.length>0){lines.push("**Regressions:**");for(const r of regressionsWithIssues){const emoji=r.status==="regression"?"\u274C":"\u26A0\uFE0F";lines.push(`- ${emoji} ${r.message}`)}lines.push("")}}}lines.push("---");lines.push(`Generated at: ${report.timestamp}`);if(report.commitHash){lines.push(`Commit: \`${report.commitHash.substring(0,8)}\``)}if(report.branch){lines.push(`Branch: \`${report.branch}\``)}return lines.join("\n")}generateJsonReport(report){return JSON.stringify(report,null,2)}calculateSummary(measurements){let passedTests=0;let warningTests=0;let failedTests=0;let leakTests=0;for(const m of measurements){const hasError=m.issues.some(i=>i.severity==="error");const hasWarning=m.issues.some(i=>i.severity==="warning");const hasLeak=m.issues.some(i=>i.type==="memory-leak");if(hasLeak){leakTests++}if(hasError){failedTests++}else if(hasWarning){warningTests++}else{passedTests++}}return{totalTests:measurements.length,passedTests,warningTests,failedTests,leakTests}}getStatusEmoji(summary){if(summary.failedTests>0||summary.leakTests>0){return"X"}if(summary.warningTests>0){return"!"}return"OK"}getSummaryText(summary){if(summary.failedTests>0){return`${summary.failedTests} test(s) failed`}if(summary.leakTests>0){return`${summary.leakTests} memory leak(s) detected`}if(summary.warningTests>0){return`${summary.warningTests} warning(s)`}return"All tests passed"}generateProjectTable(project){const lines=[];lines.push("| Test | Duration | Heap Delta | CPU Time | Status |");lines.push("|------|----------|------------|----------|--------|");for(const m of project.measurements){const status=this.getTestStatus(m);const heapDelta=m.memoryDelta?formatBytes(m.memoryDelta.heapUsed):"N/A";const cpuTime=m.final?.cpu.total?formatMicroseconds(m.final.cpu.total):"N/A";lines.push(`| ${m.name} | ${formatDuration(m.timing.durationMs)} | ${heapDelta} | ${cpuTime} | ${status} |`)}return lines.join("\n")}getTestStatus(m){const hasError=m.issues.some(i=>i.severity==="error");const hasLeak=m.issues.some(i=>i.type==="memory-leak");const hasWarning=m.issues.some(i=>i.severity==="warning");if(hasLeak){return"LEAK"}if(hasError){return"FAIL"}if(hasWarning){return"WARN"}return"OK"}isParallelResult(result){return typeof result==="object"&&result!==null&&"workersUsed"in result&&"perWorkerStats"in result&&"totalRequestsPerSecond"in result}};async function saveReports(measurements,outputDir,baseline,gitInfo){await(0,import_utils7.ensureDir)(outputDir);const generator=new ReportGenerator;const report=generator.generateReport(measurements,baseline,gitInfo);const jsonPath=`${outputDir}/report.json`;const markdownPath=`${outputDir}/report.md`;await(0,import_utils7.writeFile)(jsonPath,generator.generateJsonReport(report));await(0,import_utils7.writeFile)(markdownPath,generator.generateMarkdownReport(report));return{jsonPath,markdownPath}}function createReportGenerator(){return new ReportGenerator}0&&(module.exports={BaselineStore,LeakDetector,MetricsCollector,PerfFixturesImpl,RegressionDetector,ReportGenerator,addGlobalMeasurement,assertNoLeak,buildReleaseCommentsUrl,clearGlobalMeasurements,createLeakDetector,createPerfFixtures,createReportGenerator,filterByStatus,forceFullGc,forceGc,formatBaselineAsComment,formatBytes,formatDuration,formatMicroseconds,getBaselineStore,getGlobalCollector,getGlobalMeasurements,getMeasurementsForProject,getMostSevereMetric,getRegressionDetector,isGcAvailable,parseBaselineFromComment,perfTest,resetBaselineStore,resetGlobalCollector,resetRegressionDetector,saveReports,summarizeRegressions});
59
+ `}function buildReleaseCommentsUrl(owner,repo,releaseId){return`https://api.github.com/repos/${owner}/${repo}/releases/${releaseId}/comments`}function calculateMetricBaseline(samples){if(samples.length===0){return{mean:0,stdDev:0,min:0,max:0,p95:0,sampleCount:0}}const sorted=[...samples].sort((a,b)=>a-b);const n=sorted.length;const sum=sorted.reduce((a,b)=>a+b,0);const mean=sum/n;const squaredDiffs=sorted.map(x=>Math.pow(x-mean,2));const variance=squaredDiffs.reduce((a,b)=>a+b,0)/n;const stdDev=Math.sqrt(variance);const min=sorted[0];const max=sorted[n-1];const p95Index=Math.ceil(n*.95)-1;const p95=sorted[Math.min(p95Index,n-1)];return{mean,stdDev,min,max,p95,sampleCount:n}}var globalBaselineStore=null;function getBaselineStore(baselinePath){if(!globalBaselineStore||baselinePath){globalBaselineStore=new BaselineStore(baselinePath)}return globalBaselineStore}function resetBaselineStore(){globalBaselineStore=null}var DEFAULT_CONFIG={warningThresholdPercent:10,errorThresholdPercent:25,minAbsoluteChange:1024};var RegressionDetector=class{config;constructor(config){this.config={...DEFAULT_CONFIG,...config}}detectRegression(measurement,baseline){const testId=`${measurement.project}::${measurement.name}`;const metrics=[];const currentHeap=measurement.final?.memory.heapUsed??0;const heapRegression=this.checkMetric("heapUsed",baseline.heapUsed.mean,currentHeap,formatBytes);metrics.push(heapRegression);const durationRegression=this.checkMetric("durationMs",baseline.durationMs.mean,measurement.timing.durationMs,formatDuration);metrics.push(durationRegression);const currentCpu=measurement.final?.cpu.total??0;const cpuRegression=this.checkMetric("cpuTime",baseline.cpuTime.mean,currentCpu,formatMicroseconds);metrics.push(cpuRegression);const hasRegression=metrics.some(m=>m.status==="regression");const hasWarning=metrics.some(m=>m.status==="warning");const status=hasRegression?"regression":hasWarning?"warning":"ok";const message=this.buildMessage(testId,metrics,status);return{testId,status,metrics,message}}detectRegressions(measurements,baselines){const results=[];for(const measurement of measurements){const testId=`${measurement.project}::${measurement.name}`;const baseline=baselines.tests[testId];if(baseline){results.push(this.detectRegression(measurement,baseline))}}return results}checkMetric(name,baseline,current,_formatter){const absoluteChange=current-baseline;const changePercent=baseline>0?absoluteChange/baseline*100:0;let status="ok";if(Math.abs(absoluteChange)>this.config.minAbsoluteChange){if(changePercent>=this.config.errorThresholdPercent){status="regression"}else if(changePercent>=this.config.warningThresholdPercent){status="warning"}}return{metric:name,baseline,current,changePercent,absoluteChange,status}}buildMessage(testId,metrics,status){if(status==="ok"){return`${testId}: All metrics within acceptable range`}const issues=metrics.filter(m=>m.status!=="ok").map(m=>{const direction=m.absoluteChange>0?"+":"";return`${m.metric}: ${direction}${m.changePercent.toFixed(1)}%`});const statusText=status==="regression"?"REGRESSION":"WARNING";return`${testId}: ${statusText} - ${issues.join(", ")}`}};function summarizeRegressions(results){const total=results.length;const ok=results.filter(r=>r.status==="ok").length;const warnings=results.filter(r=>r.status==="warning").length;const regressions=results.filter(r=>r.status==="regression").length;let summary;if(regressions>0){summary=`${regressions} regression(s) detected out of ${total} tests`}else if(warnings>0){summary=`${warnings} warning(s) detected out of ${total} tests`}else{summary=`All ${total} tests within acceptable range`}return{total,ok,warnings,regressions,summary}}function filterByStatus(results,status){return results.filter(r=>r.status===status)}function getMostSevereMetric(result){const regressions=result.metrics.filter(m=>m.status==="regression");if(regressions.length>0){return regressions.reduce((max,m)=>m.changePercent>max.changePercent?m:max)}const warnings=result.metrics.filter(m=>m.status==="warning");if(warnings.length>0){return warnings.reduce((max,m)=>m.changePercent>max.changePercent?m:max)}return null}var globalDetector=null;function getRegressionDetector(config){if(!globalDetector||config){globalDetector=new RegressionDetector(config)}return globalDetector}function resetRegressionDetector(){globalDetector=null}var import_utils6=require("@frontmcp/utils");var ReportGenerator=class{detector;constructor(){this.detector=new RegressionDetector}generateReport(measurements,baseline,gitInfo){const projectGroups=new Map;for(const m of measurements){if(!projectGroups.has(m.project)){projectGroups.set(m.project,[])}const group=projectGroups.get(m.project);if(group){group.push(m)}}const projects=[];for(const[projectName,projectMeasurements]of projectGroups){const summary=this.calculateSummary(projectMeasurements);const regressions=baseline?this.detector.detectRegressions(projectMeasurements,baseline):void 0;projects.push({project:projectName,summary,measurements:projectMeasurements,regressions})}const overallSummary=this.calculateSummary(measurements);return{timestamp:new Date().toISOString(),commitHash:gitInfo?.commitHash,branch:gitInfo?.branch,summary:overallSummary,projects,baseline:baseline?{release:baseline.release,timestamp:baseline.timestamp}:void 0}}generateMarkdownReport(report){const lines=[];lines.push("## Performance Test Results");lines.push("");const statusEmoji=this.getStatusEmoji(report.summary);lines.push(`**Status:** ${statusEmoji} ${this.getSummaryText(report.summary)}`);lines.push("");lines.push("### Summary");lines.push("");lines.push("| Metric | Value |");lines.push("|--------|-------|");lines.push(`| Total Tests | ${report.summary.totalTests} |`);lines.push(`| Passed | ${report.summary.passedTests} |`);lines.push(`| Warnings | ${report.summary.warningTests} |`);lines.push(`| Failed | ${report.summary.failedTests} |`);lines.push(`| Memory Leaks | ${report.summary.leakTests} |`);lines.push("");if(report.baseline){lines.push(`**Baseline:** ${report.baseline.release} (${report.baseline.timestamp})`);lines.push("")}lines.push("### Project Breakdown");lines.push("");for(const project of report.projects){lines.push(`#### ${project.project}`);lines.push("");lines.push(this.generateProjectTable(project));lines.push("");const leakTests=project.measurements.filter(m=>m.leakDetectionResults&&m.leakDetectionResults.length>0);if(leakTests.length>0){const parallelTests=leakTests.filter(m=>m.leakDetectionResults?.some(r=>this.isParallelResult(r)));if(parallelTests.length>0){lines.push("**Parallel Stress Test Results:**");lines.push("");lines.push("| Test | Workers | Iterations | Duration | Total req/s |");lines.push("|------|---------|------------|----------|-------------|");for(const m of parallelTests){for(const result of m.leakDetectionResults||[]){if(this.isParallelResult(result)){const parallelResult=result;const durationStr=parallelResult.durationMs?`${(parallelResult.durationMs/1e3).toFixed(2)}s`:"N/A";lines.push(`| ${m.name} | ${parallelResult.workersUsed} | ${parallelResult.totalIterations} | ${durationStr} | ${parallelResult.totalRequestsPerSecond.toFixed(1)} |`)}}}lines.push("")}lines.push("**Memory Interval Analysis:**");lines.push("");for(const m of leakTests){for(const result of m.leakDetectionResults||[]){if(result.intervals&&result.intervals.length>0){lines.push(`*${m.name}:*`);lines.push("");if(this.isParallelResult(result)){const parallelResult=result;lines.push("| Worker | req/s | Iterations |");lines.push("|--------|-------|------------|");for(const worker of parallelResult.perWorkerStats){lines.push(`| ${worker.workerId} | ${worker.requestsPerSecond.toFixed(1)} | ${worker.iterationsCompleted} |`)}lines.push("")}lines.push("| Interval | Heap Start | Heap End | Delta | Rate/iter |");lines.push("|----------|------------|----------|-------|-----------|");for(const interval of result.intervals){lines.push(`| ${interval.startIteration}-${interval.endIteration} | ${formatBytes(interval.heapAtStart)} | ${formatBytes(interval.heapAtEnd)} | ${interval.deltaFormatted} | ${formatBytes(interval.growthRatePerIteration)}/iter |`)}lines.push("");const durationStr=result.durationMs?`${(result.durationMs/1e3).toFixed(2)}s`:"N/A";const rpsStr=result.requestsPerSecond?`${result.requestsPerSecond.toFixed(1)} req/s`:"N/A";lines.push(`Total: ${formatBytes(result.totalGrowth)}, R\xB2=${result.rSquared.toFixed(3)} | ${result.samples.length} iterations in ${durationStr} (${rpsStr})`);lines.push("")}}}}if(project.regressions&&project.regressions.length>0){const regressionsWithIssues=project.regressions.filter(r=>r.status!=="ok");if(regressionsWithIssues.length>0){lines.push("**Regressions:**");for(const r of regressionsWithIssues){const emoji=r.status==="regression"?"\u274C":"\u26A0\uFE0F";lines.push(`- ${emoji} ${r.message}`)}lines.push("")}}}lines.push("---");lines.push(`Generated at: ${report.timestamp}`);if(report.commitHash){lines.push(`Commit: \`${report.commitHash.substring(0,8)}\``)}if(report.branch){lines.push(`Branch: \`${report.branch}\``)}return lines.join("\n")}generateJsonReport(report){return JSON.stringify(report,null,2)}calculateSummary(measurements){let passedTests=0;let warningTests=0;let failedTests=0;let leakTests=0;for(const m of measurements){const hasError=m.issues.some(i=>i.severity==="error");const hasWarning=m.issues.some(i=>i.severity==="warning");const hasLeak=m.issues.some(i=>i.type==="memory-leak");if(hasLeak){leakTests++}if(hasError){failedTests++}else if(hasWarning){warningTests++}else{passedTests++}}return{totalTests:measurements.length,passedTests,warningTests,failedTests,leakTests}}getStatusEmoji(summary){if(summary.failedTests>0||summary.leakTests>0){return"X"}if(summary.warningTests>0){return"!"}return"OK"}getSummaryText(summary){if(summary.failedTests>0){return`${summary.failedTests} test(s) failed`}if(summary.leakTests>0){return`${summary.leakTests} memory leak(s) detected`}if(summary.warningTests>0){return`${summary.warningTests} warning(s)`}return"All tests passed"}generateProjectTable(project){const lines=[];lines.push("| Test | Duration | Heap Delta | CPU Time | Status |");lines.push("|------|----------|------------|----------|--------|");for(const m of project.measurements){const status=this.getTestStatus(m);const heapDelta=m.memoryDelta?formatBytes(m.memoryDelta.heapUsed):"N/A";const cpuTime=m.final?.cpu.total?formatMicroseconds(m.final.cpu.total):"N/A";lines.push(`| ${m.name} | ${formatDuration(m.timing.durationMs)} | ${heapDelta} | ${cpuTime} | ${status} |`)}return lines.join("\n")}getTestStatus(m){const hasError=m.issues.some(i=>i.severity==="error");const hasLeak=m.issues.some(i=>i.type==="memory-leak");const hasWarning=m.issues.some(i=>i.severity==="warning");if(hasLeak){return"LEAK"}if(hasError){return"FAIL"}if(hasWarning){return"WARN"}return"OK"}isParallelResult(result){return typeof result==="object"&&result!==null&&"workersUsed"in result&&"perWorkerStats"in result&&"totalRequestsPerSecond"in result}};async function saveReports(measurements,outputDir,baseline,gitInfo){await(0,import_utils6.ensureDir)(outputDir);const generator=new ReportGenerator;const report=generator.generateReport(measurements,baseline,gitInfo);const jsonPath=`${outputDir}/report.json`;const markdownPath=`${outputDir}/report.md`;await(0,import_utils6.writeFile)(jsonPath,generator.generateJsonReport(report));await(0,import_utils6.writeFile)(markdownPath,generator.generateMarkdownReport(report));return{jsonPath,markdownPath}}function createReportGenerator(){return new ReportGenerator}0&&(module.exports={BaselineStore,LeakDetector,MetricsCollector,PerfFixturesImpl,RegressionDetector,ReportGenerator,addGlobalMeasurement,assertNoLeak,buildReleaseCommentsUrl,clearGlobalMeasurements,createLeakDetector,createPerfFixtures,createReportGenerator,filterByStatus,forceFullGc,forceGc,formatBaselineAsComment,formatBytes,formatDuration,formatMicroseconds,getBaselineStore,getGlobalCollector,getGlobalMeasurements,getMeasurementsForProject,getMostSevereMetric,getRegressionDetector,isGcAvailable,parseBaselineFromComment,perfTest,resetBaselineStore,resetGlobalCollector,resetRegressionDetector,saveReports,summarizeRegressions});