@frontmcp/testing 1.10.15 → 1.11.0-rc.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/README.md CHANGED
@@ -36,7 +36,26 @@ test('tool execution works', async ({ mcp }) => {
36
36
  npx frontmcp test
37
37
  ```
38
38
 
39
- `frontmcp test` (from the [`frontmcp`](https://www.npmjs.com/package/frontmcp) CLI) runs `src/**/*.spec.ts`, `__tests__/**/*.spec.ts` and `e2e/**/*.e2e.spec.ts` with a Jest configuration it generates. With a `jest.config.*` of your own, use `preset: '@frontmcp/testing'` for the same settings. The server starts when the first test that needs it runs, and tests with the same `test.use()` options share it.
39
+ `frontmcp test` (from the [`frontmcp`](https://www.npmjs.com/package/frontmcp) CLI) runs `src/**/*.spec.ts`, `__tests__/**/*.spec.ts` and `e2e/**/*.e2e.spec.ts` with a Jest configuration it generates. With a `jest.config.*` of your own, start from one of the [Jest presets](#jest-presets). The server starts when the first test that needs it runs, and tests with the same `test.use()` options share it.
40
+
41
+ ## Jest presets
42
+
43
+ | Preset | Use it for |
44
+ | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | `preset: '@frontmcp/testing'` | The configuration `frontmcp test` generates: unit and e2e specs, a 60-second timeout, and the matchers registered through `@frontmcp/testing/setup` |
46
+ | `preset: '@frontmcp/testing/jest-preset-unit'` | Unit tests, in a CommonJS project too: Jest's default 5-second timeout, no setup file, and every `*.spec.ts(x)` except `*.e2e.spec`, `*.perf.spec` and `*.pw.spec` files. Add `@frontmcp/testing/setup` to `setupFilesAfterEnv` to use the matchers |
47
+
48
+ Both compile TypeScript and TSX with `@swc/jest`, and both compile `jose`, `@noble/hashes` and `@noble/ciphers`, ESM-only packages the SDK loads, which Jest's CommonJS runtime otherwise fails on with `SyntaxError: Unexpected token 'export'`. To compile your TypeScript with `ts-jest`, set a transform for `.ts` only, so the preset still compiles those packages:
49
+
50
+ ```js
51
+ // jest.config.js
52
+ module.exports = {
53
+ preset: '@frontmcp/testing/jest-preset-unit',
54
+ transform: { '^.+\\.tsx?$': 'ts-jest' },
55
+ };
56
+ ```
57
+
58
+ `testMatch` and `transformIgnorePatterns` of your own replace the preset's lists, so copy its entries into yours.
40
59
 
41
60
  ## Fixtures
42
61
 
@@ -50,7 +69,7 @@ npx frontmcp test
50
69
 
51
70
  ## Matchers
52
71
 
53
- **Tools**: `toContainTool`, `toBeSuccessful`, `toBeError`, `toHaveTextContent`, `toHaveImageContent`, `toHaveResourceContent`
72
+ **Tools**: `toContainTool`, `toBeSuccessful`, `toBeError`, `toHaveTextContent`, `toHaveImageContent`, `toHaveResourceContent`, `toPassOutputSchemaWhole`
54
73
 
55
74
  **Resources**: `toContainResource`, `toContainResourceTemplate`, `toHaveMimeType`
56
75
 
@@ -60,7 +79,7 @@ npx frontmcp test
60
79
 
61
80
  **Tool UI**: `toHaveRenderedHtml`, `toContainHtmlElement`, `toContainBoundValue`, `toBeXssSafe`, `toHaveWidgetMetadata`, `toHaveCssClass`, `toNotContainRawContent`, `toHaveProperHtmlStructure`
62
81
 
63
- Use them through the `expect` this package exports, which is Jest's `expect` with these matchers typed. `frontmcp test` and the preset also register them on Jest's global `expect`, through `@frontmcp/testing/setup`, which you can add to `setupFilesAfterEnv` yourself.
82
+ Use them through the `expect` this package exports, which is Jest's `expect` with these matchers typed. `frontmcp test` and the `@frontmcp/testing` preset register them, through `@frontmcp/testing/setup`, which you can add to `setupFilesAfterEnv` yourself.
64
83
 
65
84
  ## Configuration
66
85
 
@@ -97,13 +97,14 @@ export declare class McpTestClient {
97
97
  */
98
98
  read: (uri: string) => Promise<ResourceContentWrapper>;
99
99
  /**
100
- * Subscribe to resource changes (placeholder for future implementation)
100
+ * Subscribe to a resource: the server then sends `notifications/resources/updated` when it changes.
101
+ * Throws with the server's error when it refuses the subscription.
101
102
  */
102
- subscribe: (_uri: string) => Promise<void>;
103
+ subscribe: (uri: string) => Promise<void>;
103
104
  /**
104
- * Unsubscribe from resource changes (placeholder for future implementation)
105
+ * Unsubscribe from a resource's changes.
105
106
  */
106
- unsubscribe: (_uri: string) => Promise<void>;
107
+ unsubscribe: (uri: string) => Promise<void>;
107
108
  };
108
109
  readonly prompts: {
109
110
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-test-client.d.ts","sourceRoot":"","sources":["../../src/client/mcp-test-client.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACzB,MAAM,gBAAgB,CAAC;AAKxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,KAAK,EACV,SAAS,EAET,kBAAkB,EAElB,gBAAgB,EAChB,eAAe,EAKf,QAAQ,EAGR,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,MAAM,EACN,mBAAmB,EAEnB,YAAY,EACZ,QAAQ,EACR,sBAAsB,EACtB,gBAAgB,EAChB,WAAW,EAEX,iBAAiB,EACjB,IAAI,EACJ,eAAe,EACf,iBAAiB,EAClB,MAAM,yBAAyB,CAAC;AA4DjC,qBAAa,aAAa;IAExB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAGgE;IACvF,OAAO,CAAC,SAAS,CAA6B;IAC9C,OAAO,CAAC,UAAU,CAAiC;IACnD,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,cAAc,CAAsB;IAC5C,OAAO,CAAC,UAAU,CAAqB;IACvC,8DAA8D;IAC9D,OAAO,CAAC,wBAAwB,CAAS;IACzC,OAAO,CAAC,YAAY,CAA4B;IAChD,OAAO,CAAC,UAAU,CAAgD;IAGlE,OAAO,CAAC,KAAK,CAAkB;IAC/B,OAAO,CAAC,OAAO,CAAsB;IACrC,OAAO,CAAC,cAAc,CAA2B;IACjD,OAAO,CAAC,gBAAgB,CAAwB;IAChD,OAAO,CAAC,kBAA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MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAS7E;AAED,cAAM,iBAAiB;IACT,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,cAAc,EAAE;IAEtD,IAAI,GAAG,IAAI,cAAc,EAAE,CAE1B;IAEK,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAWxD"}
package/errors/index.d.ts CHANGED
@@ -43,4 +43,12 @@ export declare class ServerStartError extends TestClientError {
43
43
  export declare class AssertionError extends TestClientError {
44
44
  constructor(message: string);
45
45
  }
46
+ /**
47
+ * Error thrown when a call recording has a line that is not a call record
48
+ */
49
+ export declare class ReplayRecordingError extends TestClientError {
50
+ readonly file: string;
51
+ readonly line: number;
52
+ constructor(file: string, line: number, reason: string);
53
+ }
46
54
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/errors/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;gBAC5B,OAAO,EAAE,MAAM;CAM5B;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,eAAe;aAGvB,KAAK,CAAC,EAAE,KAAK;gBADtC,OAAO,EAAE,MAAM,EACU,KAAK,CAAC,EAAE,KAAK,YAAA;CAMzC;AAED;;GAEG;AACH,qBAAa,YAAa,SAAQ,eAAe;aAG7B,SAAS,EAAE,MAAM;gBADjC,OAAO,EAAE,MAAM,EACC,SAAS,EAAE,MAAM;CAMpC;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,eAAe;aAGjC,IAAI,EAAE,MAAM;aACZ,IAAI,CAAC,EAAE,OAAO;gBAF9B,OAAO,EAAE,MAAM,EACC,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,YAAA;CAMjC;AAED;;GAEG;AACH,qBAAa,gBAAiB,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1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});import{exportJWK,generateKeyPair,SignJWT}from"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 generateKeyPair("RS256",{extractable:true});this.privateKey=privateKey;this.publicKey=publicKey;this.jwk=await 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 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",scopes2=["read","write"]){return this.createTestToken({sub,scopes:scopes2,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 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 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 sleep(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 sleep(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 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=`${url.pathname.replace(/\/+$/,"")}/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=(this.entryPath??"").replace(/^\/+|\/+$/g,"");const basePath=url.pathname.replace(/\/+$/,"");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 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;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}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 headers=this.buildHeaders();this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url}`,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});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}`);jsonResponse={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(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();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();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 close(){this.closeNotificationStream();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.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}async readNotificationStream(controller,reader){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 this.handleSSEEvent(event)}}}}catch(error){this.log("Notification stream ended:",error)}finally{reader.releaseLock()}if(controller.signal.aborted||this.notificationStream!==controller)return;this.releaseNotificationStream(controller);this.notificationStreamReopenTimer=setTimeout(()=>void this.connectNotificationStream(),NOTIFICATION_STREAM_REOPEN_DELAY_MS)}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=(this.config.entryPath??"").replace(/^\/+|\/+$/g,"");const basePath=url.pathname.replace(/\/+$/,"");url.pathname=entry?`${basePath}/${entry}`:`${basePath}/`;return url.toString()}buildHeaders(){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){headers["mcp-session-id"]=this.sessionId}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 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"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}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}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 UNSUPPORTED_PROTOCOL_VERSIONS=["2026-07-28"];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 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;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;constructor(config){if(config.protocolVersion&&UNSUPPORTED_PROTOCOL_VERSIONS.includes(config.protocolVersion)){throw new Error(`McpTestClient does not support protocol version ${config.protocolVersion}: it has no initialize handshake. Use ${DEFAULT_PROTOCOL_VERSION} or earlier.`)}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,clientInfo:config.clientInfo??DEFAULT_CLIENT_INFO,platform:config.platform,capabilities:config.capabilities,queryParams:config.queryParams};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.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=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};await this.transport.notify({jsonrpc:"2.0",method:"notifications/initialized"});await this.transport.openNotificationStream?.(this.initResult.protocolVersion);this.log("info",`Connected to ${this.initResult.serverInfo?.name??"MCP Server"}`);return this.initResult}async disconnect(){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]}tools={list:async()=>this.listAllPages("tools/list","tools",cursor=>this.listTools(cursor),page=>page.tools),call:async(name,args,options={})=>{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=>{this.log("warn","Resource subscription not yet implemented")},unsubscribe:async _uri=>{this.log("warn","Resource unsubscription not yet implemented")}};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)}};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)}}async initialize(){const capabilities=this.config.capabilities??{sampling:{},elicitation:{form:{}}};return this.request("initialize",{protocolVersion:this.config.protocolVersion,capabilities,clientInfo:this.config.clientInfo})}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}=notification.params??{};this._progressUpdates.push({progress:Number(progress),total:typeof total==="number"?total: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=(this.config.entryPath??"").replace(/^\/+|\/+$/g,"");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});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){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 scopes2=payload["scopes"];if(typeof scope==="string"){return scope.split(" ")}if(Array.isArray(scopes2)){return scopes2}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")}};import{execFile,spawn}from"child_process";import{connect}from"net";import{sha256Hex}from"@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};import{createServer}from"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},"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=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 sleep2(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 sleep2(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 sleep2(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 sleep2(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 sleep2(300)}this.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}.
4
+ var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});import{exportJWK,generateKeyPair,SignJWT}from"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 generateKeyPair("RS256",{extractable:true});this.privateKey=privateKey;this.publicKey=publicKey;this.jwk=await 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 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",scopes2=["read","write"]){return this.createTestToken({sub,scopes:scopes2,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 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}};import{trimSlashes as trimSlashes3}from"@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 sleep(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 sleep(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)}import{trimSlashes,trimTrailing}from"@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=`${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=trimSlashes(this.entryPath);const basePath=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}import{trimSlashes as trimSlashes2,trimTrailing as trimTrailing2}from"@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;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}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 headers=this.buildHeaders();this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url}`,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});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}`);jsonResponse={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(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();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();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 close(){this.closeNotificationStream();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.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}async readNotificationStream(controller,reader){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 this.handleSSEEvent(event)}}}}catch(error){this.log("Notification stream ended:",error)}finally{reader.releaseLock()}if(controller.signal.aborted||this.notificationStream!==controller)return;this.releaseNotificationStream(controller);this.notificationStreamReopenTimer=setTimeout(()=>void this.connectNotificationStream(),NOTIFICATION_STREAM_REOPEN_DELAY_MS)}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=trimSlashes2(this.config.entryPath);const basePath=trimTrailing2(url.pathname,"/");url.pathname=entry?`${basePath}/${entry}`:`${basePath}/`;return url.toString()}buildHeaders(){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){headers["mcp-session-id"]=this.sessionId}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 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}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}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 UNSUPPORTED_PROTOCOL_VERSIONS=["2026-07-28"];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 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;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;constructor(config){if(config.protocolVersion&&UNSUPPORTED_PROTOCOL_VERSIONS.includes(config.protocolVersion)){throw new Error(`McpTestClient does not support protocol version ${config.protocolVersion}: it has no initialize handshake. Use ${DEFAULT_PROTOCOL_VERSION} or earlier.`)}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,clientInfo:config.clientInfo??DEFAULT_CLIENT_INFO,platform:config.platform,capabilities:config.capabilities,queryParams:config.queryParams};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.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=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};await this.transport.notify({jsonrpc:"2.0",method:"notifications/initialized"});await this.transport.openNotificationStream?.(this.initResult.protocolVersion);this.log("info",`Connected to ${this.initResult.serverInfo?.name??"MCP Server"}`);return this.initResult}async disconnect(){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]}tools={list:async()=>this.listAllPages("tools/list","tools",cursor=>this.listTools(cursor),page=>page.tools),call:async(name,args,options={})=>{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=>{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=>{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)}};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)}}async initialize(){const capabilities=this.config.capabilities??{sampling:{},elicitation:{form:{}}};return this.request("initialize",{protocolVersion:this.config.protocolVersion,capabilities,clientInfo:this.config.clientInfo})}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}=notification.params??{};this._progressUpdates.push({progress:Number(progress),total:typeof total==="number"?total: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=trimSlashes3(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});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){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 scopes2=payload["scopes"];if(typeof scope==="string"){return scope.split(" ")}if(Array.isArray(scopes2)){return scopes2}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")}};import{execFile,spawn}from"child_process";import{connect}from"net";import{sha256Hex}from"@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};import{createServer}from"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},"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=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 sleep2(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 sleep2(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 sleep2(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 sleep2(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 sleep2(300)}this.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}.
5
5
 
6
6
  Command: ${this.options.command}
7
7
  CWD: ${this.options.cwd}
@@ -26,7 +26,7 @@ Last health check error: ${lastHealthCheckError??"none"}
26
26
  === Server Logs ===
27
27
  ${allLogs||"No logs captured"}
28
28
 
29
- TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`)}log(message){if(this.options.debug){console.log(`[TestServer] ${message}`)}}};function sleep2(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=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=>{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",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})}import{trimSlashes,trimTrailing}from"@frontmcp/utils";function gatewayTokenBinding(serverUrl,entryPath){const base=trimTrailing(serverUrl,"/");const prefix=trimSlashes(entryPath??"");const mcpUrl=prefix?`${base}/${prefix}`:base;return{issuer:mcpUrl,audience:mcpUrl}}var jestApi;function jestGlobals(){if(jestApi)return jestApi;try{const api=__require("@jest/globals");jestApi={describe:api["describe"],beforeAll:api["beforeAll"],beforeEach:api["beforeEach"],afterEach:api["afterEach"],afterAll:api["afterAll"],it:api["it"]};return jestApi}catch(error){throw new Error(`@frontmcp/testing fixtures ("test", "test.use", ...) can only be used inside a Jest test file: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}function newScope(parent){return{skipped:parent?.skipped??false,reason:parent?.reason,config:{},envs:[],configured:false,cleanupRegistered:false,beforeEachHooks:[],afterEachHooks:[]}}var scopes=[newScope()];function currentScope(){return scopes[scopes.length-1]}var serverEntries=new Map;function resolveConfig(chain){const merged={};for(const scope of chain){Object.assign(merged,scope.config);for(const env of scope.envs)merged.env={...merged.env,...env}}return merged}function ownerScopeOf(chain){for(let i=chain.length-1;i>0;i--){if(chain[i].configured)return chain[i]}return chain[0]}function serverKey(config){const env=Object.fromEntries(Object.entries(config.env??{}).sort(([a],[b])=>a.localeCompare(b)));return JSON.stringify({server:config.server,baseUrl:config.baseUrl,project:config.project,port:config.port,entryPath:config.entryPath,startupTimeout:config.startupTimeout,logLevel:config.logLevel,auth:config.auth,env})}function serverEnv(config){const extra={};if(config.logLevel)extra["FRONTMCP_LOG_LEVEL"]=config.logLevel;if(config.auth?.mode)extra["FRONTMCP_TEST_AUTH_MODE"]=config.auth.mode;if(config.auth?.type)extra["FRONTMCP_TEST_AUTH_TYPE"]=config.auth.type;if(Object.keys(extra).length===0&&!config.env)return void 0;return{...extra,...config.env}}async function startServerEntry(config,owner){let server;let startedByUs=false;if(config.baseUrl&&!config.server){server=TestServer.connect(config.baseUrl)}else if(config.server){const serverCommand=resolveServerCommand(config.server);const isDebug=config.logLevel==="debug"||process.env["DEBUG"]==="1"||process.env["DEBUG_SERVER"]==="1";if(isDebug){console.log(`[TestFixture] Starting server: ${serverCommand}`)}try{server=await TestServer.start({project:config.project,port:config.port,command:serverCommand,env:serverEnv(config),startupTimeout:config.startupTimeout??3e4,debug:isDebug});startedByUs=true;if(isDebug){console.log(`[TestFixture] Server started at ${server.info.baseUrl}`)}}catch(error){const errMsg=error instanceof Error?error.message:String(error);throw new Error(`Failed to start test server.
29
+ TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`)}log(message){if(this.options.debug){console.log(`[TestServer] ${message}`)}}};function sleep2(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=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=>{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",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})}import{trimSlashes as trimSlashes4,trimTrailing as trimTrailing3}from"@frontmcp/utils";function gatewayTokenBinding(serverUrl,entryPath){const base=trimTrailing3(serverUrl,"/");const prefix=trimSlashes4(entryPath??"");const mcpUrl=prefix?`${base}/${prefix}`:base;return{issuer:mcpUrl,audience:mcpUrl}}var jestApi;function jestGlobals(){if(jestApi)return jestApi;try{const api=__require("@jest/globals");jestApi={describe:api["describe"],beforeAll:api["beforeAll"],beforeEach:api["beforeEach"],afterEach:api["afterEach"],afterAll:api["afterAll"],it:api["it"]};return jestApi}catch(error){throw new Error(`@frontmcp/testing fixtures ("test", "test.use", ...) can only be used inside a Jest test file: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}function newScope(parent){return{skipped:parent?.skipped??false,reason:parent?.reason,config:{},envs:[],configured:false,cleanupRegistered:false,beforeEachHooks:[],afterEachHooks:[]}}var scopes=[newScope()];function currentScope(){return scopes[scopes.length-1]}var serverEntries=new Map;function resolveConfig(chain){const merged={};for(const scope of chain){Object.assign(merged,scope.config);for(const env of scope.envs)merged.env={...merged.env,...env}}return merged}function ownerScopeOf(chain){for(let i=chain.length-1;i>0;i--){if(chain[i].configured)return chain[i]}return chain[0]}function serverKey(config){const env=Object.fromEntries(Object.entries(config.env??{}).sort(([a],[b])=>a.localeCompare(b)));return JSON.stringify({server:config.server,baseUrl:config.baseUrl,project:config.project,port:config.port,entryPath:config.entryPath,startupTimeout:config.startupTimeout,logLevel:config.logLevel,auth:config.auth,env})}function serverEnv(config){const extra={};if(config.logLevel)extra["FRONTMCP_LOG_LEVEL"]=config.logLevel;if(config.auth?.mode)extra["FRONTMCP_TEST_AUTH_MODE"]=config.auth.mode;if(config.auth?.type)extra["FRONTMCP_TEST_AUTH_TYPE"]=config.auth.type;if(Object.keys(extra).length===0&&!config.env)return void 0;return{...extra,...config.env}}async function startServerEntry(config,owner){let server;let startedByUs=false;if(config.baseUrl&&!config.server){server=TestServer.connect(config.baseUrl)}else if(config.server){const serverCommand=resolveServerCommand(config.server);const isDebug=config.logLevel==="debug"||process.env["DEBUG"]==="1"||process.env["DEBUG_SERVER"]==="1";if(isDebug){console.log(`[TestFixture] Starting server: ${serverCommand}`)}try{server=await TestServer.start({project:config.project,port:config.port,command:serverCommand,env:serverEnv(config),startupTimeout:config.startupTimeout??3e4,debug:isDebug});startedByUs=true;if(isDebug){console.log(`[TestFixture] Server started at ${server.info.baseUrl}`)}}catch(error){const errMsg=error instanceof Error?error.message:String(error);throw new Error(`Failed to start test server.
30
30
 
31
31
  Server entry: ${config.server}
32
32
  Project: ${config.project??"default"}