@superinterface/server 1.0.39 → 1.0.41
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/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +2 -2
- package/.next/cache/.tsbuildinfo +1 -1
- package/.next/cache/eslint/.cache_btwyo7 +1 -1
- package/.next/fallback-build-manifest.json +2 -2
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +1 -1
- package/.next/server/chunks/[root-of-the-server]__441cee00._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__441cee00._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__eb816e13._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__eb816e13._.js.map +1 -1
- package/.next/server/chunks/supercorp_superinterface_bebd2c96._.js +1 -1
- package/.next/server/chunks/supercorp_superinterface_bebd2c96._.js.map +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/trace +1 -1
- package/dist/app/api/assistants/[assistantId]/mcp-servers/[mcpServerId]/buildRoute.d.ts +6 -0
- package/dist/app/api/assistants/[assistantId]/mcp-servers/[mcpServerId]/buildRoute.d.ts.map +1 -1
- package/dist/app/api/assistants/[assistantId]/mcp-servers/[mcpServerId]/buildRoute.js +2 -2
- package/dist/app/api/assistants/[assistantId]/mcp-servers/[mcpServerId]/route.d.ts +6 -0
- package/dist/app/api/assistants/[assistantId]/mcp-servers/[mcpServerId]/route.d.ts.map +1 -1
- package/dist/app/api/assistants/[assistantId]/mcp-servers/buildRoute.d.ts +4 -0
- package/dist/app/api/assistants/[assistantId]/mcp-servers/buildRoute.d.ts.map +1 -1
- package/dist/app/api/assistants/[assistantId]/mcp-servers/buildRoute.js +3 -3
- package/dist/app/api/assistants/[assistantId]/mcp-servers/route.d.ts +4 -0
- package/dist/app/api/assistants/[assistantId]/mcp-servers/route.d.ts.map +1 -1
- package/dist/lib/mcpServers/mcpServerSchema.d.ts +48 -32
- package/dist/lib/mcpServers/mcpServerSchema.d.ts.map +1 -1
- package/dist/lib/mcpServers/mcpServerSchema.js +11 -0
- package/dist/lib/mcpServers/serializeApiMcpServer.d.ts +2 -0
- package/dist/lib/mcpServers/serializeApiMcpServer.d.ts.map +1 -1
- package/dist/lib/mcpServers/serializeApiMcpServer.js +2 -0
- package/dist/lib/tools/tools/index.d.ts.map +1 -1
- package/dist/lib/tools/tools/index.js +10 -9
- package/package.json +1 -1
- package/prisma/McpServer.prisma +2 -0
- package/prisma/migrations/20251016001510_add_mcp_server_name_description/migration.sql +3 -0
- /package/.next/static/{KSqaVkql-hTCPJn2akzn5 → 3oLvS6zqEM3JjzXyiTqF1}/_buildManifest.js +0 -0
- /package/.next/static/{KSqaVkql-hTCPJn2akzn5 → 3oLvS6zqEM3JjzXyiTqF1}/_clientMiddlewareManifest.json +0 -0
- /package/.next/static/{KSqaVkql-hTCPJn2akzn5 → 3oLvS6zqEM3JjzXyiTqF1}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/getApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/misc/isJSON.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/mcpServers/serializeApiMcpServer.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/mcpServers/mcpServerSchema.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n}\n","import { ApiKeyType, ApiKey, type PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getApiKey = async ({\n authorization,\n type,\n prisma,\n}: {\n authorization: string | null\n type: ApiKeyType\n prisma: PrismaClient\n}): Promise<ApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, apiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(apiKeyValue)) {\n return null\n }\n\n return prisma.apiKey.findFirst({\n where: { type, value: apiKeyValue },\n })\n}\n","export const isJSON = (value: string) => {\n try {\n JSON.parse(value)\n return true\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n return false\n }\n}\n","import type { Prisma, SseTransport, HttpTransport } from '@prisma/client'\n\nconst serializeApiSseTransport = ({\n sseTransport,\n}: {\n sseTransport: SseTransport\n}) => ({\n id: sseTransport.id,\n url: sseTransport.url,\n headers: sseTransport.headers,\n createdAt: sseTransport.createdAt.toISOString(),\n updatedAt: sseTransport.updatedAt.toISOString(),\n})\n\nconst serializeApiHttpTransport = ({\n httpTransport,\n}: {\n httpTransport: HttpTransport\n}) => ({\n id: httpTransport.id,\n url: httpTransport.url,\n headers: httpTransport.headers,\n createdAt: httpTransport.createdAt.toISOString(),\n updatedAt: httpTransport.updatedAt.toISOString(),\n})\n\nexport const serializeApiMcpServer = ({\n mcpServer,\n}: {\n mcpServer: Prisma.McpServerGetPayload<{\n include: {\n sseTransport: true\n httpTransport: true\n }\n }>\n}) => ({\n id: mcpServer.id,\n transportType: mcpServer.transportType,\n sseTransport: mcpServer.sseTransport\n ? serializeApiSseTransport({\n sseTransport: mcpServer.sseTransport,\n })\n : null,\n httpTransport: mcpServer.httpTransport\n ? serializeApiHttpTransport({\n httpTransport: mcpServer.httpTransport,\n })\n : null,\n createdAt: mcpServer.createdAt.toISOString(),\n updatedAt: mcpServer.updatedAt.toISOString(),\n})\n","import { z } from 'zod'\nimport { TransportType } from '@prisma/client'\nimport { isJSON } from '@/lib/misc/isJSON'\n\nconst stdioTransportSchema = z.object({\n command: z.string().min(1),\n args: z.string().min(1),\n})\n\nconst sseTransportSchema = z.object({\n url: z.string().min(1).url(),\n headers: z.string().min(1).refine(isJSON, {\n message: 'Must be a valid JSON string.',\n }),\n})\n\nconst httpTransportSchema = z.object({\n url: z.string().min(1).url(),\n headers: z.string().min(1).refine(isJSON, {\n message: 'Must be a valid JSON string.',\n }),\n})\n\nexport const baseSchema = z.object({\n transportType: z\n .nativeEnum(TransportType)\n .refine((t) => t !== TransportType.STDIO, {\n message: `transportType cannot be ${TransportType.STDIO}`,\n }),\n sseTransport: sseTransportSchema.nullable().optional(),\n httpTransport: httpTransportSchema.nullable().optional(),\n})\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const superRefine = (values: any, ctx: any) => {\n if (values.transportType === TransportType.STDIO) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Transport type ${TransportType.STDIO} is not allowed.`,\n })\n\n const result = stdioTransportSchema.safeParse(values.stdioTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['stdioTransport', ...issue.path],\n }),\n )\n } else if (values.transportType === TransportType.SSE) {\n const result = sseTransportSchema.safeParse(values.sseTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['sseTransport', ...issue.path],\n }),\n )\n } else if (values.transportType === TransportType.HTTP) {\n const result = httpTransportSchema.safeParse(values.httpTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['httpTransport', ...issue.path],\n }),\n )\n }\n}\n\nexport const mcpServerSchema = baseSchema.superRefine(superRefine)\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/assistants/[assistantId]/mcp-servers/route\",\n pathname: \"/api/assistants/[assistantId]/mcp-servers\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/assistants/[assistantId]/mcp-servers/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import { prisma } from '@/lib/prisma'\nimport { buildGET, buildOPTIONS, buildPOST } from './buildRoute'\n\nexport const GET = buildGET({ prisma })\n\nexport const POST = buildPOST({ prisma })\n\nexport const OPTIONS = buildOPTIONS()\n","import { type NextRequest, NextResponse } from 'next/server'\nimport { ApiKeyType, TransportType, type PrismaClient } from '@prisma/client'\nimport { headers } from 'next/headers'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { getApiKey } from '@/lib/apiKeys/getApiKey'\nimport { serializeApiMcpServer } from '@/lib/mcpServers/serializeApiMcpServer'\nimport { mcpServerSchema } from '@/lib/mcpServers/mcpServerSchema'\n\ntype RouteProps = {\n params: Promise<{ assistantId: string }>\n}\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (_request: NextRequest, props: RouteProps) => {\n const { assistantId } = await props.params\n\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const assistant = await prisma.assistant.findFirst({\n where: {\n id: assistantId,\n workspaceId: privateApiKey.workspaceId,\n },\n include: {\n mcpServers: {\n include: {\n stdioTransport: true,\n sseTransport: true,\n httpTransport: true,\n },\n orderBy: {\n createdAt: 'desc',\n },\n },\n },\n })\n\n if (!assistant) {\n return NextResponse.json({ error: 'No assistant found' }, { status: 400 })\n }\n\n return NextResponse.json(\n {\n mcpServers: assistant.mcpServers.map((mcpServer) =>\n serializeApiMcpServer({\n mcpServer,\n }),\n ),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (request: NextRequest, props: RouteProps) => {\n const { assistantId } = await props.params\n\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n authorization,\n type: ApiKeyType.PRIVATE,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const body = await request.json()\n const parsed = mcpServerSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n\n const { transportType, sseTransport, httpTransport } = parsed.data\n\n const workspaceId = privateApiKey.workspaceId\n\n const assistant = await prisma.assistant.findFirst({\n where: { id: assistantId, workspaceId },\n })\n\n if (!assistant) {\n return NextResponse.json({ error: 'No assistant found' }, { status: 400 })\n }\n\n const mcpServer = await prisma.mcpServer.create({\n data: {\n transportType,\n ...(transportType === TransportType.SSE\n ? {\n sseTransport: {\n create: {\n url: sseTransport!.url,\n headers: JSON.parse(sseTransport!.headers),\n },\n },\n }\n : {}),\n ...(transportType === TransportType.HTTP\n ? {\n httpTransport: {\n create: {\n url: httpTransport!.url,\n headers: JSON.parse(httpTransport!.headers),\n },\n },\n }\n : {}),\n assistant: {\n connect: {\n id: assistantId,\n workspaceId,\n },\n },\n },\n include: {\n stdioTransport: true,\n sseTransport: true,\n httpTransport: true,\n },\n })\n\n return NextResponse.json(\n {\n mcpServer: serializeApiMcpServer({ mcpServer }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.json(\n {},\n {\n headers: cacheHeaders,\n },\n )\n"],"names":[],"mappings":"6jCAAO,IAAM,EAAe,CAC1B,8BAA+B,IAC/B,+BAAgC,kCAChC,+BAAgC,cAClC,mDCHA,IAAA,EAAA,EAAA,CAAA,CAAA,OAEO,IAAM,EAAY,MAAO,eAC9B,CAAa,MACb,CAAI,QACJ,CAAM,CAKP,IACC,GAAI,CAAC,EACH,OAAO,KAGT,CAJoB,EAId,EAAG,EAAY,CAAG,EAAc,KAAK,CAAC,iBAEvC,AAAL,CAAK,EAAA,CAAD,CAAC,QAAA,AAAQ,EAAC,GAIP,EAAO,MAAM,CAAC,EAJO,OAIE,CAAC,CAC7B,MAAO,MAAE,EAAM,MAAO,CAAY,CACpC,GALS,IAMX,gDCzBO,IAAM,EAAS,AAAC,IACrB,GAAI,CAEF,OADA,KAAK,KAAK,CAAC,IACJ,CAET,CAAE,MAAO,EAAG,CACV,OAAO,CACT,CACF,0ECkBO,IAAM,EAAwB,CAAC,WACpC,CAAS,CAQV,GAAK,CAAC,CACL,GAAI,EAAU,EAAE,CAChB,cAAe,EAAU,aAAa,CACtC,aAAc,EAAU,YAAY,CAChC,CArC2B,CAAC,cAChC,CAAY,CAGb,GAAK,CAAC,CACL,GAAI,EAAa,EAAE,CACnB,IAAK,EAAa,GAAG,CACrB,QAAS,EAAa,OAAO,CAC7B,UAAW,EAAa,SAAS,CAAC,WAAW,GAC7C,UAAW,EAAa,SAAS,CAAC,WAAW,GAC/C,CAAC,EA2B8B,CACvB,aAAc,EAAU,YAAY,AACtC,GACA,KACJ,cAAe,EAAU,aAAa,CAClC,CA9B4B,CAAC,eACjC,CA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AAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,GAEf,CAAE,MAAO,EAAK,CAcV,GAbI,AAAE,CAAD,YAAgB,EAAA,eAAe,EAChC,CADmC,KAC7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,cAClC,uBACA,CACJ,EACJ,GAIA,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,EAEA,qCAAqC","ignoreList":[5]}
|
|
1
|
+
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/getApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/misc/isJSON.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/mcpServers/serializeApiMcpServer.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/mcpServers/mcpServerSchema.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n}\n","import { ApiKeyType, ApiKey, type PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getApiKey = async ({\n authorization,\n type,\n prisma,\n}: {\n authorization: string | null\n type: ApiKeyType\n prisma: PrismaClient\n}): Promise<ApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, apiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(apiKeyValue)) {\n return null\n }\n\n return prisma.apiKey.findFirst({\n where: { type, value: apiKeyValue },\n })\n}\n","export const isJSON = (value: string) => {\n try {\n JSON.parse(value)\n return true\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n return false\n }\n}\n","import type { Prisma, SseTransport, HttpTransport } from '@prisma/client'\n\nconst serializeApiSseTransport = ({\n sseTransport,\n}: {\n sseTransport: SseTransport\n}) => ({\n id: sseTransport.id,\n url: sseTransport.url,\n headers: sseTransport.headers,\n createdAt: sseTransport.createdAt.toISOString(),\n updatedAt: sseTransport.updatedAt.toISOString(),\n})\n\nconst serializeApiHttpTransport = ({\n httpTransport,\n}: {\n httpTransport: HttpTransport\n}) => ({\n id: httpTransport.id,\n url: httpTransport.url,\n headers: httpTransport.headers,\n createdAt: httpTransport.createdAt.toISOString(),\n updatedAt: httpTransport.updatedAt.toISOString(),\n})\n\nexport const serializeApiMcpServer = ({\n mcpServer,\n}: {\n mcpServer: Prisma.McpServerGetPayload<{\n include: {\n sseTransport: true\n httpTransport: true\n }\n }>\n}) => ({\n id: mcpServer.id,\n name: mcpServer.name,\n description: mcpServer.description,\n transportType: mcpServer.transportType,\n sseTransport: mcpServer.sseTransport\n ? serializeApiSseTransport({\n sseTransport: mcpServer.sseTransport,\n })\n : null,\n httpTransport: mcpServer.httpTransport\n ? serializeApiHttpTransport({\n httpTransport: mcpServer.httpTransport,\n })\n : null,\n createdAt: mcpServer.createdAt.toISOString(),\n updatedAt: mcpServer.updatedAt.toISOString(),\n})\n","import { z } from 'zod'\nimport { TransportType } from '@prisma/client'\nimport { isJSON } from '@/lib/misc/isJSON'\n\nconst stdioTransportSchema = z.object({\n command: z.string().min(1),\n args: z.string().min(1),\n})\n\nconst sseTransportSchema = z.object({\n url: z.string().min(1).url(),\n headers: z.string().min(1).refine(isJSON, {\n message: 'Must be a valid JSON string.',\n }),\n})\n\nconst httpTransportSchema = z.object({\n url: z.string().min(1).url(),\n headers: z.string().min(1).refine(isJSON, {\n message: 'Must be a valid JSON string.',\n }),\n})\n\nconst optionalNameString = z\n .string()\n .min(1)\n .regex(/^[a-zA-Z0-9-]+$/, {\n message: 'Name can only include letters, numbers, and hyphens.',\n })\n .optional()\n .nullable()\n\nconst optionalDescriptionString = z.string().min(1).optional().nullable()\n\nexport const baseSchema = z.object({\n name: optionalNameString,\n description: optionalDescriptionString,\n transportType: z\n .nativeEnum(TransportType)\n .refine((t) => t !== TransportType.STDIO, {\n message: `transportType cannot be ${TransportType.STDIO}`,\n }),\n sseTransport: sseTransportSchema.nullable().optional(),\n httpTransport: httpTransportSchema.nullable().optional(),\n})\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const superRefine = (values: any, ctx: any) => {\n if (values.transportType === TransportType.STDIO) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Transport type ${TransportType.STDIO} is not allowed.`,\n })\n\n const result = stdioTransportSchema.safeParse(values.stdioTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['stdioTransport', ...issue.path],\n }),\n )\n } else if (values.transportType === TransportType.SSE) {\n const result = sseTransportSchema.safeParse(values.sseTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['sseTransport', ...issue.path],\n }),\n )\n } else if (values.transportType === TransportType.HTTP) {\n const result = httpTransportSchema.safeParse(values.httpTransport)\n\n if (result.success) return\n\n result.error.issues.forEach((issue) =>\n ctx.addIssue({\n ...issue,\n path: ['httpTransport', ...issue.path],\n }),\n )\n }\n}\n\nexport const mcpServerSchema = baseSchema.superRefine(superRefine)\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/assistants/[assistantId]/mcp-servers/route\",\n pathname: \"/api/assistants/[assistantId]/mcp-servers\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/assistants/[assistantId]/mcp-servers/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import { prisma } from '@/lib/prisma'\nimport { buildGET, buildOPTIONS, buildPOST } from './buildRoute'\n\nexport const GET = buildGET({ prisma })\n\nexport const POST = buildPOST({ prisma })\n\nexport const OPTIONS = buildOPTIONS()\n","import { type NextRequest, NextResponse } from 'next/server'\nimport { ApiKeyType, TransportType, type PrismaClient } from '@prisma/client'\nimport { headers } from 'next/headers'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { getApiKey } from '@/lib/apiKeys/getApiKey'\nimport { serializeApiMcpServer } from '@/lib/mcpServers/serializeApiMcpServer'\nimport { mcpServerSchema } from '@/lib/mcpServers/mcpServerSchema'\n\ntype RouteProps = {\n params: Promise<{ assistantId: string }>\n}\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (_request: NextRequest, props: RouteProps) => {\n const { assistantId } = await props.params\n\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const assistant = await prisma.assistant.findFirst({\n where: {\n id: assistantId,\n workspaceId: privateApiKey.workspaceId,\n },\n include: {\n mcpServers: {\n include: {\n stdioTransport: true,\n sseTransport: true,\n httpTransport: true,\n },\n orderBy: {\n createdAt: 'desc',\n },\n },\n },\n })\n\n if (!assistant) {\n return NextResponse.json({ error: 'No assistant found' }, { status: 400 })\n }\n\n return NextResponse.json(\n {\n mcpServers: assistant.mcpServers.map((mcpServer) =>\n serializeApiMcpServer({\n mcpServer,\n }),\n ),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (request: NextRequest, props: RouteProps) => {\n const { assistantId } = await props.params\n\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n authorization,\n type: ApiKeyType.PRIVATE,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const body = await request.json()\n const parsed = mcpServerSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n\n const { transportType, sseTransport, httpTransport, name, description } =\n parsed.data\n\n const workspaceId = privateApiKey.workspaceId\n\n const assistant = await prisma.assistant.findFirst({\n where: { id: assistantId, workspaceId },\n })\n\n if (!assistant) {\n return NextResponse.json({ error: 'No assistant found' }, { status: 400 })\n }\n\n const mcpServer = await prisma.mcpServer.create({\n data: {\n transportType,\n ...(transportType === TransportType.SSE\n ? {\n sseTransport: {\n create: {\n url: sseTransport!.url,\n headers: JSON.parse(sseTransport!.headers),\n },\n },\n }\n : {}),\n ...(transportType === TransportType.HTTP\n ? {\n httpTransport: {\n create: {\n url: httpTransport!.url,\n headers: JSON.parse(httpTransport!.headers),\n },\n },\n }\n : {}),\n ...(name !== undefined ? { name } : {}),\n ...(description !== undefined ? { description } : {}),\n assistant: {\n connect: {\n id: assistantId,\n workspaceId,\n },\n },\n },\n include: {\n stdioTransport: true,\n sseTransport: true,\n httpTransport: true,\n },\n })\n\n return NextResponse.json(\n {\n mcpServer: serializeApiMcpServer({ mcpServer }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.json(\n {},\n {\n headers: cacheHeaders,\n },\n )\n"],"names":[],"mappings":"6jCAAO,IAAM,EAAe,CAC1B,8BAA+B,IAC/B,+BAAgC,kCAChC,+BAAgC,cAClC,mDCHA,IAAA,EAAA,EAAA,CAAA,CAAA,OAEO,IAAM,EAAY,MAAO,CAC9B,eAAa,MACb,CAAI,QACJ,CAAM,CAKP,IACC,GAAI,CAAC,EACH,OAAO,KAGT,CAJoB,EAId,EAAG,EAAY,CAAG,EAAc,KAAK,CAAC,iBAEvC,AAAL,AAAK,CAAA,EAAA,CAAD,CAAC,QAAQ,AAAR,EAAS,GAIP,EAAO,MAAM,CAAC,EAJO,OAIE,CAAC,CAC7B,MAAO,MAAE,EAAM,MAAO,CAAY,CACpC,GALS,IAMX,gDCzBO,IAAM,EAAS,AAAC,IACrB,GAAI,CAEF,OADA,KAAK,KAAK,CAAC,IACJ,CAET,CAAE,MAAO,EAAG,CACV,OAAO,CACT,CACF,0ECkBO,IAAM,EAAwB,CAAC,WACpC,CAAS,CAQV,GAAK,CAAC,CACL,GAAI,EAAU,EAAE,CAChB,KAAM,EAAU,IAAI,CACpB,YAAa,EAAU,WAAW,CAClC,cAAe,EAAU,aAAa,CACtC,aAAc,EAAU,YAAY,CAChC,CAvC2B,CAAC,cAChC,CAAY,CAGb,GAAK,CAAC,CACL,GAAI,EAAa,EAAE,CACnB,IAAK,EAAa,GAAG,CACrB,QAAS,EAAa,OAAO,CAC7B,UAAW,EAAa,SAAS,CAAC,WAAW,GAC7C,UAAW,EAAa,SAAS,CAAC,WA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C,kBAAkB,AAC7F,EAAQ,GAAG,CAAC,gBAAiB,CAAA,EAAA,EAAA,qBAAA,AAAqB,EAAC,EAAW,YAAY,GAE9E,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,EAAW,KAAK,CAAC,IAAI,CAAE,SAC7E,EACA,OAAQ,EAAW,KAAK,CAAC,MAAM,EAAI,GACvC,IACO,IACX,EAGI,EACA,MAAM,EAAe,EADT,CAGZ,MAAM,EAAO,qBAAqB,CAAC,EAAI,OAAO,CAAE,IAAI,EAAO,KAAK,CAAC,EAAA,cAAc,CAAC,aAAa,CAAE,CACvF,SAAU,CAAA,EAAG,EAAO,CAAC,EAAE,EAAI,GAAG,CAAA,CAAE,CAChC,KAAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,GAEf,CAAE,MAAO,EAAK,CAcV,GAbI,AAAE,CAAD,YAAgB,EAAA,eAAe,EAChC,CADmC,KAC7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,cAClC,uBACA,CACJ,EACJ,GAIA,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,EAEA,qCAAqC","ignoreList":[5]}
|
|
@@ -2,6 +2,6 @@ module.exports=[58325,(e,r,t)=>{e.e,function(e){"use strict";function r(){for(va
|
|
|
2
2
|
`)?l.slice(0,-1):l}),n=void 0,l="",c="");if(e.startsWith(":")){o&&o(e.slice(e.startsWith(": ")?2:1));return}let t=e.indexOf(":");if(-1!==t){let r=e.slice(0,t),a=" "===e[t+1]?2:1;h(r,e.slice(t+a),e);return}h(e,"",e)}function h(e,r,o){switch(e){case"event":c=r;break;case"data":l=`${l}${r}
|
|
3
3
|
`;break;case"id":n=r.includes("\0")?void 0:r;break;case"retry":/^\d+$/.test(r)?a(parseInt(r,10)):t(new d(`Invalid \`retry\` value: "${r}"`,{type:"invalid-retry",value:r,line:o}));break;default:t(new d(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:r,line:o}))}}return{feed:function(e){let r=i?e.replace(/^\xEF\xBB\xBF/,""):e,[t,a]=function(e){let r=[],t="",a=0;for(;a<e.length;){let o=e.indexOf("\r",a),s=e.indexOf(`
|
|
4
4
|
`,a),i=-1;if(-1!==o&&-1!==s?i=Math.min(o,s):-1!==o?i=o===e.length-1?-1:o:-1!==s&&(i=s),-1===i){t=e.slice(a);break}{let t=e.slice(a,i);r.push(t),"\r"===e[(a=i+1)-1]&&e[a]===`
|
|
5
|
-
`&&a++}}return[r,t]}(`${s}${r}`);for(let e of t)u(e);s=a,i=!1},reset:function(e={}){s&&e.consume&&u(s),i=!0,n=void 0,l="",c="",s=""}}}class v extends Event{constructor(e,r){var t,a;super(e),this.code=null!=(t=null==r?void 0:r.code)?t:void 0,this.message=null!=(a=null==r?void 0:r.message)?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,t){return t(g(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(g(this),r)}}function g(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var y,_,E,P,b,w,z,S,R,T,C,O,x,I,j,A,D,$,F,k,L,U,N,q=e=>{throw TypeError(e)},M=(e,r,t)=>r.has(e)||q("Cannot "+t),H=(e,r,t)=>(M(e,r,"read from private field"),t?t.call(e):r.get(e)),V=(e,r,t)=>r.has(e)?q("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t),Q=(e,r,t,a)=>(M(e,r,"write to private field"),r.set(e,t),t),G=(e,r,t)=>(M(e,r,"access private method"),t);class B extends EventTarget{constructor(e,r){var t,a;super(),V(this,I),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,V(this,y),V(this,_),V(this,E),V(this,P),V(this,b),V(this,w),V(this,z),V(this,S,null),V(this,R),V(this,T),V(this,C,null),V(this,O,null),V(this,x,null),V(this,A,async e=>{var r;H(this,T).reset();let{body:t,redirected:a,status:o,headers:s}=e;if(204===o){G(this,I,L).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Q(this,E,new URL(e.url)):Q(this,E,void 0),200!==o)return void G(this,I,L).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void G(this,I,L).call(this,'Invalid content type, expected "text/event-stream"',o);if(H(this,y)===this.CLOSED)return;Q(this,y,this.OPEN);let i=new Event("open");if(null==(r=H(this,x))||r.call(this,i),this.dispatchEvent(i),"object"!=typeof t||!t||!("getReader"in t)){G(this,I,L).call(this,"Invalid response body, expected a web ReadableStream",o),this.close();return}let n=new TextDecoder,l=t.getReader(),c=!0;do{let{done:e,value:r}=await l.read();r&&H(this,T).feed(n.decode(r,{stream:!e})),e&&(c=!1,H(this,T).reset(),G(this,I,U).call(this))}while(c)}),V(this,D,e=>{Q(this,R,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&G(this,I,U).call(this,function e(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(e).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${e(r.cause)}`:r.message:`${r}`}(e))}),V(this,F,e=>{"string"==typeof e.id&&Q(this,S,e.id);let r=new MessageEvent(e.event||"message",{data:e.data,origin:H(this,E)?H(this,E).origin:H(this,_).origin,lastEventId:e.id||""});H(this,O)&&(!e.event||"message"===e.event)&&H(this,O).call(this,r),this.dispatchEvent(r)}),V(this,k,e=>{Q(this,w,e)}),V(this,N,()=>{Q(this,z,void 0),H(this,y)===this.CONNECTING&&G(this,I,j).call(this)});try{if(e instanceof URL)Q(this,_,e);else if("string"==typeof e)Q(this,_,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let r=globalThis.DOMException;return"function"==typeof r?new r(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}Q(this,T,f({onEvent:H(this,F),onRetry:H(this,k)})),Q(this,y,this.CONNECTING),Q(this,w,3e3),Q(this,b,null!=(t=null==r?void 0:r.fetch)?t:globalThis.fetch),Q(this,P,null!=(a=null==r?void 0:r.withCredentials)&&a),G(this,I,j).call(this)}get readyState(){return H(this,y)}get url(){return H(this,_).href}get withCredentials(){return H(this,P)}get onerror(){return H(this,C)}set onerror(e){Q(this,C,e)}get onmessage(){return H(this,O)}set onmessage(e){Q(this,O,e)}get onopen(){return H(this,x)}set onopen(e){Q(this,x,e)}addEventListener(e,r,t){super.addEventListener(e,r,t)}removeEventListener(e,r,t){super.removeEventListener(e,r,t)}close(){H(this,z)&&clearTimeout(H(this,z)),H(this,y)!==this.CLOSED&&(H(this,R)&&H(this,R).abort(),Q(this,y,this.CLOSED),Q(this,R,void 0))}}y=new WeakMap,_=new WeakMap,E=new WeakMap,P=new WeakMap,b=new WeakMap,w=new WeakMap,z=new WeakMap,S=new WeakMap,R=new WeakMap,T=new WeakMap,C=new WeakMap,O=new WeakMap,x=new WeakMap,I=new WeakSet,j=function(){Q(this,y,this.CONNECTING),Q(this,R,new AbortController),H(this,b)(H(this,_),G(this,I,$).call(this)).then(H(this,A)).catch(H(this,D))},A=new WeakMap,D=new WeakMap,$=function(){var e;let r={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...H(this,S)?{"Last-Event-ID":H(this,S)}:void 0},cache:"no-store",signal:null==(e=H(this,R))?void 0:e.signal};return"window"in globalThis&&(r.credentials=this.withCredentials?"include":"same-origin"),r},F=new WeakMap,k=new WeakMap,L=function(e,r){var t;H(this,y)!==this.CLOSED&&Q(this,y,this.CLOSED);let a=new v("error",{code:r,message:e});null==(t=H(this,C))||t.call(this,a),this.dispatchEvent(a)},U=function(e,r){var t;if(H(this,y)===this.CLOSED)return;Q(this,y,this.CONNECTING);let a=new v("error",{code:r,message:e});null==(t=H(this,C))||t.call(this,a),this.dispatchEvent(a),Q(this,z,setTimeout(H(this,N),H(this,w)))},N=new WeakMap,B.CONNECTING=0,B.OPEN=1,B.CLOSED=2,e.s(["CallToolResultSchema",()=>rt,"CancelledNotificationSchema",()=>ev,"CompleteResultSchema",()=>rw,"EmptyResultSchema",()=>ef,"ErrorCode",()=>t,"GetPromptResultSchema",()=>e5,"InitializeResultSchema",()=>ez,"JSONRPCMessageSchema",()=>em,"LATEST_PROTOCOL_VERSION",()=>W,"ListPromptsResultSchema",()=>eZ,"ListResourceTemplatesResultSchema",()=>eq,"ListResourcesResultSchema",()=>eU,"ListToolsResultSchema",()=>rr,"McpError",()=>rC,"PingRequestSchema",()=>eT,"ProgressNotificationSchema",()=>eO,"ReadResourceResultSchema",()=>eH,"SUPPORTED_PROTOCOL_VERSIONS",()=>J,"isInitializedNotification",()=>eR,"isJSONRPCError",()=>ed,"isJSONRPCNotification",()=>ec,"isJSONRPCRequest",()=>en,"isJSONRPCResponse",()=>eh],76862);var K=e.i(13669);let W="2025-06-18",J=[W,"2025-03-26","2024-11-05","2024-10-07"],Z=K.z.union([K.z.string(),K.z.number().int()]),Y=K.z.string(),X=K.z.object({progressToken:K.z.optional(Z)}).passthrough(),ee=K.z.object({_meta:K.z.optional(X)}).passthrough(),er=K.z.object({method:K.z.string(),params:K.z.optional(ee)}),et=K.z.object({_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),ea=K.z.object({method:K.z.string(),params:K.z.optional(et)}),eo=K.z.object({_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),es=K.z.union([K.z.string(),K.z.number().int()]),ei=K.z.object({jsonrpc:K.z.literal("2.0"),id:es}).merge(er).strict(),en=e=>ei.safeParse(e).success,el=K.z.object({jsonrpc:K.z.literal("2.0")}).merge(ea).strict(),ec=e=>el.safeParse(e).success,eu=K.z.object({jsonrpc:K.z.literal("2.0"),id:es,result:eo}).strict(),eh=e=>eu.safeParse(e).success;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(t||(t={}));let ep=K.z.object({jsonrpc:K.z.literal("2.0"),id:es,error:K.z.object({code:K.z.number().int(),message:K.z.string(),data:K.z.optional(K.z.unknown())})}).strict(),ed=e=>ep.safeParse(e).success,em=K.z.union([ei,el,eu,ep]),ef=eo.strict(),ev=ea.extend({method:K.z.literal("notifications/cancelled"),params:et.extend({requestId:es,reason:K.z.string().optional()})}),eg=K.z.object({src:K.z.string(),mimeType:K.z.optional(K.z.string()),sizes:K.z.optional(K.z.array(K.z.string()))}).passthrough(),ey=K.z.object({icons:K.z.array(eg).optional()}).passthrough(),e_=K.z.object({name:K.z.string(),title:K.z.optional(K.z.string())}).passthrough(),eE=e_.extend({version:K.z.string(),websiteUrl:K.z.optional(K.z.string())}).merge(ey),eP=K.z.object({experimental:K.z.optional(K.z.object({}).passthrough()),sampling:K.z.optional(K.z.object({}).passthrough()),elicitation:K.z.optional(K.z.object({}).passthrough()),roots:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough())}).passthrough(),eb=er.extend({method:K.z.literal("initialize"),params:ee.extend({protocolVersion:K.z.string(),capabilities:eP,clientInfo:eE})}),ew=K.z.object({experimental:K.z.optional(K.z.object({}).passthrough()),logging:K.z.optional(K.z.object({}).passthrough()),completions:K.z.optional(K.z.object({}).passthrough()),prompts:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough()),resources:K.z.optional(K.z.object({subscribe:K.z.optional(K.z.boolean()),listChanged:K.z.optional(K.z.boolean())}).passthrough()),tools:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough())}).passthrough(),ez=eo.extend({protocolVersion:K.z.string(),capabilities:ew,serverInfo:eE,instructions:K.z.optional(K.z.string())}),eS=ea.extend({method:K.z.literal("notifications/initialized")}),eR=e=>eS.safeParse(e).success,eT=er.extend({method:K.z.literal("ping")}),eC=K.z.object({progress:K.z.number(),total:K.z.optional(K.z.number()),message:K.z.optional(K.z.string())}).passthrough(),eO=ea.extend({method:K.z.literal("notifications/progress"),params:et.merge(eC).extend({progressToken:Z})}),ex=er.extend({params:ee.extend({cursor:K.z.optional(Y)}).optional()}),eI=eo.extend({nextCursor:K.z.optional(Y)}),ej=K.z.object({uri:K.z.string(),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),eA=ej.extend({text:K.z.string()}),eD=K.z.string().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),e$=ej.extend({blob:eD}),eF=e_.extend({uri:K.z.string(),description:K.z.optional(K.z.string()),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),ek=e_.extend({uriTemplate:K.z.string(),description:K.z.optional(K.z.string()),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),eL=ex.extend({method:K.z.literal("resources/list")}),eU=eI.extend({resources:K.z.array(eF)}),eN=ex.extend({method:K.z.literal("resources/templates/list")}),eq=eI.extend({resourceTemplates:K.z.array(ek)}),eM=er.extend({method:K.z.literal("resources/read"),params:ee.extend({uri:K.z.string()})}),eH=eo.extend({contents:K.z.array(K.z.union([eA,e$]))}),eV=ea.extend({method:K.z.literal("notifications/resources/list_changed")}),eQ=er.extend({method:K.z.literal("resources/subscribe"),params:ee.extend({uri:K.z.string()})}),eG=er.extend({method:K.z.literal("resources/unsubscribe"),params:ee.extend({uri:K.z.string()})}),eB=ea.extend({method:K.z.literal("notifications/resources/updated"),params:et.extend({uri:K.z.string()})}),eK=K.z.object({name:K.z.string(),description:K.z.optional(K.z.string()),required:K.z.optional(K.z.boolean())}).passthrough(),eW=e_.extend({description:K.z.optional(K.z.string()),arguments:K.z.optional(K.z.array(eK)),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),eJ=ex.extend({method:K.z.literal("prompts/list")}),eZ=eI.extend({prompts:K.z.array(eW)}),eY=er.extend({method:K.z.literal("prompts/get"),params:ee.extend({name:K.z.string(),arguments:K.z.optional(K.z.record(K.z.string()))})}),eX=K.z.object({type:K.z.literal("text"),text:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e0=K.z.object({type:K.z.literal("image"),data:eD,mimeType:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e1=K.z.object({type:K.z.literal("audio"),data:eD,mimeType:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e2=K.z.object({type:K.z.literal("resource"),resource:K.z.union([eA,e$]),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e9=eF.extend({type:K.z.literal("resource_link")}),e4=K.z.union([eX,e0,e1,e9,e2]),e3=K.z.object({role:K.z.enum(["user","assistant"]),content:e4}).passthrough(),e5=eo.extend({description:K.z.optional(K.z.string()),messages:K.z.array(e3)}),e6=ea.extend({method:K.z.literal("notifications/prompts/list_changed")}),e7=K.z.object({title:K.z.optional(K.z.string()),readOnlyHint:K.z.optional(K.z.boolean()),destructiveHint:K.z.optional(K.z.boolean()),idempotentHint:K.z.optional(K.z.boolean()),openWorldHint:K.z.optional(K.z.boolean())}).passthrough(),e8=e_.extend({description:K.z.optional(K.z.string()),inputSchema:K.z.object({type:K.z.literal("object"),properties:K.z.optional(K.z.object({}).passthrough()),required:K.z.optional(K.z.array(K.z.string()))}).passthrough(),outputSchema:K.z.optional(K.z.object({type:K.z.literal("object"),properties:K.z.optional(K.z.object({}).passthrough()),required:K.z.optional(K.z.array(K.z.string()))}).passthrough()),annotations:K.z.optional(e7),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),re=ex.extend({method:K.z.literal("tools/list")}),rr=eI.extend({tools:K.z.array(e8)}),rt=eo.extend({content:K.z.array(e4).default([]),structuredContent:K.z.object({}).passthrough().optional(),isError:K.z.optional(K.z.boolean())});rt.or(eo.extend({toolResult:K.z.unknown()}));let ra=er.extend({method:K.z.literal("tools/call"),params:ee.extend({name:K.z.string(),arguments:K.z.optional(K.z.record(K.z.unknown()))})}),ro=ea.extend({method:K.z.literal("notifications/tools/list_changed")}),rs=K.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),ri=er.extend({method:K.z.literal("logging/setLevel"),params:ee.extend({level:rs})}),rn=ea.extend({method:K.z.literal("notifications/message"),params:et.extend({level:rs,logger:K.z.optional(K.z.string()),data:K.z.unknown()})}),rl=K.z.object({name:K.z.string().optional()}).passthrough(),rc=K.z.object({hints:K.z.optional(K.z.array(rl)),costPriority:K.z.optional(K.z.number().min(0).max(1)),speedPriority:K.z.optional(K.z.number().min(0).max(1)),intelligencePriority:K.z.optional(K.z.number().min(0).max(1))}).passthrough(),ru=K.z.object({role:K.z.enum(["user","assistant"]),content:K.z.union([eX,e0,e1])}).passthrough(),rh=er.extend({method:K.z.literal("sampling/createMessage"),params:ee.extend({messages:K.z.array(ru),systemPrompt:K.z.optional(K.z.string()),includeContext:K.z.optional(K.z.enum(["none","thisServer","allServers"])),temperature:K.z.optional(K.z.number()),maxTokens:K.z.number().int(),stopSequences:K.z.optional(K.z.array(K.z.string())),metadata:K.z.optional(K.z.object({}).passthrough()),modelPreferences:K.z.optional(rc)})}),rp=eo.extend({model:K.z.string(),stopReason:K.z.optional(K.z.enum(["endTurn","stopSequence","maxTokens"]).or(K.z.string())),role:K.z.enum(["user","assistant"]),content:K.z.discriminatedUnion("type",[eX,e0,e1])}),rd=K.z.object({type:K.z.literal("boolean"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),default:K.z.optional(K.z.boolean())}).passthrough(),rm=K.z.object({type:K.z.literal("string"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),minLength:K.z.optional(K.z.number()),maxLength:K.z.optional(K.z.number()),format:K.z.optional(K.z.enum(["email","uri","date","date-time"]))}).passthrough(),rf=K.z.object({type:K.z.enum(["number","integer"]),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),minimum:K.z.optional(K.z.number()),maximum:K.z.optional(K.z.number())}).passthrough(),rv=K.z.object({type:K.z.literal("string"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),enum:K.z.array(K.z.string()),enumNames:K.z.optional(K.z.array(K.z.string()))}).passthrough(),rg=K.z.union([rd,rm,rf,rv]),ry=er.extend({method:K.z.literal("elicitation/create"),params:ee.extend({message:K.z.string(),requestedSchema:K.z.object({type:K.z.literal("object"),properties:K.z.record(K.z.string(),rg),required:K.z.optional(K.z.array(K.z.string()))}).passthrough()})}),r_=eo.extend({action:K.z.enum(["accept","decline","cancel"]),content:K.z.optional(K.z.record(K.z.string(),K.z.unknown()))}),rE=K.z.object({type:K.z.literal("ref/resource"),uri:K.z.string()}).passthrough(),rP=K.z.object({type:K.z.literal("ref/prompt"),name:K.z.string()}).passthrough(),rb=er.extend({method:K.z.literal("completion/complete"),params:ee.extend({ref:K.z.union([rP,rE]),argument:K.z.object({name:K.z.string(),value:K.z.string()}).passthrough(),context:K.z.optional(K.z.object({arguments:K.z.optional(K.z.record(K.z.string(),K.z.string()))}))})}),rw=eo.extend({completion:K.z.object({values:K.z.array(K.z.string()).max(100),total:K.z.optional(K.z.number().int()),hasMore:K.z.optional(K.z.boolean())}).passthrough()}),rz=K.z.object({uri:K.z.string().startsWith("file://"),name:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),rS=er.extend({method:K.z.literal("roots/list")}),rR=eo.extend({roots:K.z.array(rz)}),rT=ea.extend({method:K.z.literal("notifications/roots/list_changed")});K.z.union([eT,eb,rb,ri,eY,eJ,eL,eN,eM,eQ,eG,ra,re]),K.z.union([ev,eO,eS,rT]),K.z.union([ef,rp,r_,rR]),K.z.union([eT,rh,ry,rS]),K.z.union([ev,eO,rn,eB,eV,ro,e6]),K.z.union([ef,ez,rw,e5,eZ,eU,eq,eH,rt,rr]);class rC extends Error{constructor(e,r,t){super(`MCP error ${e}: ${r}`),this.code=e,this.data=t,this.name="McpError"}}class rO{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ev,e=>{let r=this._requestHandlerAbortControllers.get(e.params.requestId);null==r||r.abort(e.params.reason)}),this.setNotificationHandler(eO,e=>{this._onprogress(e)}),this.setRequestHandler(eT,e=>({}))}_setupTimeout(e,r,t,a,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:o,onTimeout:a})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rC(t.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,t,a;this._transport=e;let o=null==(r=this.transport)?void 0:r.onclose;this._transport.onclose=()=>{null==o||o(),this._onclose()};let s=null==(t=this.transport)?void 0:t.onerror;this._transport.onerror=e=>{null==s||s(e),this._onerror(e)};let i=null==(a=this._transport)?void 0:a.onmessage;this._transport.onmessage=(e,r)=>{null==i||i(e,r),eh(e)||ed(e)?this._onresponse(e):en(e)?this._onrequest(e,r):ec(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null==(e=this.onclose)||e.call(this);let a=new rC(t.ConnectionClosed,"Connection closed");for(let e of r.values())e(a)}_onerror(e){var r;null==(r=this.onerror)||r.call(this,e)}_onnotification(e){var r;let t=null!=(r=this._notificationHandlers.get(e.method))?r:this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,r){var a,o;let s=null!=(a=this._requestHandlers.get(e.method))?a:this.fallbackRequestHandler,i=this._transport;if(void 0===s){null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:t.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);let l={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null==(o=e.params)?void 0:o._meta,sendNotification:r=>this.notification(r,{relatedRequestId:e.id}),sendRequest:(r,t,a)=>this.request(r,t,{...a,relatedRequestId:e.id}),authInfo:null==r?void 0:r.authInfo,requestId:e.id,requestInfo:null==r?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(r=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:r,jsonrpc:"2.0",id:e.id})},r=>{var a;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(r.code)?r.code:t.InternalError,message:null!=(a=r.message)?a:"Internal error"}})}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...t}=e.params,a=Number(r),o=this._progressHandlers.get(a);if(!o)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let s=this._responseHandlers.get(a),i=this._timeoutInfo.get(a);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){s(e);return}o(t)}_onresponse(e){let r=Number(e.id),t=this._responseHandlers.get(r);if(void 0===t)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),t(eh(e)?e:new rC(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await (null==(e=this._transport)?void 0:e.close())}request(e,r,a){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=null!=a?a:{};return new Promise((n,l)=>{var c,u,h,p,d,m;if(!this._transport)return void l(Error("Not connected"));(null==(c=this._options)?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),null==(u=null==a?void 0:a.signal)||u.throwIfAborted();let f=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:f};(null==a?void 0:a.onprogress)&&(this._progressHandlers.set(f,a.onprogress),v.params={...e.params,_meta:{...(null==(h=e.params)?void 0:h._meta)||{},progressToken:f}});let g=e=>{var r;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null==(r=this._transport)||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e)};this._responseHandlers.set(f,e=>{var t;if(null==(t=null==a?void 0:a.signal)||!t.aborted){if(e instanceof Error)return l(e);try{let t=r.parse(e.result);n(t)}catch(e){l(e)}}}),null==(p=null==a?void 0:a.signal)||p.addEventListener("abort",()=>{var e;g(null==(e=null==a?void 0:a.signal)?void 0:e.reason)});let y=null!=(d=null==a?void 0:a.timeout)?d:6e4;this._setupTimeout(f,y,null==a?void 0:a.maxTotalTimeout,()=>g(new rC(t.RequestTimeout,"Request timed out",{timeout:y})),null!=(m=null==a?void 0:a.resetTimeoutOnProgress)&&m),this._transport.send(v,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),l(e)})})}async notification(e,r){var t,a;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(e.method),(null!=(a=null==(t=this._options)?void 0:t.debouncedNotificationMethods)?a:[]).includes(e.method)&&!e.params&&!(null==r?void 0:r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var t;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};null==(t=this._transport)||t.send(a,r).catch(e=>this._onerror(e))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(t,a)=>Promise.resolve(r(e.parse(t),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var rx=e.i(14510);class rI extends rO{constructor(e,r){var t;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!=(t=null==r?void 0:r.capabilities)?t:{},this._ajv=new rx.default}registerCapabilities(e){var r;if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=(r=this._capabilities,Object.entries(e).reduce((e,[r,t])=>(t&&"object"==typeof t?e[r]=e[r]?{...e[r],...t}:t:e[r]=t,e),{...r}))}assertCapability(e,r){var t;if(!(null==(t=this._serverCapabilities)?void 0:t[e]))throw Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),void 0===e.sessionId)try{let t=await this.request({method:"initialize",params:{protocolVersion:W,capabilities:this._capabilities,clientInfo:this._clientInfo}},ez,r);if(void 0===t)throw Error(`Server sent invalid initialize result: ${t}`);if(!J.includes(t.protocolVersion))throw Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(t.protocolVersion),this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,t,a,o,s;switch(e){case"logging/setLevel":if(!(null==(r=this._serverCapabilities)?void 0:r.logging))throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null==(t=this._serverCapabilities)?void 0:t.prompts))throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null==(a=this._serverCapabilities)?void 0:a.resources))throw Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null==(o=this._serverCapabilities)?void 0:o.tools))throw Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null==(s=this._serverCapabilities)?void 0:s.completions))throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var r;if("notifications/roots/list_changed"===e&&!(null==(r=this._capabilities.roots)?void 0:r.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},ef,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},rw,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},ef,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},e5,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eZ,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},eU,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},eq,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},eH,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},ef,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},ef,r)}async callTool(e,r=rt,a){let o=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new rC(t.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{if(!s(o.structuredContent))throw new rC(t.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof rC)throw e;throw new rC(t.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}cacheToolOutputSchemas(e){for(let r of(this._cachedToolOutputValidators.clear(),e))if(r.outputSchema)try{let e=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let t=await this.request({method:"tools/list",params:e},rr,r);return this.cacheToolOutputSchemas(t.tools),t}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}async function rj(e){return(await r).getRandomValues(new Uint8Array(e))}async function rA(e){let r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await rj(e);for(let o=0;o<e;o++){let e=a[o]%r.length;t+=r[e]}return t}async function rD(e){return await rA(e)}async function r$(e){return btoa(String.fromCharCode(...new Uint8Array(await (await r).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function rF(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let r=await rD(e),t=await r$(r);return{code_verifier:r,code_challenge:t}}r=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);let rk=K.z.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:K.z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),K.z.NEVER}).refine(e=>{let r=new URL(e);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rL=K.z.object({resource:K.z.string().url(),authorization_servers:K.z.array(rk).optional(),jwks_uri:K.z.string().url().optional(),scopes_supported:K.z.array(K.z.string()).optional(),bearer_methods_supported:K.z.array(K.z.string()).optional(),resource_signing_alg_values_supported:K.z.array(K.z.string()).optional(),resource_name:K.z.string().optional(),resource_documentation:K.z.string().optional(),resource_policy_uri:K.z.string().url().optional(),resource_tos_uri:K.z.string().url().optional(),tls_client_certificate_bound_access_tokens:K.z.boolean().optional(),authorization_details_types_supported:K.z.array(K.z.string()).optional(),dpop_signing_alg_values_supported:K.z.array(K.z.string()).optional(),dpop_bound_access_tokens_required:K.z.boolean().optional()}).passthrough(),rU=K.z.object({issuer:K.z.string(),authorization_endpoint:rk,token_endpoint:rk,registration_endpoint:rk.optional(),scopes_supported:K.z.array(K.z.string()).optional(),response_types_supported:K.z.array(K.z.string()),response_modes_supported:K.z.array(K.z.string()).optional(),grant_types_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),service_documentation:rk.optional(),revocation_endpoint:rk.optional(),revocation_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),introspection_endpoint:K.z.string().optional(),introspection_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),code_challenge_methods_supported:K.z.array(K.z.string()).optional()}).passthrough(),rN=K.z.object({issuer:K.z.string(),authorization_endpoint:rk,token_endpoint:rk,userinfo_endpoint:rk.optional(),jwks_uri:rk,registration_endpoint:rk.optional(),scopes_supported:K.z.array(K.z.string()).optional(),response_types_supported:K.z.array(K.z.string()),response_modes_supported:K.z.array(K.z.string()).optional(),grant_types_supported:K.z.array(K.z.string()).optional(),acr_values_supported:K.z.array(K.z.string()).optional(),subject_types_supported:K.z.array(K.z.string()),id_token_signing_alg_values_supported:K.z.array(K.z.string()),id_token_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),id_token_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),userinfo_signing_alg_values_supported:K.z.array(K.z.string()).optional(),userinfo_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),userinfo_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),request_object_signing_alg_values_supported:K.z.array(K.z.string()).optional(),request_object_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),request_object_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),display_values_supported:K.z.array(K.z.string()).optional(),claim_types_supported:K.z.array(K.z.string()).optional(),claims_supported:K.z.array(K.z.string()).optional(),service_documentation:K.z.string().optional(),claims_locales_supported:K.z.array(K.z.string()).optional(),ui_locales_supported:K.z.array(K.z.string()).optional(),claims_parameter_supported:K.z.boolean().optional(),request_parameter_supported:K.z.boolean().optional(),request_uri_parameter_supported:K.z.boolean().optional(),require_request_uri_registration:K.z.boolean().optional(),op_policy_uri:rk.optional(),op_tos_uri:rk.optional()}).passthrough().merge(rU.pick({code_challenge_methods_supported:!0})),rq=K.z.object({access_token:K.z.string(),id_token:K.z.string().optional(),token_type:K.z.string(),expires_in:K.z.number().optional(),scope:K.z.string().optional(),refresh_token:K.z.string().optional()}).strip(),rM=K.z.object({error:K.z.string(),error_description:K.z.string().optional(),error_uri:K.z.string().optional()}),rH=K.z.object({redirect_uris:K.z.array(rk),token_endpoint_auth_method:K.z.string().optional(),grant_types:K.z.array(K.z.string()).optional(),response_types:K.z.array(K.z.string()).optional(),client_name:K.z.string().optional(),client_uri:rk.optional(),logo_uri:rk.optional(),scope:K.z.string().optional(),contacts:K.z.array(K.z.string()).optional(),tos_uri:rk.optional(),policy_uri:K.z.string().optional(),jwks_uri:rk.optional(),jwks:K.z.any().optional(),software_id:K.z.string().optional(),software_version:K.z.string().optional(),software_statement:K.z.string().optional()}).strip(),rV=K.z.object({client_id:K.z.string(),client_secret:K.z.string().optional(),client_id_issued_at:K.z.number().optional(),client_secret_expires_at:K.z.number().optional()}).strip(),rQ=rH.merge(rV);K.z.object({error:K.z.string(),error_description:K.z.string().optional()}).strip(),K.z.object({token:K.z.string(),token_type_hint:K.z.string().optional()}).strip();class rG extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class rB extends rG{}rB.errorCode="invalid_request";class rK extends rG{}rK.errorCode="invalid_client";class rW extends rG{}rW.errorCode="invalid_grant";class rJ extends rG{}rJ.errorCode="unauthorized_client";class rZ extends rG{}rZ.errorCode="unsupported_grant_type";class rY extends rG{}rY.errorCode="invalid_scope";class rX extends rG{}rX.errorCode="access_denied";class r0 extends rG{}r0.errorCode="server_error";class r1 extends rG{}r1.errorCode="temporarily_unavailable";class r2 extends rG{}r2.errorCode="unsupported_response_type";class r9 extends rG{}r9.errorCode="unsupported_token_type";class r4 extends rG{}r4.errorCode="invalid_token";class r3 extends rG{}r3.errorCode="method_not_allowed";class r5 extends rG{}r5.errorCode="too_many_requests";class r6 extends rG{}r6.errorCode="invalid_client_metadata";class r7 extends rG{}r7.errorCode="insufficient_scope";let r8={[rB.errorCode]:rB,[rK.errorCode]:rK,[rW.errorCode]:rW,[rJ.errorCode]:rJ,[rZ.errorCode]:rZ,[rY.errorCode]:rY,[rX.errorCode]:rX,[r0.errorCode]:r0,[r1.errorCode]:r1,[r2.errorCode]:r2,[r9.errorCode]:r9,[r4.errorCode]:r4,[r3.errorCode]:r3,[r5.errorCode]:r5,[r6.errorCode]:r6,[r7.errorCode]:r7};class te extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function tr(e,r){let t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function tt(e,r,t,a){let{client_id:o,client_secret:s}=r;switch(e){case"client_secret_basic":var i,n,l,c,u=o,h=s,p=t;if(!h)throw Error("client_secret_basic authentication requires a client_secret");let d=btoa(`${u}:${h}`);p.set("Authorization",`Basic ${d}`);return;case"client_secret_post":i=o,n=s,(l=a).set("client_id",i),n&&l.set("client_secret",n);return;case"none":c=o,a.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}async function ta(e){let r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=rM.parse(JSON.parse(t));return new(r8[e]||r0)(r||"",a)}catch(e){return new r0(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function to(e,r){var t,a;try{return await ts(e,r)}catch(o){if(o instanceof rK||o instanceof rJ)return await (null==(t=e.invalidateCredentials)?void 0:t.call(e,"all")),await ts(e,r);if(o instanceof rW)return await (null==(a=e.invalidateCredentials)?void 0:a.call(e,"tokens")),await ts(e,r);throw o}}async function ts(e,{serverUrl:r,authorizationCode:t,scope:a,resourceMetadataUrl:o,fetchFn:s}){let i,n;try{(i=await tl(r,{resourceMetadataUrl:o},s)).authorization_servers&&i.authorization_servers.length>0&&(n=i.authorization_servers[0])}catch(e){}n||(n=r);let l=await ti(r,e,i),c=await tp(n,{fetchFn:s}),u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==t)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let r=await tv(n,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(r),u=r}if(void 0!==t){let r=await e.codeVerifier(),a=await tm(n,{metadata:c,clientInformation:u,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(a),"AUTHORIZED"}let h=await e.tokens();if(null==h?void 0:h.refresh_token)try{let r=await tf(n,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(!(e instanceof rG)||e instanceof r0);else throw e}let p=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:m}=await td(n,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(d),"REDIRECT"}async function ti(e,r,t){let a=function(e){let r=new URL("string"==typeof e?e:e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(a,null==t?void 0:t.resource);if(t){if(!function({requestedResource:e,configuredResource:r}){let t=new URL("string"==typeof e?e:e.href),a=new URL("string"==typeof r?r:r.href);if(t.origin!==a.origin||t.pathname.length<a.pathname.length)return!1;let o=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return o.startsWith(s)}({requestedResource:a,configuredResource:t.resource}))throw Error(`Protected resource ${t.resource} does not match expected ${a} (or origin)`);return new URL(t.resource)}}function tn(e){let r=e.headers.get("WWW-Authenticate");if(!r)return;let[t,a]=r.split(" ");if("bearer"!==t.toLowerCase()||!a)return;let o=/resource_metadata="([^"]*)"/.exec(r);if(o)try{return new URL(o[1])}catch(e){return}}async function tl(e,r,t=fetch){let a=await th(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!a||404===a.status)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return rL.parse(await a.json())}async function tc(e,r,t=fetch){try{return await t(e,{headers:r})}catch(a){if(a instanceof TypeError)if(r)return tc(e,void 0,t);else return;throw a}}async function tu(e,r,t=fetch){return await tc(e,{"MCP-Protocol-Version":r},t)}async function th(e,r,t,a){var o,s,i,n;let l,c=new URL(e),u=null!=(o=null==a?void 0:a.protocolVersion)?o:W;(null==a?void 0:a.metadataUrl)?l=new URL(a.metadataUrl):(l=new URL(function(e,r="",t={}){return r.endsWith("/")&&(r=r.slice(0,-1)),t.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}(r,c.pathname),null!=(s=null==a?void 0:a.metadataServerUrl)?s:c)).search=c.search;let h=await tu(l,u,t);if(!(null==a?void 0:a.metadataUrl)&&(i=h,n=c.pathname,!i||i.status>=400&&i.status<500&&"/"!==n)){let e=new URL(`/.well-known/${r}`,c);h=await tu(e,u,t)}return h}async function tp(e,{fetchFn:r=fetch,protocolVersion:t=W}={}){var a;let o={"MCP-Protocol-Version":t};for(let{url:t,type:s}of function(e){let r="string"==typeof e?new URL(e):e,t="/"!==r.pathname,a=[];if(!t)return a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),a;let o=r.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${o}`,r.origin),type:"oidc"}),a.push({url:new URL(`${o}/.well-known/openid-configuration`,r.origin),type:"oidc"}),a}(e)){let e=await tc(t,o,r);if(e){if(!e.ok){if(e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===s?"OAuth":"OpenID provider"} metadata from ${t}`)}if("oauth"===s)return rU.parse(await e.json());{let r=rN.parse(await e.json());if(!(null==(a=r.code_challenge_methods_supported)?void 0:a.includes("S256")))throw Error(`Incompatible OIDC provider at ${t}: does not support S256 code challenge method required by MCP specification`);return r}}}}async function td(e,{metadata:r,clientInformation:t,redirectUrl:a,scope:o,state:s,resource:i}){let n,l="code",c="S256";if(r){if(n=new URL(r.authorization_endpoint),!r.response_types_supported.includes(l))throw Error(`Incompatible auth server: does not support response type ${l}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else n=new URL("/authorize",e);let u=await rF(),h=u.code_verifier,p=u.code_challenge;return n.searchParams.set("response_type",l),n.searchParams.set("client_id",t.client_id),n.searchParams.set("code_challenge",p),n.searchParams.set("code_challenge_method",c),n.searchParams.set("redirect_uri",String(a)),s&&n.searchParams.set("state",s),o&&n.searchParams.set("scope",o),(null==o?void 0:o.includes("offline_access"))&&n.searchParams.append("prompt","consent"),i&&n.searchParams.set("resource",i.href),{authorizationUrl:n,codeVerifier:h}}async function tm(e,{metadata:r,clientInformation:t,authorizationCode:a,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:n,fetchFn:l}){var c;let u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:o,redirect_uri:String(s)});n?n(p,d,e,r):tt(tr(t,null!=(c=null==r?void 0:r.token_endpoint_auth_methods_supported)?c:[]),t,p,d),i&&d.set("resource",i.href);let m=await (null!=l?l:fetch)(h,{method:"POST",headers:p,body:d});if(!m.ok)throw await ta(m);return rq.parse(await m.json())}async function tf(e,{metadata:r,clientInformation:t,refreshToken:a,resource:o,addClientAuthentication:s,fetchFn:i}){var n;let l,c="refresh_token";if(r){if(l=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:a});s?s(u,h,e,r):tt(tr(t,null!=(n=null==r?void 0:r.token_endpoint_auth_methods_supported)?n:[]),t,u,h),o&&h.set("resource",o.href);let p=await (null!=i?i:fetch)(l,{method:"POST",headers:u,body:h});if(!p.ok)throw await ta(p);return rq.parse({refresh_token:a,...await p.json()})}async function tv(e,{metadata:r,clientMetadata:t,fetchFn:a}){let o;if(r){if(!r.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");o=new URL(r.registration_endpoint)}else o=new URL("/register",e);let s=await (null!=a?a:fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw await ta(s);return rQ.parse(await s.json())}class tg extends Error{constructor(e,r,t){super(`SSE error: ${r}`),this.code=e,this.event=t}}class ty{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=null==r?void 0:r.eventSourceInit,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch}async _authThenStart(){var e;let r;if(!this._authProvider)throw new te("No auth provider");try{r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new te;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...null==(e=this._requestInit)?void 0:e.headers})}_startOrAuth(){var e,r,t;let a=null!=(t=null!=(r=null==(e=this===null||void 0===this?void 0:this._eventSourceInit)?void 0:e.fetch)?r:this._fetch)?t:fetch;return new Promise((e,r)=>{this._eventSource=new B(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let t=await this._commonHeaders();t.set("Accept","text/event-stream");let o=await a(e,{...r,headers:t});return 401===o.status&&o.headers.has("www-authenticate")&&(this._resourceMetadataUrl=tn(o)),o}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{var a;if(401===t.code&&this._authProvider)return void this._authThenStart().then(e,r);let o=new tg(t.code,t.message,t);r(o),null==(a=this.onerror)||a.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",t=>{var a;try{if(this._endpoint=new URL(t.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),null==(a=this.onerror)||a.call(this,e),this.close();return}e()}),this._eventSource.onmessage=e=>{var r,t;let a;try{a=em.parse(JSON.parse(e.data))}catch(e){null==(r=this.onerror)||r.call(this,e);return}null==(t=this.onmessage)||t.call(this,a)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new te("No auth provider");if("AUTHORIZED"!==await to(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new te("Failed to authorize")}async close(){var e,r,t;null==(e=this._abortController)||e.abort(),null==(r=this._eventSource)||r.close(),null==(t=this.onclose)||t.call(this)}async send(e){var r,t,a;if(!this._endpoint)throw Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:null==(r=this._abortController)?void 0:r.signal},s=await (null!=(t=this._fetch)?t:fetch)(this._endpoint,o);if(!s.ok){if(401===s.status&&this._authProvider){this._resourceMetadataUrl=tn(s);let r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new te;return this.send(e)}let r=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${r}`)}}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}}class t_ extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let a;super({start(o){a=f({onEvent:e=>{o.enqueue(e)},onError(r){"terminate"===e?o.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){a.feed(e)}})}}let tE={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tP extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class tb{constructor(e,r){var t;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!=(t=null==r?void 0:r.reconnectionOptions)?t:tE}async _authThenStart(){var e;let r;if(!this._authProvider)throw new te("No auth provider");try{r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new te;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let t=this._normalizeHeaders(null==(e=this._requestInit)?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,a;let{resumptionToken:o}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);let s=await (null!=(r=this._fetch)?r:fetch)(this._url,{method:"GET",headers:a,signal:null==(t=this._abortController)?void 0:t.signal});if(!s.ok){if(401===s.status&&this._authProvider)return await this._authThenStart();if(405===s.status)return;throw new tP(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay;return Math.min(r*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;let a=this._reconnectionOptions.maxRetries;if(a>0&&r>=a){null==(t=this.onerror)||t.call(this,Error(`Maximum reconnection attempts (${a}) exceeded.`));return}setTimeout(()=>{this._startOrAuthSse(e).catch(t=>{var a;null==(a=this.onerror)||a.call(this,Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)})},this._getNextReconnectionDelay(r))}_handleSseStream(e,r,t){let a;if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r;(async()=>{var r,i,n,l;try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new t_).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,null==o||o(e.id)),!e.event||"message"===e.event)try{let t=em.parse(JSON.parse(e.data));void 0!==s&&eh(t)&&(t.id=s),null==(r=this.onmessage)||r.call(this,t)}catch(e){null==(i=this.onerror)||i.call(this,e)}}}catch(e){if(null==(n=this.onerror)||n.call(this,Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(e){null==(l=this.onerror)||l.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new te("No auth provider");if("AUTHORIZED"!==await to(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new te("Failed to authorize")}async close(){var e,r;null==(e=this._abortController)||e.abort(),null==(r=this.onclose)||r.call(this)}async send(e,r){var t,a,o,s;try{let{resumptionToken:s,onresumptiontoken:i}=r||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:en(e)?e.id:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:null==(t=this._abortController)?void 0:t.signal},c=await (null!=(a=this._fetch)?a:fetch)(this._url,l),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){if(401===c.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tP(401,"Server returned 401 after successful authentication");this._resourceMetadataUrl=tn(c);let r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new te;return this._hasCompletedAuthFlow=!0,this.send(e)}let r=await c.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${c.status}): ${r}`)}if(this._hasCompletedAuthFlow=!1,202===c.status){eR(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});return}let h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=c.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:i},!1);else if(null==p?void 0:p.includes("application/json")){let e=await c.json();for(let r of Array.isArray(e)?e.map(e=>em.parse(e)):[em.parse(e)])null==(o=this.onmessage)||o.call(this,r)}else throw new tP(-1,`Unexpected content type: ${p}`)}catch(e){throw null==(s=this.onerror)||s.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{let t=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:t,signal:null==(e=this._abortController)?void 0:e.signal},o=await (null!=(r=this._fetch)?r:fetch)(this._url,a);if(!o.ok&&405!==o.status)throw new tP(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(e){throw null==(t=this.onerror)||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}let tw=e=>{if(!e||0===e.length)return"";let r=e.toLowerCase();return r.substring(0,1).toUpperCase()+r.substring(1,r.length)};e.s(["interpolateFunctionValue",()=>tz],43488);let tz=({value:e,args:r,thread:t,assistant:a})=>{let o=[];return{value:(e||"").replace(/{{\s*([\w-]+)\s*}}/g,(e,s)=>r&&s in r?String(r[s]):s in(t.metadata||{})?String(t.metadata[s]):"threadId"===s?t.id:"assistantId"===s?a.id:(o.push(s),`{{${s}}}`)),missing:o}};e.s(["createLog",()=>tR],18527);var tS=e.i(45076);let tR=({log:e,prisma:r})=>(0,tS.waitUntil)(new Promise(async t=>{console.log("Logging error."),await r.log.create({data:e}),console.log("Successfully logged error."),t(!0)})),tT=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{headers:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let s={},i=[];for(let[n,l]of Object.entries((({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.headers:e.transportType===a.TransportType.SSE?e.sseTransport.headers:{})({mcpServer:e}))){let e=tz({value:l,args:t,thread:r,assistant:o});s[n]=e.value,i.push(...e.missing)}return{headers:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tR({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return Object.fromEntries(Object.entries({...s,...e.metadata??{}}).map(([e,r])=>[(e=>{let r=e?.replace(/([A-Z])+/g,tw)?.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.toLowerCase())??[];return 0===r.length?"":1===r.length?r[0]:r.reduce((e,r)=>`${e}-${r.toLowerCase()}`)})(e),r]))},tC=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{url:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let{value:s,missing:i}=tz({value:(({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.url:e.transportType===a.TransportType.SSE?e.sseTransport.url:"")({mcpServer:e}),args:t,thread:r,assistant:o});return{url:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tR({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return s};e.g.EventSource=B;let tO=async({mcpServer:e,thread:r,assistant:t,prisma:o})=>{let s=new rI({name:"superinterface-mcp-client",version:"1.0.0"},{capabilities:{}}),i=(({mcpServer:e,thread:r,assistant:t,prisma:o})=>{if(e.transportType===a.TransportType.STDIO)throw Error("STDIO transport is not supported.");if(e.transportType===a.TransportType.HTTP){let a=tT({thread:r,mcpServer:e,assistant:t,prisma:o});return new tb(new URL(tC({thread:r,mcpServer:e,assistant:t,prisma:o})),{requestInit:{headers:a}})}if(e.transportType===a.TransportType.SSE){let a=tC({thread:r,mcpServer:e,assistant:t,prisma:o}),s=tT({thread:r,mcpServer:e,assistant:t,prisma:o});return new ty(new URL(a),{eventSourceInit:{fetch:(({headers:e})=>(r,t)=>{let a=new Headers({...t?.headers??{},...e});return fetch(r.toString(),{...t,headers:a})})({headers:s})},requestInit:{headers:s}})}throw Error(`Unknown transport type ${e.transportType}`)})({mcpServer:e,thread:r,assistant:t,prisma:o});return await s.connect(i),{mcpConnection:{client:s,transport:i}}};e.s(["closeMcpConnection",()=>tx],10273);let tx=async({mcpConnection:e})=>{await e.client.close(),await e.transport.close()},tI=({mcpServers:e,thread:r,assistant:t,prisma:a})=>Promise.all(e.map(async e=>{let{mcpConnection:o}=await tO({mcpServer:e,thread:r,assistant:t,prisma:a}),s=await o.client.listTools();return await tx({mcpConnection:o}),s.tools.map(e=>({type:"function",function:(({tool:e})=>({name:e.name,description:e.description,parameters:e.inputSchema}))({tool:e})}))})),tj=async({assistant:e,thread:r,prisma:t})=>{let o=e.mcpServers.filter(e=>!e.computerUseTool);if(l({storageProviderType:e.storageProviderType})&&!e.modelSlug.match("computer-use")){let s=o.filter(e=>e.transportType===a.TransportType.HTTP).map(a=>({type:"mcp",mcp:{server_label:`mcp-server-${a.id}`,server_url:tC({thread:r,mcpServer:a,assistant:e,prisma:t}),headers:tT({thread:r,mcpServer:a,assistant:e,prisma:t}),require_approval:"never"}})),i=o.filter(e=>e.transportType===a.TransportType.SSE);return[...s,...(0,h.flat)(await tI({mcpServers:i,thread:r,assistant:e,prisma:t}))]}let s=await tI({mcpServers:o,thread:r,assistant:e,prisma:t});return(0,h.flat)(s)},tA=async({assistant:e,thread:r,prisma:t})=>{let o=p.find(r=>r.type===e.modelProvider.type);return o&&o.isFunctionCallingAvailable?{tools:[...await tj({assistant:e,thread:r,prisma:t}),...e.functions.map(e=>({type:"function",function:e.openapiSpec})),...(({assistant:e})=>i({storageProviderType:e.storageProviderType})||l({storageProviderType:e.storageProviderType})?e.tools.map(r=>{if(r.type===a.ToolType.FILE_SEARCH)return i({storageProviderType:e.storageProviderType})?{type:"file_search"}:{type:"file_search",file_search:{vector_store_ids:r.fileSearchTool.vectorStoreIds,max_num_results:r.fileSearchTool.maxNumResults}};if(r.type===a.ToolType.CODE_INTERPRETER)return i({storageProviderType:e.storageProviderType})?{type:"code_interpreter"}:{type:"code_interpreter",code_interpreter:{container:{type:"auto"}}};if(r.type===a.ToolType.IMAGE_GENERATION)return{type:"image_generation",image_generation:{model:r.imageGenerationTool.model,background:r.imageGenerationTool.background.toLowerCase(),quality:r.imageGenerationTool.quality.toLowerCase(),output_format:r.imageGenerationTool.outputFormat.toLowerCase(),size:(({tool:e})=>e.imageGenerationTool.size===a.ImageGenerationToolSize.AUTO?"auto":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1024?"1024x1024":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1536?"1024x1536":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1536_1024?"1536x1024":void 0)({tool:r}),partial_images:r.imageGenerationTool.partialImages}};if(r.type===a.ToolType.WEB_SEARCH)return{type:"web_search"};if(r.type===a.ToolType.COMPUTER_USE)return r.computerUseTool.mcpServerId?{type:"computer_use_preview",computer_use_preview:{environment:r.computerUseTool.environment.toLowerCase(),display_width:r.computerUseTool.displayWidth,display_height:r.computerUseTool.displayHeight}}:null;return null}).filter(Boolean):[])({assistant:e,modelProviderConfig:o})]}:{}},tD=({assistant:e,prisma:r,thread:t=null})=>(0,o.supercompat)({client:(0,c.clientAdapter)({modelProvider:e.modelProvider}),storage:(({assistant:e,prisma:r})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.prismaStorageAdapter)({prisma:r});if(!i({storageProviderType:e.storageProviderType})){if(l({storageProviderType:e.storageProviderType}))return(0,o.responsesStorageAdapter)();throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,prisma:r}),runAdapter:(({assistant:e,thread:r,prisma:t})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.completionsRunAdapter)();if(!i({storageProviderType:e.storageProviderType})){if(l({storageProviderType:e.storageProviderType}))return(0,o.responsesRunAdapter)({getOpenaiAssistant:(({assistant:e,thread:r,prisma:t})=>async({select:{id:o=!1}={}}={})=>({id:o}).id?{id:e.id}:{id:e.id,object:"assistant",created_at:(0,u.default)().unix(),model:e.modelSlug,name:e.name,instructions:e.instructions,description:null,tools:r?(await tA({assistant:e,thread:r,prisma:t}))?.tools??[]:[],metadata:{},top_p:1,temperature:1,response_format:{type:"text"},truncation_strategy:(({assistant:e})=>e.truncationType===a.TruncationType.LAST_MESSAGES?{type:"last_messages",last_messages:e.truncationLastMessagesCount}:e.truncationType===a.TruncationType.DISABLED?{type:"disabled"}:{type:"auto"})({assistant:e})})({assistant:e,thread:r,prisma:t}),waitUntil:tS.waitUntil});throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,thread:t,prisma:r})})}];
|
|
5
|
+
`&&a++}}return[r,t]}(`${s}${r}`);for(let e of t)u(e);s=a,i=!1},reset:function(e={}){s&&e.consume&&u(s),i=!0,n=void 0,l="",c="",s=""}}}class v extends Event{constructor(e,r){var t,a;super(e),this.code=null!=(t=null==r?void 0:r.code)?t:void 0,this.message=null!=(a=null==r?void 0:r.message)?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,t){return t(g(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(g(this),r)}}function g(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var y,_,E,P,b,w,z,S,R,T,C,O,x,I,j,A,D,$,F,k,L,U,N,q=e=>{throw TypeError(e)},M=(e,r,t)=>r.has(e)||q("Cannot "+t),H=(e,r,t)=>(M(e,r,"read from private field"),t?t.call(e):r.get(e)),V=(e,r,t)=>r.has(e)?q("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t),Q=(e,r,t,a)=>(M(e,r,"write to private field"),r.set(e,t),t),G=(e,r,t)=>(M(e,r,"access private method"),t);class B extends EventTarget{constructor(e,r){var t,a;super(),V(this,I),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,V(this,y),V(this,_),V(this,E),V(this,P),V(this,b),V(this,w),V(this,z),V(this,S,null),V(this,R),V(this,T),V(this,C,null),V(this,O,null),V(this,x,null),V(this,A,async e=>{var r;H(this,T).reset();let{body:t,redirected:a,status:o,headers:s}=e;if(204===o){G(this,I,L).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Q(this,E,new URL(e.url)):Q(this,E,void 0),200!==o)return void G(this,I,L).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void G(this,I,L).call(this,'Invalid content type, expected "text/event-stream"',o);if(H(this,y)===this.CLOSED)return;Q(this,y,this.OPEN);let i=new Event("open");if(null==(r=H(this,x))||r.call(this,i),this.dispatchEvent(i),"object"!=typeof t||!t||!("getReader"in t)){G(this,I,L).call(this,"Invalid response body, expected a web ReadableStream",o),this.close();return}let n=new TextDecoder,l=t.getReader(),c=!0;do{let{done:e,value:r}=await l.read();r&&H(this,T).feed(n.decode(r,{stream:!e})),e&&(c=!1,H(this,T).reset(),G(this,I,U).call(this))}while(c)}),V(this,D,e=>{Q(this,R,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&G(this,I,U).call(this,function e(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(e).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${e(r.cause)}`:r.message:`${r}`}(e))}),V(this,F,e=>{"string"==typeof e.id&&Q(this,S,e.id);let r=new MessageEvent(e.event||"message",{data:e.data,origin:H(this,E)?H(this,E).origin:H(this,_).origin,lastEventId:e.id||""});H(this,O)&&(!e.event||"message"===e.event)&&H(this,O).call(this,r),this.dispatchEvent(r)}),V(this,k,e=>{Q(this,w,e)}),V(this,N,()=>{Q(this,z,void 0),H(this,y)===this.CONNECTING&&G(this,I,j).call(this)});try{if(e instanceof URL)Q(this,_,e);else if("string"==typeof e)Q(this,_,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let r=globalThis.DOMException;return"function"==typeof r?new r(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}Q(this,T,f({onEvent:H(this,F),onRetry:H(this,k)})),Q(this,y,this.CONNECTING),Q(this,w,3e3),Q(this,b,null!=(t=null==r?void 0:r.fetch)?t:globalThis.fetch),Q(this,P,null!=(a=null==r?void 0:r.withCredentials)&&a),G(this,I,j).call(this)}get readyState(){return H(this,y)}get url(){return H(this,_).href}get withCredentials(){return H(this,P)}get onerror(){return H(this,C)}set onerror(e){Q(this,C,e)}get onmessage(){return H(this,O)}set onmessage(e){Q(this,O,e)}get onopen(){return H(this,x)}set onopen(e){Q(this,x,e)}addEventListener(e,r,t){super.addEventListener(e,r,t)}removeEventListener(e,r,t){super.removeEventListener(e,r,t)}close(){H(this,z)&&clearTimeout(H(this,z)),H(this,y)!==this.CLOSED&&(H(this,R)&&H(this,R).abort(),Q(this,y,this.CLOSED),Q(this,R,void 0))}}y=new WeakMap,_=new WeakMap,E=new WeakMap,P=new WeakMap,b=new WeakMap,w=new WeakMap,z=new WeakMap,S=new WeakMap,R=new WeakMap,T=new WeakMap,C=new WeakMap,O=new WeakMap,x=new WeakMap,I=new WeakSet,j=function(){Q(this,y,this.CONNECTING),Q(this,R,new AbortController),H(this,b)(H(this,_),G(this,I,$).call(this)).then(H(this,A)).catch(H(this,D))},A=new WeakMap,D=new WeakMap,$=function(){var e;let r={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...H(this,S)?{"Last-Event-ID":H(this,S)}:void 0},cache:"no-store",signal:null==(e=H(this,R))?void 0:e.signal};return"window"in globalThis&&(r.credentials=this.withCredentials?"include":"same-origin"),r},F=new WeakMap,k=new WeakMap,L=function(e,r){var t;H(this,y)!==this.CLOSED&&Q(this,y,this.CLOSED);let a=new v("error",{code:r,message:e});null==(t=H(this,C))||t.call(this,a),this.dispatchEvent(a)},U=function(e,r){var t;if(H(this,y)===this.CLOSED)return;Q(this,y,this.CONNECTING);let a=new v("error",{code:r,message:e});null==(t=H(this,C))||t.call(this,a),this.dispatchEvent(a),Q(this,z,setTimeout(H(this,N),H(this,w)))},N=new WeakMap,B.CONNECTING=0,B.OPEN=1,B.CLOSED=2,e.s(["CallToolResultSchema",()=>rt,"CancelledNotificationSchema",()=>ev,"CompleteResultSchema",()=>rw,"EmptyResultSchema",()=>ef,"ErrorCode",()=>t,"GetPromptResultSchema",()=>e5,"InitializeResultSchema",()=>ez,"JSONRPCMessageSchema",()=>em,"LATEST_PROTOCOL_VERSION",()=>W,"ListPromptsResultSchema",()=>eZ,"ListResourceTemplatesResultSchema",()=>eq,"ListResourcesResultSchema",()=>eU,"ListToolsResultSchema",()=>rr,"McpError",()=>rC,"PingRequestSchema",()=>eT,"ProgressNotificationSchema",()=>eO,"ReadResourceResultSchema",()=>eH,"SUPPORTED_PROTOCOL_VERSIONS",()=>J,"isInitializedNotification",()=>eR,"isJSONRPCError",()=>ed,"isJSONRPCNotification",()=>ec,"isJSONRPCRequest",()=>en,"isJSONRPCResponse",()=>eh],76862);var K=e.i(13669);let W="2025-06-18",J=[W,"2025-03-26","2024-11-05","2024-10-07"],Z=K.z.union([K.z.string(),K.z.number().int()]),Y=K.z.string(),X=K.z.object({progressToken:K.z.optional(Z)}).passthrough(),ee=K.z.object({_meta:K.z.optional(X)}).passthrough(),er=K.z.object({method:K.z.string(),params:K.z.optional(ee)}),et=K.z.object({_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),ea=K.z.object({method:K.z.string(),params:K.z.optional(et)}),eo=K.z.object({_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),es=K.z.union([K.z.string(),K.z.number().int()]),ei=K.z.object({jsonrpc:K.z.literal("2.0"),id:es}).merge(er).strict(),en=e=>ei.safeParse(e).success,el=K.z.object({jsonrpc:K.z.literal("2.0")}).merge(ea).strict(),ec=e=>el.safeParse(e).success,eu=K.z.object({jsonrpc:K.z.literal("2.0"),id:es,result:eo}).strict(),eh=e=>eu.safeParse(e).success;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(t||(t={}));let ep=K.z.object({jsonrpc:K.z.literal("2.0"),id:es,error:K.z.object({code:K.z.number().int(),message:K.z.string(),data:K.z.optional(K.z.unknown())})}).strict(),ed=e=>ep.safeParse(e).success,em=K.z.union([ei,el,eu,ep]),ef=eo.strict(),ev=ea.extend({method:K.z.literal("notifications/cancelled"),params:et.extend({requestId:es,reason:K.z.string().optional()})}),eg=K.z.object({src:K.z.string(),mimeType:K.z.optional(K.z.string()),sizes:K.z.optional(K.z.array(K.z.string()))}).passthrough(),ey=K.z.object({icons:K.z.array(eg).optional()}).passthrough(),e_=K.z.object({name:K.z.string(),title:K.z.optional(K.z.string())}).passthrough(),eE=e_.extend({version:K.z.string(),websiteUrl:K.z.optional(K.z.string())}).merge(ey),eP=K.z.object({experimental:K.z.optional(K.z.object({}).passthrough()),sampling:K.z.optional(K.z.object({}).passthrough()),elicitation:K.z.optional(K.z.object({}).passthrough()),roots:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough())}).passthrough(),eb=er.extend({method:K.z.literal("initialize"),params:ee.extend({protocolVersion:K.z.string(),capabilities:eP,clientInfo:eE})}),ew=K.z.object({experimental:K.z.optional(K.z.object({}).passthrough()),logging:K.z.optional(K.z.object({}).passthrough()),completions:K.z.optional(K.z.object({}).passthrough()),prompts:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough()),resources:K.z.optional(K.z.object({subscribe:K.z.optional(K.z.boolean()),listChanged:K.z.optional(K.z.boolean())}).passthrough()),tools:K.z.optional(K.z.object({listChanged:K.z.optional(K.z.boolean())}).passthrough())}).passthrough(),ez=eo.extend({protocolVersion:K.z.string(),capabilities:ew,serverInfo:eE,instructions:K.z.optional(K.z.string())}),eS=ea.extend({method:K.z.literal("notifications/initialized")}),eR=e=>eS.safeParse(e).success,eT=er.extend({method:K.z.literal("ping")}),eC=K.z.object({progress:K.z.number(),total:K.z.optional(K.z.number()),message:K.z.optional(K.z.string())}).passthrough(),eO=ea.extend({method:K.z.literal("notifications/progress"),params:et.merge(eC).extend({progressToken:Z})}),ex=er.extend({params:ee.extend({cursor:K.z.optional(Y)}).optional()}),eI=eo.extend({nextCursor:K.z.optional(Y)}),ej=K.z.object({uri:K.z.string(),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),eA=ej.extend({text:K.z.string()}),eD=K.z.string().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),e$=ej.extend({blob:eD}),eF=e_.extend({uri:K.z.string(),description:K.z.optional(K.z.string()),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),ek=e_.extend({uriTemplate:K.z.string(),description:K.z.optional(K.z.string()),mimeType:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),eL=ex.extend({method:K.z.literal("resources/list")}),eU=eI.extend({resources:K.z.array(eF)}),eN=ex.extend({method:K.z.literal("resources/templates/list")}),eq=eI.extend({resourceTemplates:K.z.array(ek)}),eM=er.extend({method:K.z.literal("resources/read"),params:ee.extend({uri:K.z.string()})}),eH=eo.extend({contents:K.z.array(K.z.union([eA,e$]))}),eV=ea.extend({method:K.z.literal("notifications/resources/list_changed")}),eQ=er.extend({method:K.z.literal("resources/subscribe"),params:ee.extend({uri:K.z.string()})}),eG=er.extend({method:K.z.literal("resources/unsubscribe"),params:ee.extend({uri:K.z.string()})}),eB=ea.extend({method:K.z.literal("notifications/resources/updated"),params:et.extend({uri:K.z.string()})}),eK=K.z.object({name:K.z.string(),description:K.z.optional(K.z.string()),required:K.z.optional(K.z.boolean())}).passthrough(),eW=e_.extend({description:K.z.optional(K.z.string()),arguments:K.z.optional(K.z.array(eK)),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),eJ=ex.extend({method:K.z.literal("prompts/list")}),eZ=eI.extend({prompts:K.z.array(eW)}),eY=er.extend({method:K.z.literal("prompts/get"),params:ee.extend({name:K.z.string(),arguments:K.z.optional(K.z.record(K.z.string()))})}),eX=K.z.object({type:K.z.literal("text"),text:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e0=K.z.object({type:K.z.literal("image"),data:eD,mimeType:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e1=K.z.object({type:K.z.literal("audio"),data:eD,mimeType:K.z.string(),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e2=K.z.object({type:K.z.literal("resource"),resource:K.z.union([eA,e$]),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),e9=eF.extend({type:K.z.literal("resource_link")}),e4=K.z.union([eX,e0,e1,e9,e2]),e3=K.z.object({role:K.z.enum(["user","assistant"]),content:e4}).passthrough(),e5=eo.extend({description:K.z.optional(K.z.string()),messages:K.z.array(e3)}),e6=ea.extend({method:K.z.literal("notifications/prompts/list_changed")}),e7=K.z.object({title:K.z.optional(K.z.string()),readOnlyHint:K.z.optional(K.z.boolean()),destructiveHint:K.z.optional(K.z.boolean()),idempotentHint:K.z.optional(K.z.boolean()),openWorldHint:K.z.optional(K.z.boolean())}).passthrough(),e8=e_.extend({description:K.z.optional(K.z.string()),inputSchema:K.z.object({type:K.z.literal("object"),properties:K.z.optional(K.z.object({}).passthrough()),required:K.z.optional(K.z.array(K.z.string()))}).passthrough(),outputSchema:K.z.optional(K.z.object({type:K.z.literal("object"),properties:K.z.optional(K.z.object({}).passthrough()),required:K.z.optional(K.z.array(K.z.string()))}).passthrough()),annotations:K.z.optional(e7),_meta:K.z.optional(K.z.object({}).passthrough())}).merge(ey),re=ex.extend({method:K.z.literal("tools/list")}),rr=eI.extend({tools:K.z.array(e8)}),rt=eo.extend({content:K.z.array(e4).default([]),structuredContent:K.z.object({}).passthrough().optional(),isError:K.z.optional(K.z.boolean())});rt.or(eo.extend({toolResult:K.z.unknown()}));let ra=er.extend({method:K.z.literal("tools/call"),params:ee.extend({name:K.z.string(),arguments:K.z.optional(K.z.record(K.z.unknown()))})}),ro=ea.extend({method:K.z.literal("notifications/tools/list_changed")}),rs=K.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),ri=er.extend({method:K.z.literal("logging/setLevel"),params:ee.extend({level:rs})}),rn=ea.extend({method:K.z.literal("notifications/message"),params:et.extend({level:rs,logger:K.z.optional(K.z.string()),data:K.z.unknown()})}),rl=K.z.object({name:K.z.string().optional()}).passthrough(),rc=K.z.object({hints:K.z.optional(K.z.array(rl)),costPriority:K.z.optional(K.z.number().min(0).max(1)),speedPriority:K.z.optional(K.z.number().min(0).max(1)),intelligencePriority:K.z.optional(K.z.number().min(0).max(1))}).passthrough(),ru=K.z.object({role:K.z.enum(["user","assistant"]),content:K.z.union([eX,e0,e1])}).passthrough(),rh=er.extend({method:K.z.literal("sampling/createMessage"),params:ee.extend({messages:K.z.array(ru),systemPrompt:K.z.optional(K.z.string()),includeContext:K.z.optional(K.z.enum(["none","thisServer","allServers"])),temperature:K.z.optional(K.z.number()),maxTokens:K.z.number().int(),stopSequences:K.z.optional(K.z.array(K.z.string())),metadata:K.z.optional(K.z.object({}).passthrough()),modelPreferences:K.z.optional(rc)})}),rp=eo.extend({model:K.z.string(),stopReason:K.z.optional(K.z.enum(["endTurn","stopSequence","maxTokens"]).or(K.z.string())),role:K.z.enum(["user","assistant"]),content:K.z.discriminatedUnion("type",[eX,e0,e1])}),rd=K.z.object({type:K.z.literal("boolean"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),default:K.z.optional(K.z.boolean())}).passthrough(),rm=K.z.object({type:K.z.literal("string"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),minLength:K.z.optional(K.z.number()),maxLength:K.z.optional(K.z.number()),format:K.z.optional(K.z.enum(["email","uri","date","date-time"]))}).passthrough(),rf=K.z.object({type:K.z.enum(["number","integer"]),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),minimum:K.z.optional(K.z.number()),maximum:K.z.optional(K.z.number())}).passthrough(),rv=K.z.object({type:K.z.literal("string"),title:K.z.optional(K.z.string()),description:K.z.optional(K.z.string()),enum:K.z.array(K.z.string()),enumNames:K.z.optional(K.z.array(K.z.string()))}).passthrough(),rg=K.z.union([rd,rm,rf,rv]),ry=er.extend({method:K.z.literal("elicitation/create"),params:ee.extend({message:K.z.string(),requestedSchema:K.z.object({type:K.z.literal("object"),properties:K.z.record(K.z.string(),rg),required:K.z.optional(K.z.array(K.z.string()))}).passthrough()})}),r_=eo.extend({action:K.z.enum(["accept","decline","cancel"]),content:K.z.optional(K.z.record(K.z.string(),K.z.unknown()))}),rE=K.z.object({type:K.z.literal("ref/resource"),uri:K.z.string()}).passthrough(),rP=K.z.object({type:K.z.literal("ref/prompt"),name:K.z.string()}).passthrough(),rb=er.extend({method:K.z.literal("completion/complete"),params:ee.extend({ref:K.z.union([rP,rE]),argument:K.z.object({name:K.z.string(),value:K.z.string()}).passthrough(),context:K.z.optional(K.z.object({arguments:K.z.optional(K.z.record(K.z.string(),K.z.string()))}))})}),rw=eo.extend({completion:K.z.object({values:K.z.array(K.z.string()).max(100),total:K.z.optional(K.z.number().int()),hasMore:K.z.optional(K.z.boolean())}).passthrough()}),rz=K.z.object({uri:K.z.string().startsWith("file://"),name:K.z.optional(K.z.string()),_meta:K.z.optional(K.z.object({}).passthrough())}).passthrough(),rS=er.extend({method:K.z.literal("roots/list")}),rR=eo.extend({roots:K.z.array(rz)}),rT=ea.extend({method:K.z.literal("notifications/roots/list_changed")});K.z.union([eT,eb,rb,ri,eY,eJ,eL,eN,eM,eQ,eG,ra,re]),K.z.union([ev,eO,eS,rT]),K.z.union([ef,rp,r_,rR]),K.z.union([eT,rh,ry,rS]),K.z.union([ev,eO,rn,eB,eV,ro,e6]),K.z.union([ef,ez,rw,e5,eZ,eU,eq,eH,rt,rr]);class rC extends Error{constructor(e,r,t){super(`MCP error ${e}: ${r}`),this.code=e,this.data=t,this.name="McpError"}}class rO{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ev,e=>{let r=this._requestHandlerAbortControllers.get(e.params.requestId);null==r||r.abort(e.params.reason)}),this.setNotificationHandler(eO,e=>{this._onprogress(e)}),this.setRequestHandler(eT,e=>({}))}_setupTimeout(e,r,t,a,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:o,onTimeout:a})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rC(t.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,t,a;this._transport=e;let o=null==(r=this.transport)?void 0:r.onclose;this._transport.onclose=()=>{null==o||o(),this._onclose()};let s=null==(t=this.transport)?void 0:t.onerror;this._transport.onerror=e=>{null==s||s(e),this._onerror(e)};let i=null==(a=this._transport)?void 0:a.onmessage;this._transport.onmessage=(e,r)=>{null==i||i(e,r),eh(e)||ed(e)?this._onresponse(e):en(e)?this._onrequest(e,r):ec(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null==(e=this.onclose)||e.call(this);let a=new rC(t.ConnectionClosed,"Connection closed");for(let e of r.values())e(a)}_onerror(e){var r;null==(r=this.onerror)||r.call(this,e)}_onnotification(e){var r;let t=null!=(r=this._notificationHandlers.get(e.method))?r:this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,r){var a,o;let s=null!=(a=this._requestHandlers.get(e.method))?a:this.fallbackRequestHandler,i=this._transport;if(void 0===s){null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:t.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);let l={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null==(o=e.params)?void 0:o._meta,sendNotification:r=>this.notification(r,{relatedRequestId:e.id}),sendRequest:(r,t,a)=>this.request(r,t,{...a,relatedRequestId:e.id}),authInfo:null==r?void 0:r.authInfo,requestId:e.id,requestInfo:null==r?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(r=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:r,jsonrpc:"2.0",id:e.id})},r=>{var a;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(r.code)?r.code:t.InternalError,message:null!=(a=r.message)?a:"Internal error"}})}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...t}=e.params,a=Number(r),o=this._progressHandlers.get(a);if(!o)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let s=this._responseHandlers.get(a),i=this._timeoutInfo.get(a);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){s(e);return}o(t)}_onresponse(e){let r=Number(e.id),t=this._responseHandlers.get(r);if(void 0===t)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),t(eh(e)?e:new rC(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await (null==(e=this._transport)?void 0:e.close())}request(e,r,a){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=null!=a?a:{};return new Promise((n,l)=>{var c,u,h,p,d,m;if(!this._transport)return void l(Error("Not connected"));(null==(c=this._options)?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),null==(u=null==a?void 0:a.signal)||u.throwIfAborted();let f=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:f};(null==a?void 0:a.onprogress)&&(this._progressHandlers.set(f,a.onprogress),v.params={...e.params,_meta:{...(null==(h=e.params)?void 0:h._meta)||{},progressToken:f}});let g=e=>{var r;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null==(r=this._transport)||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e)};this._responseHandlers.set(f,e=>{var t;if(null==(t=null==a?void 0:a.signal)||!t.aborted){if(e instanceof Error)return l(e);try{let t=r.parse(e.result);n(t)}catch(e){l(e)}}}),null==(p=null==a?void 0:a.signal)||p.addEventListener("abort",()=>{var e;g(null==(e=null==a?void 0:a.signal)?void 0:e.reason)});let y=null!=(d=null==a?void 0:a.timeout)?d:6e4;this._setupTimeout(f,y,null==a?void 0:a.maxTotalTimeout,()=>g(new rC(t.RequestTimeout,"Request timed out",{timeout:y})),null!=(m=null==a?void 0:a.resetTimeoutOnProgress)&&m),this._transport.send(v,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),l(e)})})}async notification(e,r){var t,a;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(e.method),(null!=(a=null==(t=this._options)?void 0:t.debouncedNotificationMethods)?a:[]).includes(e.method)&&!e.params&&!(null==r?void 0:r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var t;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};null==(t=this._transport)||t.send(a,r).catch(e=>this._onerror(e))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(t,a)=>Promise.resolve(r(e.parse(t),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var rx=e.i(14510);class rI extends rO{constructor(e,r){var t;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!=(t=null==r?void 0:r.capabilities)?t:{},this._ajv=new rx.default}registerCapabilities(e){var r;if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=(r=this._capabilities,Object.entries(e).reduce((e,[r,t])=>(t&&"object"==typeof t?e[r]=e[r]?{...e[r],...t}:t:e[r]=t,e),{...r}))}assertCapability(e,r){var t;if(!(null==(t=this._serverCapabilities)?void 0:t[e]))throw Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),void 0===e.sessionId)try{let t=await this.request({method:"initialize",params:{protocolVersion:W,capabilities:this._capabilities,clientInfo:this._clientInfo}},ez,r);if(void 0===t)throw Error(`Server sent invalid initialize result: ${t}`);if(!J.includes(t.protocolVersion))throw Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(t.protocolVersion),this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,t,a,o,s;switch(e){case"logging/setLevel":if(!(null==(r=this._serverCapabilities)?void 0:r.logging))throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null==(t=this._serverCapabilities)?void 0:t.prompts))throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null==(a=this._serverCapabilities)?void 0:a.resources))throw Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null==(o=this._serverCapabilities)?void 0:o.tools))throw Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null==(s=this._serverCapabilities)?void 0:s.completions))throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var r;if("notifications/roots/list_changed"===e&&!(null==(r=this._capabilities.roots)?void 0:r.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},ef,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},rw,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},ef,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},e5,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eZ,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},eU,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},eq,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},eH,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},ef,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},ef,r)}async callTool(e,r=rt,a){let o=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new rC(t.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{if(!s(o.structuredContent))throw new rC(t.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof rC)throw e;throw new rC(t.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}cacheToolOutputSchemas(e){for(let r of(this._cachedToolOutputValidators.clear(),e))if(r.outputSchema)try{let e=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let t=await this.request({method:"tools/list",params:e},rr,r);return this.cacheToolOutputSchemas(t.tools),t}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}async function rj(e){return(await r).getRandomValues(new Uint8Array(e))}async function rA(e){let r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t="",a=await rj(e);for(let o=0;o<e;o++){let e=a[o]%r.length;t+=r[e]}return t}async function rD(e){return await rA(e)}async function r$(e){return btoa(String.fromCharCode(...new Uint8Array(await (await r).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function rF(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let r=await rD(e),t=await r$(r);return{code_verifier:r,code_challenge:t}}r=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);let rk=K.z.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:K.z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),K.z.NEVER}).refine(e=>{let r=new URL(e);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rL=K.z.object({resource:K.z.string().url(),authorization_servers:K.z.array(rk).optional(),jwks_uri:K.z.string().url().optional(),scopes_supported:K.z.array(K.z.string()).optional(),bearer_methods_supported:K.z.array(K.z.string()).optional(),resource_signing_alg_values_supported:K.z.array(K.z.string()).optional(),resource_name:K.z.string().optional(),resource_documentation:K.z.string().optional(),resource_policy_uri:K.z.string().url().optional(),resource_tos_uri:K.z.string().url().optional(),tls_client_certificate_bound_access_tokens:K.z.boolean().optional(),authorization_details_types_supported:K.z.array(K.z.string()).optional(),dpop_signing_alg_values_supported:K.z.array(K.z.string()).optional(),dpop_bound_access_tokens_required:K.z.boolean().optional()}).passthrough(),rU=K.z.object({issuer:K.z.string(),authorization_endpoint:rk,token_endpoint:rk,registration_endpoint:rk.optional(),scopes_supported:K.z.array(K.z.string()).optional(),response_types_supported:K.z.array(K.z.string()),response_modes_supported:K.z.array(K.z.string()).optional(),grant_types_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),service_documentation:rk.optional(),revocation_endpoint:rk.optional(),revocation_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),introspection_endpoint:K.z.string().optional(),introspection_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),code_challenge_methods_supported:K.z.array(K.z.string()).optional()}).passthrough(),rN=K.z.object({issuer:K.z.string(),authorization_endpoint:rk,token_endpoint:rk,userinfo_endpoint:rk.optional(),jwks_uri:rk,registration_endpoint:rk.optional(),scopes_supported:K.z.array(K.z.string()).optional(),response_types_supported:K.z.array(K.z.string()),response_modes_supported:K.z.array(K.z.string()).optional(),grant_types_supported:K.z.array(K.z.string()).optional(),acr_values_supported:K.z.array(K.z.string()).optional(),subject_types_supported:K.z.array(K.z.string()),id_token_signing_alg_values_supported:K.z.array(K.z.string()),id_token_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),id_token_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),userinfo_signing_alg_values_supported:K.z.array(K.z.string()).optional(),userinfo_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),userinfo_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),request_object_signing_alg_values_supported:K.z.array(K.z.string()).optional(),request_object_encryption_alg_values_supported:K.z.array(K.z.string()).optional(),request_object_encryption_enc_values_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_methods_supported:K.z.array(K.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:K.z.array(K.z.string()).optional(),display_values_supported:K.z.array(K.z.string()).optional(),claim_types_supported:K.z.array(K.z.string()).optional(),claims_supported:K.z.array(K.z.string()).optional(),service_documentation:K.z.string().optional(),claims_locales_supported:K.z.array(K.z.string()).optional(),ui_locales_supported:K.z.array(K.z.string()).optional(),claims_parameter_supported:K.z.boolean().optional(),request_parameter_supported:K.z.boolean().optional(),request_uri_parameter_supported:K.z.boolean().optional(),require_request_uri_registration:K.z.boolean().optional(),op_policy_uri:rk.optional(),op_tos_uri:rk.optional()}).passthrough().merge(rU.pick({code_challenge_methods_supported:!0})),rq=K.z.object({access_token:K.z.string(),id_token:K.z.string().optional(),token_type:K.z.string(),expires_in:K.z.number().optional(),scope:K.z.string().optional(),refresh_token:K.z.string().optional()}).strip(),rM=K.z.object({error:K.z.string(),error_description:K.z.string().optional(),error_uri:K.z.string().optional()}),rH=K.z.object({redirect_uris:K.z.array(rk),token_endpoint_auth_method:K.z.string().optional(),grant_types:K.z.array(K.z.string()).optional(),response_types:K.z.array(K.z.string()).optional(),client_name:K.z.string().optional(),client_uri:rk.optional(),logo_uri:rk.optional(),scope:K.z.string().optional(),contacts:K.z.array(K.z.string()).optional(),tos_uri:rk.optional(),policy_uri:K.z.string().optional(),jwks_uri:rk.optional(),jwks:K.z.any().optional(),software_id:K.z.string().optional(),software_version:K.z.string().optional(),software_statement:K.z.string().optional()}).strip(),rV=K.z.object({client_id:K.z.string(),client_secret:K.z.string().optional(),client_id_issued_at:K.z.number().optional(),client_secret_expires_at:K.z.number().optional()}).strip(),rQ=rH.merge(rV);K.z.object({error:K.z.string(),error_description:K.z.string().optional()}).strip(),K.z.object({token:K.z.string(),token_type_hint:K.z.string().optional()}).strip();class rG extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class rB extends rG{}rB.errorCode="invalid_request";class rK extends rG{}rK.errorCode="invalid_client";class rW extends rG{}rW.errorCode="invalid_grant";class rJ extends rG{}rJ.errorCode="unauthorized_client";class rZ extends rG{}rZ.errorCode="unsupported_grant_type";class rY extends rG{}rY.errorCode="invalid_scope";class rX extends rG{}rX.errorCode="access_denied";class r0 extends rG{}r0.errorCode="server_error";class r1 extends rG{}r1.errorCode="temporarily_unavailable";class r2 extends rG{}r2.errorCode="unsupported_response_type";class r9 extends rG{}r9.errorCode="unsupported_token_type";class r4 extends rG{}r4.errorCode="invalid_token";class r3 extends rG{}r3.errorCode="method_not_allowed";class r5 extends rG{}r5.errorCode="too_many_requests";class r6 extends rG{}r6.errorCode="invalid_client_metadata";class r7 extends rG{}r7.errorCode="insufficient_scope";let r8={[rB.errorCode]:rB,[rK.errorCode]:rK,[rW.errorCode]:rW,[rJ.errorCode]:rJ,[rZ.errorCode]:rZ,[rY.errorCode]:rY,[rX.errorCode]:rX,[r0.errorCode]:r0,[r1.errorCode]:r1,[r2.errorCode]:r2,[r9.errorCode]:r9,[r4.errorCode]:r4,[r3.errorCode]:r3,[r5.errorCode]:r5,[r6.errorCode]:r6,[r7.errorCode]:r7};class te extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function tr(e,r){let t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function tt(e,r,t,a){let{client_id:o,client_secret:s}=r;switch(e){case"client_secret_basic":var i,n,l,c,u=o,h=s,p=t;if(!h)throw Error("client_secret_basic authentication requires a client_secret");let d=btoa(`${u}:${h}`);p.set("Authorization",`Basic ${d}`);return;case"client_secret_post":i=o,n=s,(l=a).set("client_id",i),n&&l.set("client_secret",n);return;case"none":c=o,a.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}async function ta(e){let r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=rM.parse(JSON.parse(t));return new(r8[e]||r0)(r||"",a)}catch(e){return new r0(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function to(e,r){var t,a;try{return await ts(e,r)}catch(o){if(o instanceof rK||o instanceof rJ)return await (null==(t=e.invalidateCredentials)?void 0:t.call(e,"all")),await ts(e,r);if(o instanceof rW)return await (null==(a=e.invalidateCredentials)?void 0:a.call(e,"tokens")),await ts(e,r);throw o}}async function ts(e,{serverUrl:r,authorizationCode:t,scope:a,resourceMetadataUrl:o,fetchFn:s}){let i,n;try{(i=await tl(r,{resourceMetadataUrl:o},s)).authorization_servers&&i.authorization_servers.length>0&&(n=i.authorization_servers[0])}catch(e){}n||(n=r);let l=await ti(r,e,i),c=await tp(n,{fetchFn:s}),u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==t)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let r=await tv(n,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(r),u=r}if(void 0!==t){let r=await e.codeVerifier(),a=await tm(n,{metadata:c,clientInformation:u,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(a),"AUTHORIZED"}let h=await e.tokens();if(null==h?void 0:h.refresh_token)try{let r=await tf(n,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(!(e instanceof rG)||e instanceof r0);else throw e}let p=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:m}=await td(n,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(d),"REDIRECT"}async function ti(e,r,t){let a=function(e){let r=new URL("string"==typeof e?e:e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(a,null==t?void 0:t.resource);if(t){if(!function({requestedResource:e,configuredResource:r}){let t=new URL("string"==typeof e?e:e.href),a=new URL("string"==typeof r?r:r.href);if(t.origin!==a.origin||t.pathname.length<a.pathname.length)return!1;let o=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return o.startsWith(s)}({requestedResource:a,configuredResource:t.resource}))throw Error(`Protected resource ${t.resource} does not match expected ${a} (or origin)`);return new URL(t.resource)}}function tn(e){let r=e.headers.get("WWW-Authenticate");if(!r)return;let[t,a]=r.split(" ");if("bearer"!==t.toLowerCase()||!a)return;let o=/resource_metadata="([^"]*)"/.exec(r);if(o)try{return new URL(o[1])}catch(e){return}}async function tl(e,r,t=fetch){let a=await th(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!a||404===a.status)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return rL.parse(await a.json())}async function tc(e,r,t=fetch){try{return await t(e,{headers:r})}catch(a){if(a instanceof TypeError)if(r)return tc(e,void 0,t);else return;throw a}}async function tu(e,r,t=fetch){return await tc(e,{"MCP-Protocol-Version":r},t)}async function th(e,r,t,a){var o,s,i,n;let l,c=new URL(e),u=null!=(o=null==a?void 0:a.protocolVersion)?o:W;(null==a?void 0:a.metadataUrl)?l=new URL(a.metadataUrl):(l=new URL(function(e,r="",t={}){return r.endsWith("/")&&(r=r.slice(0,-1)),t.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}(r,c.pathname),null!=(s=null==a?void 0:a.metadataServerUrl)?s:c)).search=c.search;let h=await tu(l,u,t);if(!(null==a?void 0:a.metadataUrl)&&(i=h,n=c.pathname,!i||i.status>=400&&i.status<500&&"/"!==n)){let e=new URL(`/.well-known/${r}`,c);h=await tu(e,u,t)}return h}async function tp(e,{fetchFn:r=fetch,protocolVersion:t=W}={}){var a;let o={"MCP-Protocol-Version":t};for(let{url:t,type:s}of function(e){let r="string"==typeof e?new URL(e):e,t="/"!==r.pathname,a=[];if(!t)return a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),a;let o=r.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,r.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${o}`,r.origin),type:"oidc"}),a.push({url:new URL(`${o}/.well-known/openid-configuration`,r.origin),type:"oidc"}),a}(e)){let e=await tc(t,o,r);if(e){if(!e.ok){if(e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===s?"OAuth":"OpenID provider"} metadata from ${t}`)}if("oauth"===s)return rU.parse(await e.json());{let r=rN.parse(await e.json());if(!(null==(a=r.code_challenge_methods_supported)?void 0:a.includes("S256")))throw Error(`Incompatible OIDC provider at ${t}: does not support S256 code challenge method required by MCP specification`);return r}}}}async function td(e,{metadata:r,clientInformation:t,redirectUrl:a,scope:o,state:s,resource:i}){let n,l="code",c="S256";if(r){if(n=new URL(r.authorization_endpoint),!r.response_types_supported.includes(l))throw Error(`Incompatible auth server: does not support response type ${l}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else n=new URL("/authorize",e);let u=await rF(),h=u.code_verifier,p=u.code_challenge;return n.searchParams.set("response_type",l),n.searchParams.set("client_id",t.client_id),n.searchParams.set("code_challenge",p),n.searchParams.set("code_challenge_method",c),n.searchParams.set("redirect_uri",String(a)),s&&n.searchParams.set("state",s),o&&n.searchParams.set("scope",o),(null==o?void 0:o.includes("offline_access"))&&n.searchParams.append("prompt","consent"),i&&n.searchParams.set("resource",i.href),{authorizationUrl:n,codeVerifier:h}}async function tm(e,{metadata:r,clientInformation:t,authorizationCode:a,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:n,fetchFn:l}){var c;let u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:o,redirect_uri:String(s)});n?n(p,d,e,r):tt(tr(t,null!=(c=null==r?void 0:r.token_endpoint_auth_methods_supported)?c:[]),t,p,d),i&&d.set("resource",i.href);let m=await (null!=l?l:fetch)(h,{method:"POST",headers:p,body:d});if(!m.ok)throw await ta(m);return rq.parse(await m.json())}async function tf(e,{metadata:r,clientInformation:t,refreshToken:a,resource:o,addClientAuthentication:s,fetchFn:i}){var n;let l,c="refresh_token";if(r){if(l=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:a});s?s(u,h,e,r):tt(tr(t,null!=(n=null==r?void 0:r.token_endpoint_auth_methods_supported)?n:[]),t,u,h),o&&h.set("resource",o.href);let p=await (null!=i?i:fetch)(l,{method:"POST",headers:u,body:h});if(!p.ok)throw await ta(p);return rq.parse({refresh_token:a,...await p.json()})}async function tv(e,{metadata:r,clientMetadata:t,fetchFn:a}){let o;if(r){if(!r.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");o=new URL(r.registration_endpoint)}else o=new URL("/register",e);let s=await (null!=a?a:fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw await ta(s);return rQ.parse(await s.json())}class tg extends Error{constructor(e,r,t){super(`SSE error: ${r}`),this.code=e,this.event=t}}class ty{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=null==r?void 0:r.eventSourceInit,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch}async _authThenStart(){var e;let r;if(!this._authProvider)throw new te("No auth provider");try{r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new te;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...null==(e=this._requestInit)?void 0:e.headers})}_startOrAuth(){var e,r,t;let a=null!=(t=null!=(r=null==(e=this===null||void 0===this?void 0:this._eventSourceInit)?void 0:e.fetch)?r:this._fetch)?t:fetch;return new Promise((e,r)=>{this._eventSource=new B(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let t=await this._commonHeaders();t.set("Accept","text/event-stream");let o=await a(e,{...r,headers:t});return 401===o.status&&o.headers.has("www-authenticate")&&(this._resourceMetadataUrl=tn(o)),o}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{var a;if(401===t.code&&this._authProvider)return void this._authThenStart().then(e,r);let o=new tg(t.code,t.message,t);r(o),null==(a=this.onerror)||a.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",t=>{var a;try{if(this._endpoint=new URL(t.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),null==(a=this.onerror)||a.call(this,e),this.close();return}e()}),this._eventSource.onmessage=e=>{var r,t;let a;try{a=em.parse(JSON.parse(e.data))}catch(e){null==(r=this.onerror)||r.call(this,e);return}null==(t=this.onmessage)||t.call(this,a)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new te("No auth provider");if("AUTHORIZED"!==await to(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new te("Failed to authorize")}async close(){var e,r,t;null==(e=this._abortController)||e.abort(),null==(r=this._eventSource)||r.close(),null==(t=this.onclose)||t.call(this)}async send(e){var r,t,a;if(!this._endpoint)throw Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:null==(r=this._abortController)?void 0:r.signal},s=await (null!=(t=this._fetch)?t:fetch)(this._endpoint,o);if(!s.ok){if(401===s.status&&this._authProvider){this._resourceMetadataUrl=tn(s);let r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new te;return this.send(e)}let r=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${r}`)}}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}}class t_ extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let a;super({start(o){a=f({onEvent:e=>{o.enqueue(e)},onError(r){"terminate"===e?o.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){a.feed(e)}})}}let tE={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tP extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class tb{constructor(e,r){var t;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!=(t=null==r?void 0:r.reconnectionOptions)?t:tE}async _authThenStart(){var e;let r;if(!this._authProvider)throw new te("No auth provider");try{r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null==(e=this.onerror)||e.call(this,r),r}if("AUTHORIZED"!==r)throw new te;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let t=this._normalizeHeaders(null==(e=this._requestInit)?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,a;let{resumptionToken:o}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);let s=await (null!=(r=this._fetch)?r:fetch)(this._url,{method:"GET",headers:a,signal:null==(t=this._abortController)?void 0:t.signal});if(!s.ok){if(401===s.status&&this._authProvider)return await this._authThenStart();if(405===s.status)return;throw new tP(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(e){throw null==(a=this.onerror)||a.call(this,e),e}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay;return Math.min(r*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;let a=this._reconnectionOptions.maxRetries;if(a>0&&r>=a){null==(t=this.onerror)||t.call(this,Error(`Maximum reconnection attempts (${a}) exceeded.`));return}setTimeout(()=>{this._startOrAuthSse(e).catch(t=>{var a;null==(a=this.onerror)||a.call(this,Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)})},this._getNextReconnectionDelay(r))}_handleSseStream(e,r,t){let a;if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r;(async()=>{var r,i,n,l;try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new t_).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,null==o||o(e.id)),!e.event||"message"===e.event)try{let t=em.parse(JSON.parse(e.data));void 0!==s&&eh(t)&&(t.id=s),null==(r=this.onmessage)||r.call(this,t)}catch(e){null==(i=this.onerror)||i.call(this,e)}}}catch(e){if(null==(n=this.onerror)||n.call(this,Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(e){null==(l=this.onerror)||l.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new te("No auth provider");if("AUTHORIZED"!==await to(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new te("Failed to authorize")}async close(){var e,r;null==(e=this._abortController)||e.abort(),null==(r=this.onclose)||r.call(this)}async send(e,r){var t,a,o,s;try{let{resumptionToken:s,onresumptiontoken:i}=r||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:en(e)?e.id:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:null==(t=this._abortController)?void 0:t.signal},c=await (null!=(a=this._fetch)?a:fetch)(this._url,l),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){if(401===c.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tP(401,"Server returned 401 after successful authentication");this._resourceMetadataUrl=tn(c);let r=await to(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch});if("AUTHORIZED"!==r)throw new te;return this._hasCompletedAuthFlow=!0,this.send(e)}let r=await c.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${c.status}): ${r}`)}if(this._hasCompletedAuthFlow=!1,202===c.status){eR(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var r;return null==(r=this.onerror)?void 0:r.call(this,e)});return}let h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=c.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:i},!1);else if(null==p?void 0:p.includes("application/json")){let e=await c.json();for(let r of Array.isArray(e)?e.map(e=>em.parse(e)):[em.parse(e)])null==(o=this.onmessage)||o.call(this,r)}else throw new tP(-1,`Unexpected content type: ${p}`)}catch(e){throw null==(s=this.onerror)||s.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{let t=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:t,signal:null==(e=this._abortController)?void 0:e.signal},o=await (null!=(r=this._fetch)?r:fetch)(this._url,a);if(!o.ok&&405!==o.status)throw new tP(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(e){throw null==(t=this.onerror)||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}let tw=e=>{if(!e||0===e.length)return"";let r=e.toLowerCase();return r.substring(0,1).toUpperCase()+r.substring(1,r.length)};e.s(["interpolateFunctionValue",()=>tz],43488);let tz=({value:e,args:r,thread:t,assistant:a})=>{let o=[];return{value:(e||"").replace(/{{\s*([\w-]+)\s*}}/g,(e,s)=>r&&s in r?String(r[s]):s in(t.metadata||{})?String(t.metadata[s]):"threadId"===s?t.id:"assistantId"===s?a.id:(o.push(s),`{{${s}}}`)),missing:o}};e.s(["createLog",()=>tR],18527);var tS=e.i(45076);let tR=({log:e,prisma:r})=>(0,tS.waitUntil)(new Promise(async t=>{console.log("Logging error."),await r.log.create({data:e}),console.log("Successfully logged error."),t(!0)})),tT=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{headers:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let s={},i=[];for(let[n,l]of Object.entries((({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.headers:e.transportType===a.TransportType.SSE?e.sseTransport.headers:{})({mcpServer:e}))){let e=tz({value:l,args:t,thread:r,assistant:o});s[n]=e.value,i.push(...e.missing)}return{headers:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tR({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return Object.fromEntries(Object.entries({...s,...e.metadata??{}}).map(([e,r])=>[(e=>{let r=e?.replace(/([A-Z])+/g,tw)?.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.toLowerCase())??[];return 0===r.length?"":1===r.length?r[0]:r.reduce((e,r)=>`${e}-${r.toLowerCase()}`)})(e),r]))},tC=({thread:e,mcpServer:r,assistant:t,prisma:o})=>{let{url:s,missing:i}=(({mcpServer:e,thread:r,metadata:t,assistant:o})=>{let{value:s,missing:i}=tz({value:(({mcpServer:e})=>e.transportType===a.TransportType.HTTP?e.httpTransport.url:e.transportType===a.TransportType.SSE?e.sseTransport.url:"")({mcpServer:e}),args:t,thread:r,assistant:o});return{url:s,missing:i}})({mcpServer:r,thread:e,metadata:e.metadata??{},assistant:t});if(i.length){let r=`Missing variables in MCP server: ${i.join(", ")}`;throw tR({log:{requestMethod:a.LogRequestMethod.POST,requestRoute:a.LogRequestRoute.MESSAGES,level:a.LogLevel.ERROR,status:400,message:r,workspaceId:t.workspaceId,assistantId:t.id,threadId:e.id},prisma:o}),Error(r)}return s};e.g.EventSource=B;let tO=async({mcpServer:e,thread:r,assistant:t,prisma:o})=>{let s=new rI({name:"superinterface-mcp-client",version:"1.0.0"},{capabilities:{}}),i=(({mcpServer:e,thread:r,assistant:t,prisma:o})=>{if(e.transportType===a.TransportType.STDIO)throw Error("STDIO transport is not supported.");if(e.transportType===a.TransportType.HTTP){let a=tT({thread:r,mcpServer:e,assistant:t,prisma:o});return new tb(new URL(tC({thread:r,mcpServer:e,assistant:t,prisma:o})),{requestInit:{headers:a}})}if(e.transportType===a.TransportType.SSE){let a=tC({thread:r,mcpServer:e,assistant:t,prisma:o}),s=tT({thread:r,mcpServer:e,assistant:t,prisma:o});return new ty(new URL(a),{eventSourceInit:{fetch:(({headers:e})=>(r,t)=>{let a=new Headers({...t?.headers??{},...e});return fetch(r.toString(),{...t,headers:a})})({headers:s})},requestInit:{headers:s}})}throw Error(`Unknown transport type ${e.transportType}`)})({mcpServer:e,thread:r,assistant:t,prisma:o});return await s.connect(i),{mcpConnection:{client:s,transport:i}}};e.s(["closeMcpConnection",()=>tx],10273);let tx=async({mcpConnection:e})=>{await e.client.close(),await e.transport.close()},tI=({mcpServers:e,thread:r,assistant:t,prisma:a})=>Promise.all(e.map(async e=>{let{mcpConnection:o}=await tO({mcpServer:e,thread:r,assistant:t,prisma:a}),s=await o.client.listTools();return await tx({mcpConnection:o}),s.tools.map(e=>({type:"function",function:(({tool:e})=>({name:e.name,description:e.description,parameters:e.inputSchema}))({tool:e})}))})),tj=async({assistant:e,thread:r,prisma:t})=>{let o=e.mcpServers.filter(e=>!e.computerUseTool);if(l({storageProviderType:e.storageProviderType})&&!e.modelSlug.match("computer-use")){let s=o.filter(e=>e.transportType===a.TransportType.HTTP).map(a=>({type:"mcp",mcp:{server_label:a.name??`mcp-server-${a.id}`,...a.description?{server_description:a.description}:{},server_url:tC({thread:r,mcpServer:a,assistant:e,prisma:t}),headers:tT({thread:r,mcpServer:a,assistant:e,prisma:t}),require_approval:"never"}})),i=o.filter(e=>e.transportType===a.TransportType.SSE);return[...s,...(0,h.flat)(await tI({mcpServers:i,thread:r,assistant:e,prisma:t}))]}let s=await tI({mcpServers:o,thread:r,assistant:e,prisma:t});return(0,h.flat)(s)},tA=async({assistant:e,thread:r,prisma:t})=>{let o=p.find(r=>r.type===e.modelProvider.type);return o&&o.isFunctionCallingAvailable?{tools:[...await tj({assistant:e,thread:r,prisma:t}),...e.functions.map(e=>({type:"function",function:e.openapiSpec})),...(({assistant:e})=>i({storageProviderType:e.storageProviderType})||l({storageProviderType:e.storageProviderType})?e.tools.map(r=>{if(r.type===a.ToolType.FILE_SEARCH)return i({storageProviderType:e.storageProviderType})?{type:"file_search"}:{type:"file_search",file_search:{vector_store_ids:r.fileSearchTool.vectorStoreIds,max_num_results:r.fileSearchTool.maxNumResults}};if(r.type===a.ToolType.CODE_INTERPRETER)return i({storageProviderType:e.storageProviderType})?{type:"code_interpreter"}:{type:"code_interpreter",code_interpreter:{container:{type:"auto"}}};if(r.type===a.ToolType.IMAGE_GENERATION)return{type:"image_generation",image_generation:{model:r.imageGenerationTool.model,background:r.imageGenerationTool.background.toLowerCase(),quality:r.imageGenerationTool.quality.toLowerCase(),output_format:r.imageGenerationTool.outputFormat.toLowerCase(),size:(({tool:e})=>e.imageGenerationTool.size===a.ImageGenerationToolSize.AUTO?"auto":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1024?"1024x1024":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1024_1536?"1024x1536":e.imageGenerationTool.size===a.ImageGenerationToolSize.SIZE_1536_1024?"1536x1024":void 0)({tool:r}),partial_images:r.imageGenerationTool.partialImages}};if(r.type===a.ToolType.WEB_SEARCH)return{type:"web_search"};if(r.type===a.ToolType.COMPUTER_USE)return r.computerUseTool.mcpServerId?{type:"computer_use_preview",computer_use_preview:{environment:r.computerUseTool.environment.toLowerCase(),display_width:r.computerUseTool.displayWidth,display_height:r.computerUseTool.displayHeight}}:null;return null}).filter(Boolean):[])({assistant:e,modelProviderConfig:o})]}:{}},tD=({assistant:e,prisma:r,thread:t=null})=>(0,o.supercompat)({client:(0,c.clientAdapter)({modelProvider:e.modelProvider}),storage:(({assistant:e,prisma:r})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.prismaStorageAdapter)({prisma:r});if(!i({storageProviderType:e.storageProviderType})){if(l({storageProviderType:e.storageProviderType}))return(0,o.responsesStorageAdapter)();throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,prisma:r}),runAdapter:(({assistant:e,thread:r,prisma:t})=>{if(e.storageProviderType===a.StorageProviderType.SUPERINTERFACE_CLOUD)return(0,o.completionsRunAdapter)();if(!i({storageProviderType:e.storageProviderType})){if(l({storageProviderType:e.storageProviderType}))return(0,o.responsesRunAdapter)({getOpenaiAssistant:(({assistant:e,thread:r,prisma:t})=>async({select:{id:o=!1}={}}={})=>({id:o}).id?{id:e.id}:{id:e.id,object:"assistant",created_at:(0,u.default)().unix(),model:e.modelSlug,name:e.name,instructions:e.instructions,description:null,tools:r?(await tA({assistant:e,thread:r,prisma:t}))?.tools??[]:[],metadata:{},top_p:1,temperature:1,response_format:{type:"text"},truncation_strategy:(({assistant:e})=>e.truncationType===a.TruncationType.LAST_MESSAGES?{type:"last_messages",last_messages:e.truncationLastMessagesCount}:e.truncationType===a.TruncationType.DISABLED?{type:"disabled"}:{type:"auto"})({assistant:e})})({assistant:e,thread:r,prisma:t}),waitUntil:tS.waitUntil});throw Error(`Invalid storage provider type: ${e.storageProviderType}`)}})({assistant:e,thread:t,prisma:r})})}];
|
|
6
6
|
|
|
7
7
|
//# sourceMappingURL=supercorp_superinterface_bebd2c96._.js.map
|