← Files Sulekha EventsARCHIVED FILE
source/src/server.js
15.8 KB · Nov 30, 2026 · 07:53 UTC
import { createServer } from "node:http";
import widgetHtml, { widgetScript, widgetScriptPath } from "./widget-resource.js";
import {
registerAppResource,
registerAppTool,
RESOURCE_MIME_TYPE
} from "@modelcontextprotocol/ext-apps/server";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import { createSearchCache } from "./data/search-cache.js";
import { searchEventResults } from "./data/events.js";
import { enrichEventImages } from "./data/event-images.js";
import { resolvePlatform } from "./data/platform.js";
const stagingAssetOrigin = "https://sulainodeapp-staging-ekevbhe4f2bmdchc.eastus-01.azurewebsites.net";
const productionAssetOrigin = "https://sulainodeapp-agcbddf0b4d8dybg.eastus-01.azurewebsites.net";
const configuredDomain = process.env.WIDGET_DOMAIN;
// Older deployments used the long Azure asset hostname as the sandbox identifier.
const widgetDomain = configuredDomain === stagingAssetOrigin || configuredDomain == null
? "https://events.sulekha.com"
: configuredDomain;
if (widgetDomain && (new URL(widgetDomain).origin !== widgetDomain || !widgetDomain.startsWith("https://"))) {
throw new Error("WIDGET_DOMAIN must be an HTTPS origin without a trailing slash or path.");
}
// Assets are served by this MCP server; the sandbox origin may differ.
const widgetAssetOrigin = process.env.WIDGET_ASSET_ORIGIN || (widgetDomain === "https://events.sulekha.com" ? productionAssetOrigin : widgetDomain);
if (!widgetAssetOrigin || new URL(widgetAssetOrigin).origin !== widgetAssetOrigin || !widgetAssetOrigin.startsWith("https://")) {
throw new Error("WIDGET_ASSET_ORIGIN must be the public HTTPS origin serving this MCP server.");
}
// Deliver startup code with the resource: no asset fetch or cross-slot dependency.
// Escape HTML end tags so script source cannot terminate the script element.
const renderedWidgetHtml = widgetHtml.replace("__WIDGET_SCRIPT__", () => widgetScript.replace(/<\/script/gi, "<\\/script"));
const resourceDomains = ["https://usimg.sulekha.io", widgetAssetOrigin];
const WIDGET_URI = "ui://sulekha/events-v20.html";
const eventSchema = z.object({
id: z.string(),
title: z.string(),
city: z.string(),
region: z.string(),
dateTime: z.string(),
startsAt: z.string().optional(),
imageUrl: z.string().url().optional(),
price: z.string().optional(),
startPrice: z.string().optional(),
soldOut: z.boolean().optional(),
status: z.string().optional(),
organizer: z.string().optional(),
url: z.string().url().optional(),
latitude: z.number().optional(),
longitude: z.number().optional()
});
function eventResult(items, message, locationFallback = false, related = []) {
const lines = items.map(event => [
event.title, event.dateTime || event.startsAt, [event.city, event.region].filter(Boolean).join(", "),
event.price, event.soldOut ? "Sold out" : event.status, event.organizer ? `Organized by ${event.organizer}` : undefined, event.url
].filter(Boolean).join(" · "));
return {
content: [{ type: "text", text: [message, ...lines, ...(related.length ? ["Related artists, tours and venues (profiles, not scheduled events):", ...related.map(item => `${item.kind}: ${item.title} · ${item.url}`)] : [])].join("\n") }],
structuredContent: { events: items, count: items.length, locationFallback, message, related }
};
}
const cachedSearch = createSearchCache(async (args, options) => {
const result = await searchEventResults(args, options);
return { ...result, events: await enrichEventImages(result.events) };
});
function createSulekhaServer() {
const server = new McpServer(
{ name: "sulekha-apps", version: "0.4.6" },
{
instructions:
"Use only search_sulekha_events for event discovery. The widget displays search results and lets users open, copy, or share each event's public URL. Do not offer ticketing, booking, checkout, entity detail, or payment tools."
}
);
// Existing conversations can retain an earlier outputTemplate URI.
// Keep previously advertised addresses available across deployments.
for (const uri of [WIDGET_URI, "ui://sulekha/events-v19.html", "ui://sulekha/events-v18.html", "ui://sulekha/events-v17.html", "ui://sulekha/events-v16.html", "ui://sulekha/events-v15.html", "ui://sulekha/events-v14.html", "ui://sulekha/events-v13.html", "ui://sulekha/events-v12.html", "ui://sulekha/events-v11.html", "ui://sulekha/events-v10.html"]) {
registerAppResource(server, `sulekha-events-${uri === WIDGET_URI ? "current" : uri.split("/").pop()}`, uri, {}, async () => ({
contents: [
{
uri,
mimeType: RESOURCE_MIME_TYPE,
text: renderedWidgetHtml,
_meta: {
...(widgetDomain ? { "openai/widgetDomain": widgetDomain } : {}),
"openai/widgetDescription": "Sulekha event search results with public event links.",
"openai/widgetCSP": { connect_domains: [], resource_domains: resourceDomains, redirect_domains: ["https://events.sulekha.com"] },
ui: {
prefersBorder: false,
csp: {
connectDomains: [],
resourceDomains
}
}
}
}
]
}));
}
registerAppTool(
server,
"search_sulekha_events",
{
title: "Search Sulekha events",
description:
"Find events in the United States and Canada. Supply only event search keywords and the location needed for this search. Do not send entire messages, conversation history, contact information or unrelated personal details. Derive query from the user's requested artist, event title, genre, language, organizer, venue, or other meaningful event keywords. Preserve their wording, including multiword names and non-English text; do not invent, broaden, translate, or add an artist/category. Keep location and request words (show/find/get) out of query, but do not remove words that are part of a proper event title. For location-only requests use query=''. Use earlier preferences only when the user clearly refers to them (e.g. 'same artist in Toronto'); a fresh 'show me events in PA' has no artist filter. Examples: 'show events in PA' -> query='', country='US', stateCode='PA'; 'Tamil music events in Toronto' -> query='Tamil music', country='CA', cityUrl='toronto-on' with Toronto coordinates; 'Sonu Nigam in NJ' -> query='Sonu Nigam', country='US', stateCode='NJ'. country='CA' means Canada, while stateCode='CA' with country='US' means California. Resolve bare CA from clear context; otherwise ask California or Canada instead of guessing. Use stateCode for US states or Canadian provinces/territories (ON, BC, etc.), and cityUrl plus coordinates for cities. For state/province searches leave cityUrl empty and supply coordinates and a radius covering the requested area, up to 500 miles; never claim complete coverage for larger areas. Never substitute a single city for a country. Ask for a city/province/state when needed to scope a broad search. Do not silently discard unsupported date, price, or other preferences: verify them against results or explain the limitation. Never present artist suggestions as events. When keyword searches have no local matches, the server automatically retries without location filters and labels results from other locations. Do not ask permission to broaden those searches. Results come from the configured Sulekha events API.",
inputSchema: {
query: z.string().trim().max(160).default("").describe("User-chosen event keywords only; preserve names, language, and meaningful qualifiers. Empty for location-only requests. Exclude request phrasing and location, except words belonging to a proper title. Never invent an artist or genre."),
cityUrl: z.string().trim().max(100).default("").describe("Sulekha city slug, such as frisco-tx or new-york-ny. Use new-york-ny only for New York City, not New York state."),
stateCode: z.string().trim().regex(/^[A-Za-z]{2}$/).optional().describe("Strict US state or Canadian province/territory code, e.g. PA/NJ/CA for US or ON/BC/QC for Canada. Must match country."),
country: z.enum(["US", "CA"]).default("US").describe("US = United States; CA = Canada (not California). Infer from the requested location; clarify ambiguous CA."),
latitude: z.number().min(-90).max(90).optional(),
longitude: z.number().min(-180).max(180).optional(),
distance: z.number().int().min(1).max(500).default(50).describe("Search radius in miles."),
limit: z.number().int().min(1).max(20).default(10)
},
outputSchema: {
events: z.array(eventSchema),
count: z.number().int(),
locationFallback: z.boolean(),
message: z.string(),
related: z.array(z.object({
id: z.string(), kind: z.enum(["artist", "tour", "venue"]), title: z.string(),
imageUrl: z.string().url().optional(), url: z.string().url(),
eventCount: z.number().int().nonnegative().optional()
}))
},
_meta: {
ui: { resourceUri: WIDGET_URI },
"openai/outputTemplate": WIDGET_URI,
securitySchemes: [{ type: "noauth" }],
"openai/toolInvocation/invoking": "Searching Sulekha events…",
"openai/toolInvocation/invoked": "Sulekha events ready."
},
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true, idempotentHint: true }
},
async (args, extra) => {
try {
const options = {
platform: resolvePlatform(server.server.getClientVersion()?.name
?? extra?._meta?.["io.modelcontextprotocol/clientInfo"]?.name)
};
// Drop legacy full-message input even if an older client still supplies it.
const { rawQuery: _unusedRawQuery, ...searchArgs } = args ?? {};
let searchResult = await cachedSearch(searchArgs, options);
let results = searchResult.events;
const locationFallback = results.length === 0 && Boolean(args.query?.trim())
&& Boolean(args.cityUrl || args.stateCode || args.latitude !== undefined || args.longitude !== undefined);
if (locationFallback) {
// Do not forward rawQuery: it can reintroduce the original location.
searchResult = await cachedSearch({ query: args.query, limit: args.limit, omitLocation: true }, options);
results = searchResult.events;
}
const message = locationFallback
? results.length
? `No matching events found in this location. Showing ${results.length} matching event${results.length === 1 ? "" : "s"} in other locations.`
: "No matching events found in this location or in the search without location filters."
: results.length
? `Found ${results.length} matching Sulekha event${results.length === 1 ? "" : "s"}.`
: "No matching Sulekha events were found.";
return eventResult(results, message, locationFallback, searchResult.related);
} catch (error) {
console.error("Sulekha Events search failed", error);
const message = error.code === "SEARCH_INVALID_LOCATION"
? error.message
: error.code === "SEARCH_AUTH_NOT_CONFIGURED"
? "Sulekha search is not configured on the host. Set SearchApiAuth__ClientId and SearchApiAuth__Secret in the Azure application settings, then restart the app."
: error.code === "SEARCH_AUTH_REJECTED"
? "The Sulekha API rejected the host's authentication. Check the host credentials, request signing, and clock synchronization."
: "The Sulekha events search is temporarily unavailable.";
return {
isError: true,
content: [{ type: "text", text: message }]
};
}
}
);
return server;
}
// Azure App Service custom containers commonly provide WEBSITES_PORT instead
// of PORT. Prefer the platform-provided value so the health probe reaches the
// Node process rather than Azure's default 404 handler.
const endpoint = process.env.PORT ?? process.env.WEBSITES_PORT ?? "8787";
const port = /^\d+$/.test(endpoint) ? Number(endpoint) : endpoint;
// App Service routes external traffic to the container's network interface.
// Listen on all interfaces by default; HOST can still override this locally.
const host = process.env.HOST ?? "0.0.0.0";
const mcpPath = "/mcp";
// Accept both URL forms so clients can use the endpoint as a folder-style route.
const mcpPaths = new Set(["/", mcpPath, `${mcpPath}/`]);
const httpServer = createServer(async (req, res) => {
if (!req.url) {
res.writeHead(400).end("Missing URL");
return;
}
const url = new URL(req.url, "http://localhost");
if (["GET", "HEAD"].includes(req.method) && url.pathname === "/.well-known/openai-apps-challenge") {
const token = process.env.OPENAI_APPS_CHALLENGE_TOKEN;
if (!token) { res.writeHead(404).end("Not Found"); return; }
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
res.end(req.method === "HEAD" ? undefined : token);
return;
}
if (["GET", "HEAD"].includes(req.method) && url.pathname === widgetScriptPath) {
res.writeHead(200, {
"Content-Type": "text/javascript; charset=utf-8",
"Cache-Control": "public, max-age=31536000, immutable",
"Access-Control-Allow-Origin": "*",
"X-Content-Type-Options": "nosniff"
});
res.end(req.method === "HEAD" ? undefined : widgetScript);
return;
}
if (req.method === "OPTIONS" && mcpPaths.has(url.pathname)) {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "content-type, mcp-session-id, mcp-protocol-version",
"Access-Control-Expose-Headers": "Mcp-Session-Id"
});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/") {
res.writeHead(200, { "content-type": "application/json" }).end(
JSON.stringify({ name: "sulekha-apps-sdk", status: "ok", mcp: mcpPath })
);
return;
}
if (req.method === "GET" && url.pathname === "/health") {
res.writeHead(200, { "content-type": "application/json" }).end(
JSON.stringify({ status: "ok", version: "0.4.6", build: "apps-sdk-widget-11" })
);
return;
}
const mcpMethods = new Set(["POST", "GET", "DELETE"]);
if (mcpPaths.has(url.pathname) && req.method && mcpMethods.has(req.method)) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
const server = createSulekhaServer();
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true
});
res.on("close", () => {
transport.close();
server.close();
});
try {
await server.connect(transport);
await transport.handleRequest(req, res);
} catch (error) {
console.error("Failed to handle MCP request", error);
if (!res.headersSent) res.writeHead(500).end("Internal server error");
}
return;
}
res.writeHead(404).end("Not Found");
});
httpServer.on("error", (error) => {
if (error.code === "EADDRINUSE") {
console.error(
`Cannot start Sulekha: ${host}:${port} is already in use.\n` +
`If Sulekha is already running, connect to http://${host}:${port}${mcpPath}.\n` +
"Otherwise stop the existing process (Ctrl+C in its terminal), then run npm start again.\n" +
"To run a second instance, use PORT=8788 npm start and connect to that port."
);
} else {
console.error(`Cannot start Sulekha on ${host}:${port}: ${error.message}`);
}
process.exitCode = 1;
});
const listenOptions = typeof port === "number" ? { port, host } : { path: port };
httpServer.listen(listenOptions, () => {
const address = httpServer.address();
console.log(`Sulekha Apps SDK server listening on ${typeof address === "string" ? address : `http://${host}:${address.port}${mcpPath}`}`);
});
SHA-256: 9dbebc7529158e240d0a9882969f21129864c67442b086b4975c72db11032665