← Files Sulekha EventsARCHIVED FILE

source/test/server.test.js

8.83 KB · Nov 30, 2026 · 07:53 UTC

↓ Download file

import test from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createHmac } from 'node:crypto';
import { createServer } from 'node:http';
import { once } from 'node:events';
import { tmpdir } from 'node:os';
import { mkdtemp, cp, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { Script } from 'node:vm';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

for (const entry of ['server.js', 'isolated-deployment']) {
test(`${entry}: IIS require startup, health, MCP search and widget work from another directory`, { timeout: 15000 }, async (t) => {
  const upstreamRequests = [];
  const api = createServer((req, res) => {
    const payload = [req.headers['x-timestamp'], req.headers['x-nonce'], req.method, req.url].join('\n');
    const expected = createHmac('sha256', 'test-secret').update(payload).digest('hex');
    if (req.headers['x-client-id'] !== 'test-client' || req.headers['x-signature'] !== expected) {
      res.writeHead(401).end(); return;
    }
    upstreamRequests.push(new URL(req.url, 'http://localhost'));
    const query = upstreamRequests.at(-1).searchParams.get('searchtxt');
    if (query === 'failure') { res.writeHead(503).end(); return; }
    if (query === 'empty') { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify([])); return; }
    res.setHeader('content-type', 'application/json');
    res.end(JSON.stringify([{ search: 'event', contentid: 123, title: 'Test Concert', cityname: 'New York', statecode: 'NY', trackurl: 'https://events.sulekha.com/event_123' }]));
  });
  api.listen(0, '127.0.0.1');
  await once(api, 'listening');
  t.after(() => api.close());
  let entryPath = fileURLToPath(new URL('../server.js', import.meta.url));
  if (entry === 'isolated-deployment') {
    const isolated = await mkdtemp(join(tmpdir(), 'sulekha-deploy-'));
    t.after(() => rm(isolated, { recursive: true, force: true }));
    await cp(new URL('../deploy/', import.meta.url), isolated, { recursive: true });
    entryPath = join(isolated, 'server.js');
  }
  const child = spawn(process.execPath, ['-e', `require(${JSON.stringify(entryPath)})`], {
    cwd: tmpdir(), env: { ...process.env, SearchApiAuth__ClientId: 'test-client', SearchApiAuth__Secret: 'test-secret', WIDGET_DOMAIN: 'https://events.sulekha.com', WIDGET_ASSET_ORIGIN: 'https://sulainodeapp-agcbddf0b4d8dybg.eastus-01.azurewebsites.net', SULEKHA_PLATFORM: 'appsSDK', OPENAI_APPS_CHALLENGE_TOKEN: 'test-domain-token', NODE_ENV: 'production', PORT: '0', HOST: '127.0.0.1', SULEKHA_EVENTS_WEB_BASE_URL: `http://127.0.0.1:${api.address().port}`, SULEKHA_EVENTS_WEB_SEARCH_PATH: 'search' },
    stdio: ['ignore', 'pipe', 'pipe']
  });
  t.after(() => child.kill());
  const endpoint = await new Promise((resolve, reject) => {
    let output = '';
    child.stdout.on('data', data => { output += data; const match = output.match(/http:\/\/127\.0\.0\.1:\d+\/mcp/); if (match) resolve(match[0]); });
    child.stderr.on('data', data => { output += data; });
    child.on('error', reject);
    child.on('exit', code => reject(new Error(`Server exited ${code}: ${output}`)));
  });
  const health = await (await fetch(new URL('/health', endpoint))).json();
  assert.equal(health.status, 'ok');
  assert.equal(health.version, '0.4.6');
  assert.equal(health.build, 'apps-sdk-widget-11');
  const challengeUrl = new URL('/.well-known/openai-apps-challenge', endpoint);
  assert.equal(await (await fetch(challengeUrl)).text(), 'test-domain-token');
  assert.equal(await (await fetch(challengeUrl, { method: 'HEAD' })).text(), '');
  const client = new Client({ name: 'integration-test', version: '1.0.0' });
  t.after(() => client.close());
  await client.connect(new StreamableHTTPClientTransport(new URL(endpoint)));
  const { tools } = await client.listTools();
  assert.deepEqual(tools.map(tool => tool.name), ['search_sulekha_events']);
  const result = await client.callTool({ name: 'search_sulekha_events', arguments: { query: 'Concert' } });
  assert.equal(result.isError, undefined);
  assert.equal(upstreamRequests.at(-1).searchParams.get('platform'), 'appsSDK');
  assert.equal(result.structuredContent.events[0].title, 'Test Concert');
  assert.match(result.content[0].text, /Test Concert.*New York, NY.*https:\/\/events\.sulekha\.com\/event_123/);
  assert.ok(tools[0].inputSchema.properties.stateCode);
  const rawQuery = '  Show me Concert events in NY?!\nPlease  ';
  await client.callTool({ name: 'search_sulekha_events', arguments: { query: 'Concert', rawQuery } });
  assert.equal(tools[0].inputSchema.properties.rawQuery, undefined);
  assert.equal(upstreamRequests.at(-1).searchParams.has('rawQuery'), false);
  assert.equal(upstreamRequests.at(-1).searchParams.get('searchtxt'), 'Concert');

  const callsBefore = upstreamRequests.length;
  const duplicateArgs = { query: 'duplicate check', rawQuery: 'duplicate check in NY' };
  const duplicateResults = await Promise.all([1, 2].map(() => client.callTool({ name: 'search_sulekha_events', arguments: duplicateArgs })));
  assert.equal(upstreamRequests.length - callsBefore, 1);
  assert.deepEqual(duplicateResults[0].structuredContent, duplicateResults[1].structuredContent);
  const invalid = await client.callTool({ name: 'search_sulekha_events', arguments: { latitude: 100 } });
  assert.equal(invalid.isError, true);

  const inState = await client.callTool({ name: 'search_sulekha_events', arguments: { stateCode: 'NY' } });
  assert.equal(inState.structuredContent.count, 1);
  const outOfState = await client.callTool({ name: 'search_sulekha_events', arguments: { stateCode: 'PA' } });
  assert.equal(outOfState.structuredContent.count, 0);
  const beforeFallback = upstreamRequests.length;
  const fallback = await client.callTool({ name: 'search_sulekha_events', arguments: {
    query: 'tour artist', rawQuery: 'tour artist in NJ', stateCode: 'NJ', cityUrl: 'edison-nj', latitude: 40.5187, longitude: -74.4121
  } });
  assert.equal(upstreamRequests.length - beforeFallback, 2);
  assert.equal(fallback.structuredContent.locationFallback, true);
  assert.equal(fallback.structuredContent.events[0].region, 'NY');
  assert.match(fallback.structuredContent.message, /other locations/);
  const broadParams = upstreamRequests.at(-1).searchParams;
  assert.equal(broadParams.get('searchtxt'), 'tour artist');
  for (const key of ['lat', 'long', 'perflat', 'perflong', 'radius', 'cityurl', 'passingcityurl', 'rawQuery']) {
    assert.equal(broadParams.has(key), false, key);
  }
  const noMatches = await client.callTool({ name: 'search_sulekha_events', arguments: { query: 'empty', stateCode: 'NJ' } });
  assert.equal(noMatches.structuredContent.count, 0);
  assert.equal(noMatches.structuredContent.locationFallback, true);
  const { resources } = await client.listResources();
  const widget = await client.readResource({ uri: resources[0].uri });
  assert.match(widget.contents[0].text, /<!doctype html>/i);
  const html = widget.contents[0].text;
  assert.doesNotMatch(html, /<script[^>]*\bsrc=/i);
  assert.doesNotMatch(html, /__WIDGET_SCRIPT/);
  const embeddedScript = html.match(/<script>([\s\S]*?)<\/script>/i)?.[1];
  assert.ok(embeddedScript, 'Widget must start without any external download');
  new Script(embeddedScript);
  assert.equal(embeddedScript, readFileSync(new URL('../public/events-widget.js', import.meta.url), 'utf8').replace(/<\/script/gi, '<\\/script'));
  const cachedWidget = await client.readResource({ uri: 'ui://sulekha/events-v19.html' });
  assert.equal(cachedWidget.contents[0].text, html);
  const previousWidget = await client.readResource({ uri: 'ui://sulekha/events-v12.html' });
  assert.equal(previousWidget.contents[0].text, html);
  const legacyWidget = await client.readResource({ uri: 'ui://sulekha/events-v10.html' });
  assert.equal(legacyWidget.contents[0].uri, 'ui://sulekha/events-v10.html');
  assert.equal(legacyWidget.contents[0].text, widget.contents[0].text);
  assert.equal(legacyWidget.contents[0].mimeType, 'text/html;profile=mcp-app');
  assert.equal(tools[0]._meta['openai/outputTemplate'], tools[0]._meta.ui.resourceUri);
  await client.readResource({ uri: tools[0]._meta.ui.resourceUri });
  assert.equal(widget.contents[0]._meta.ui.domain, undefined);
  assert.equal(widget.contents[0]._meta['openai/widgetDomain'], 'https://events.sulekha.com');
  assert.doesNotMatch(widget.contents[0].text, /save_sulekha_shopping_cart|sulekhaBuyer|renderBooking/);
  assert.equal(tools[0].annotations.readOnlyHint, true);
  const empty = await client.callTool({ name: 'search_sulekha_events', arguments: { query: 'empty' } });
  assert.equal(empty.structuredContent.count, 0);
  const failure = await client.callTool({ name: 'search_sulekha_events', arguments: { query: 'failure' } });
  assert.equal(failure.isError, true);
});
}

SHA-256: e3940971a0253d71353be51e3fdf99cce10eb2c6ff8e02df30bb2854e2eb132f