Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: mcp health checker tool (#2190)
Maximilian Kaskeb7026efff601
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 79bd4caa6..e7fb85bb7 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -9,6 +9,7 @@"build": "pnpm build:registry && next build","start": "next start","lint": "next lint",+ "test": "bun test","tsc": "tsc --noEmit"},"dependencies": {diff --git a/apps/web/src/app/(ai)/llms.txt/route.ts b/apps/web/src/app/(ai)/llms.txt/route.tsindex 8cd47ac0f..53c007c99 100644--- a/apps/web/src/app/(ai)/llms.txt/route.ts+++ b/apps/web/src/app/(ai)/llms.txt/route.ts@@ -72,9 +72,7 @@ export function GET() {),renderSection("Playground",- getToolsPages()- .filter((t) => t.slug !== "checker-slug")- .map((p) => toItem(p, true)),+ getToolsPages().map((p) => toItem(p, true)),),renderSection("Pages",diff --git a/apps/web/src/app/(landing)/play/mcp-health/[id]/client.tsx b/apps/web/src/app/(landing)/play/mcp-health/[id]/client.tsxnew file mode 100644index 000000000..ed66e54c8--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/[id]/client.tsx@@ -0,0 +1,20 @@+"use client";++import type { HealthCheckReport } from "@/lib/mcp/health-check";+import { ResultTableStatic, ToolsTableView, VerdictBarStatic } from "../client";++export function Table({ data }: { data: HealthCheckReport }) {+ return (+ <div className="space-y-4">+ <VerdictBarStatic report={data} />+ <ResultTableStatic report={data} />+ {data.toolsList.tools && data.toolsList.tools.length > 0 && (+ <ToolsTableView+ tools={data.toolsList.tools}+ total={data.toolsList.toolCount}+ truncated={data.toolsList.truncated}+ />+ )}+ </div>+ );+}diff --git a/apps/web/src/app/(landing)/play/mcp-health/[id]/page.tsx b/apps/web/src/app/(landing)/play/mcp-health/[id]/page.tsxnew file mode 100644index 000000000..2a30817c8--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/[id]/page.tsx@@ -0,0 +1,97 @@+import { CustomMDX } from "@/content/mdx";+import { getToolsPage } from "@/content/utils";+import { getHealthReportById } from "@/lib/mcp/health-check";+import { BASE_URL, getPageMetadata } from "@/lib/metadata/shared-metadata";+import {+ createJsonLDGraph,+ getJsonLDBreadcrumbList,+ getJsonLDWebPage,+} from "@/lib/metadata/structured-data";+import type { Metadata } from "next";+import { redirect } from "next/navigation";+import { VERDICT_LABEL, formatTimestamp } from "../utils";+import { Table } from "./client";++export async function generateMetadata({+ params,+}: {+ params: Promise<{ id: string }>;+}): Promise<Metadata | undefined> {+ const { id } = await params;+ const page = getToolsPage("mcp-health-slug");++ const metadata = {+ ...getPageMetadata(page, "play"),+ alternates: { canonical: `${BASE_URL}/play/mcp-health/${id}` },+ };++ const data = await getHealthReportById(id);+ if (!data) return metadata;++ const TITLE = data.url;+ const server = data.initialize.serverInfo+ ? `${data.initialize.serverInfo.name}@${data.initialize.serverInfo.version}`+ : "unknown";+ const DESCRIPTION = `${formatTimestamp(new Date(data.timestamp))} | Verdict: ${+ VERDICT_LABEL[data.verdict]+ } | Server: ${server}`;++ return {+ ...metadata,+ twitter: {+ ...metadata.twitter,+ images: [+ `/api/og?title=${encodeURIComponent(+ TITLE,+ )}&description=${encodeURIComponent(DESCRIPTION)}&category=mcp-health`,+ ],+ },+ openGraph: {+ ...metadata.openGraph,+ images: [+ `/api/og?title=${encodeURIComponent(+ TITLE,+ )}&description=${encodeURIComponent(DESCRIPTION)}&category=mcp-health`,+ ],+ },+ };+}++export default async function Page({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;+ const page = getToolsPage("mcp-health-slug");++ const data = await getHealthReportById(id);+ if (!data) redirect("/play/mcp-health");++ const jsonLDGraph = createJsonLDGraph([+ getJsonLDWebPage(page),+ getJsonLDBreadcrumbList([+ { name: "Home", url: BASE_URL },+ { name: "Playground", url: `${BASE_URL}/play` },+ { name: "MCP Server Health Check", url: `${BASE_URL}/play/mcp-health` },+ { name: data.url, url: `${BASE_URL}/play/mcp-health/${id}` },+ ]),+ ]);++ return (+ <section className="prose dark:prose-invert max-w-none">+ <script+ type="application/ld+json"+ suppressHydrationWarning+ // biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>+ dangerouslySetInnerHTML={{+ __html: JSON.stringify(jsonLDGraph).replace(/</g, "\\u003c"),+ }}+ />+ <h1>{data.url}</h1>+ <p className="text-lg">{formatTimestamp(new Date(data.timestamp))}</p>+ <Table data={data} />+ <CustomMDX source={page.content} />+ </section>+ );+}diff --git a/apps/web/src/app/(landing)/play/mcp-health/api/route.ts b/apps/web/src/app/(landing)/play/mcp-health/api/route.tsnew file mode 100644index 000000000..5a33b20b6--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/api/route.ts@@ -0,0 +1,193 @@+import {+ type HealthCheckReport,+ normalizeUrlForStorage,+ runMcpHealthCheck,+ storeHealthReport,+ toPersistedReport,+} from "@/lib/mcp/health-check";+import { getClientIP, ratelimit } from "@/lib/ratelimit";+import { Events, setupAnalytics } from "@openstatus/analytics";+import { assertSafeUrlSync } from "@openstatus/utils";+import { after } from "next/server";+import { z } from "zod";++export const runtime = "edge";+// Worst-case 16s of step time + metadata fetch + analytics; give some slack.+export const maxDuration = 30;++const RATE_LIMIT_WINDOW = 60;+const MAX_REQUESTS_PER_WINDOW = 3;++const requestSchema = z.object({+ url: z.url("Invalid URL format"),+ headers: z+ .array(z.object({ key: z.string().max(256), value: z.string().max(2048) }))+ .max(20)+ .optional(),+});++type ErrorCode =+ | "RATE_LIMIT_EXCEEDED"+ | "INVALID_REQUEST"+ | "NO_CLIENT_IP"+ | "INTERNAL_ERROR";++function errorResponse(+ code: ErrorCode,+ error: string,+ status: number,+ details?: Record<string, unknown>,+ headers?: Record<string, string>,+) {+ return new Response(JSON.stringify({ error, code, ...details }), {+ status,+ headers: { "Content-Type": "application/json", ...headers },+ });+}++function authMechanismOf(report: HealthCheckReport) {+ if (report.verdict !== "auth-required") return undefined;+ return report.authChallenge?.mechanism ?? "unknown";+}++export async function POST(request: Request) {+ let parsed: z.infer<typeof requestSchema>;+ try {+ const json = await request.json();+ const result = requestSchema.safeParse(json);+ if (!result.success) {+ return errorResponse("INVALID_REQUEST", "Invalid request format", 400, {+ details: {+ issues: result.error.issues.map((issue) => ({+ field: issue.path.join("."),+ message: issue.message,+ })),+ },+ });+ }+ parsed = result.data;+ } catch {+ return errorResponse(+ "INVALID_REQUEST",+ "Invalid JSON in request body",+ 400,+ );+ }++ try {+ // protocol check + private/loopback/metadata-host block. Throws on bad input.+ assertSafeUrlSync(parsed.url);+ } catch (err) {+ return errorResponse(+ "INVALID_REQUEST",+ err instanceof Error ? err.message : "Invalid URL",+ 400,+ );+ }+ const urlObject = new URL(parsed.url);+ if (+ urlObject.hostname.toLowerCase().endsWith("openstatus.dev") &&+ urlObject.pathname.startsWith("/play/mcp-health/api")+ ) {+ return errorResponse(+ "INVALID_REQUEST",+ "Self-requests are not allowed",+ 400,+ );+ }++ const blacklistPatterns = (process.env.BLACKLIST_URL ?? "")+ .split(",")+ .map((p) => p.trim())+ .filter(Boolean);+ for (const pattern of blacklistPatterns) {+ let matches = false;+ try {+ matches = new RegExp(pattern).test(parsed.url);+ } catch (error) {+ // skip the bad pattern so it can't silently disable the whole guard+ console.error("Invalid blacklist pattern", pattern, error);+ continue;+ }+ if (matches) {+ return errorResponse("INVALID_REQUEST", "This URL is not allowed", 403);+ }+ }++ const clientIP = getClientIP(request.headers);+ if (!clientIP) {+ return errorResponse(+ "NO_CLIENT_IP",+ "Unable to determine client IP address",+ 400,+ );+ }++ const rl = await ratelimit(`play-mcp-health:${clientIP}`, {+ window: RATE_LIMIT_WINDOW,+ limit: MAX_REQUESTS_PER_WINDOW,+ });+ if (!rl.success) {+ return errorResponse(+ "RATE_LIMIT_EXCEEDED",+ `You have exceeded the rate limit of ${MAX_REQUESTS_PER_WINDOW} requests per ${RATE_LIMIT_WINDOW} seconds`,+ 429,+ { limit: rl.limit, remaining: rl.remaining, reset: rl.reset },+ {+ "X-RateLimit-Limit": rl.limit.toString(),+ "X-RateLimit-Remaining": rl.remaining.toString(),+ "X-RateLimit-Reset": rl.reset.toString(),+ "Retry-After": Math.ceil((rl.reset - Date.now()) / 1000).toString(),+ },+ );+ }++ let report: HealthCheckReport;+ try {+ report = await runMcpHealthCheck({+ url: parsed.url,+ headers: parsed.headers,+ });+ } catch (error) {+ console.error("mcp-health runner failed", error);+ return errorResponse(+ "INTERNAL_ERROR",+ "Health check failed unexpectedly",+ 500,+ );+ }++ const id = crypto.randomUUID().replace(/-/g, "");+ const persisted = toPersistedReport(report);++ after(async () => {+ try {+ await storeHealthReport(id, persisted);+ } catch (error) {+ console.error("mcp-health redis store failed", error);+ }+ try {+ const analytics = await setupAnalytics({});+ await analytics.track({+ ...Events.MCPHealthCheck,+ url: normalizeUrlForStorage(parsed.url),+ uuid: id,+ verdict: persisted.verdict,+ authMechanism: authMechanismOf(persisted),+ });+ } catch (error) {+ console.error("mcp-health analytics failed", error);+ }+ });++ return Response.json(+ { id, report: persisted },+ {+ headers: {+ "X-RateLimit-Limit": rl.limit.toString(),+ "X-RateLimit-Remaining": rl.remaining.toString(),+ "X-RateLimit-Reset": rl.reset.toString(),+ },+ },+ );+}diff --git a/apps/web/src/app/(landing)/play/mcp-health/client.tsx b/apps/web/src/app/(landing)/play/mcp-health/client.tsxnew file mode 100644index 000000000..b3a42c8c1--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/client.tsx@@ -0,0 +1,746 @@+"use client";++import type {+ HealthCheckReport,+ StepResult,+ ToolInfo,+} from "@/lib/mcp/health-check";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import { Button } from "@openstatus/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@openstatus/ui/components/ui/dialog";+import { Input } from "@openstatus/ui/components/ui/input";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@openstatus/ui/components/ui/tabs";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useQueryStates } from "nuqs";+import {+ Fragment,+ createContext,+ useContext,+ useEffect,+ useState,+ useTransition,+} from "react";+import { searchParamsParsers } from "./search-params";+import {+ STEP_REQUEST_BODIES,+ type StepKey,+ VERDICT_DOT,+ VERDICT_LABEL,+ formatResponseBody,+ originOf,+ statusDotClass,+} from "./utils";++const SAMPLE_URLS = ["https://hf.co/mcp", "https://mcp.context7.com/mcp"];++type HeaderRow = { key: string; value: string };++type ApiResponse =+ | { id: string; report: HealthCheckReport }+ | { error: string; code: string; details?: unknown };++type McpHealthContextType = {+ report: HealthCheckReport | null;+ setReport: React.Dispatch<React.SetStateAction<HealthCheckReport | null>>;+ id: string | null;+ setId: (next: string | null) => void;+};++const McpHealthContext = createContext<McpHealthContextType | null>(null);++export function McpHealthProvider({+ children,+ defaultReport = null,+}: {+ children: React.ReactNode;+ defaultReport?: HealthCheckReport | null;+}) {+ const [report, setReport] = useState<HealthCheckReport | null>(defaultReport);+ const [{ id: urlId }, setSearchParams] = useQueryStates(searchParamsParsers);+ const [id, setLocalId] = useState<string | null>(urlId);++ useEffect(() => {+ setLocalId(urlId);+ }, [urlId]);++ const setId: McpHealthContextType["setId"] = (next) => {+ setLocalId(next);+ void setSearchParams({ id: next });+ };++ return (+ <McpHealthContext.Provider value={{ report, setReport, id, setId }}>+ {children}+ </McpHealthContext.Provider>+ );+}++function useMcpHealthContext() {+ const context = useContext(McpHealthContext);+ if (!context) {+ throw new Error(+ "useMcpHealthContext must be used within a McpHealthProvider",+ );+ }+ return context;+}++export function Form({ defaultUrl = "" }: { defaultUrl?: string }) {+ const { setReport, setId } = useMcpHealthContext();+ const [headers, setHeaders] = useState<HeaderRow[]>([]);+ const [isPending, startTransition] = useTransition();+ const router = useRouter();++ function handleSubmit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ const formData = new FormData(event.target as HTMLFormElement);+ const url = String(formData.get("url") ?? "").trim();+ if (!url) {+ toast.error("Enter an MCP server URL");+ return;+ }+ try {+ new URL(url);+ } catch {+ toast.error("Invalid URL");+ return;+ }++ setReport(null);+ setId(null);++ startTransition(async () => {+ const toastId = toast.loading("Running MCP handshake...", {+ duration: Number.POSITIVE_INFINITY,+ closeButton: false,+ });+ try {+ const res = await fetch("/play/mcp-health/api", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ url,+ headers: headers.filter((h) => h.key.trim()),+ }),+ });+ const data = (await res.json()) as ApiResponse;+ if (!res.ok || "error" in data) {+ const msg =+ "error" in data ? data.error : `Request failed (${res.status})`;+ toast.error(msg, { id: toastId, className: "text-destructive!" });+ return;+ }+ setReport(data.report);+ setId(data.id);+ toast.success(`Check complete: ${VERDICT_LABEL[data.report.verdict]}`, {+ id: toastId,+ description: "View full request/response per step.",+ action: {+ label: "Details",+ onClick: () => router.push(`/play/mcp-health/${data.id}`),+ },+ duration: 4000,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : "Network error";+ toast.error(msg, { id: toastId, className: "text-destructive!" });+ }+ });+ }++ return (+ <form onSubmit={handleSubmit}>+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-5">+ <div className="col-span-3 md:col-span-4">+ <Input+ name="url"+ placeholder="https://example.com/mcp"+ className="h-auto! rounded-none p-4 text-base md:text-base"+ defaultValue={defaultUrl}+ autoComplete="off"+ spellCheck={false}+ inputMode="url"+ required+ />+ </div>+ <div className="col-span-3 sm:col-span-1">+ <Button+ type="submit"+ variant="default"+ className="h-full w-full rounded-none p-4 text-base"+ disabled={isPending}+ >+ {isPending ? "Submitting..." : "Submit"}+ </Button>+ </div>+ </div>+ <SampleHint />+ <HeadersEditor+ headers={headers}+ setHeaders={setHeaders}+ disabled={isPending}+ />+ </form>+ );+}++function HeadersEditor({+ headers,+ setHeaders,+ disabled,+}: {+ headers: HeaderRow[];+ setHeaders: React.Dispatch<React.SetStateAction<HeaderRow[]>>;+ disabled?: boolean;+}) {+ return (+ <div>+ <p className="text-muted-foreground text-sm">+ <code>Content-Type: application/json</code> and{" "}+ <code>Accept: application/json, text/event-stream</code> are sent on+ every request.+ </p>+ <div className="grid grid-cols-5 gap-2">+ <Button+ type="button"+ variant="outline"+ className="col-span-2 h-auto! rounded-none p-3 text-base"+ onClick={() => setHeaders((h) => [...h, { key: "", value: "" }])}+ disabled={disabled}+ >+ Add header+ </Button>+ <div className="col-span-3" />+ {headers.map((header, index) => (+ <Fragment key={index}>+ <Input+ placeholder="Key (e.g. Authorization)"+ className="col-span-2 h-auto! rounded-none p-3 text-base md:text-base"+ value={header.key}+ onChange={(e) =>+ setHeaders((rows) =>+ rows.map((h, i) =>+ i === index ? { ...h, key: e.target.value } : h,+ ),+ )+ }+ disabled={disabled}+ />+ <Input+ placeholder="Value"+ className="col-span-2 h-auto! rounded-none p-3 text-base md:text-base"+ value={header.value}+ onChange={(e) =>+ setHeaders((rows) =>+ rows.map((h, i) =>+ i === index ? { ...h, value: e.target.value } : h,+ ),+ )+ }+ disabled={disabled}+ />+ <Button+ type="button"+ variant="ghost"+ className="h-full w-full rounded-none p-3 text-base"+ onClick={() =>+ setHeaders((rows) => rows.filter((_, i) => i !== index))+ }+ disabled={disabled}+ >+ Remove+ </Button>+ </Fragment>+ ))}+ </div>+ </div>+ );+}++export function SampleHint() {+ return (+ <p className="text-muted-foreground text-sm">+ No idea where to start? Try{" "}+ {SAMPLE_URLS.map((url, i) => (+ <Fragment key={url}>+ {i > 0 && (i === SAMPLE_URLS.length - 1 ? " or " : ", ")}+ <button+ type="button"+ className="underline underline-offset-2"+ onClick={() => {+ const input =+ document.querySelector<HTMLInputElement>("input[name='url']");+ if (input) input.value = url;+ }}+ >+ <code>{url}</code>+ </button>+ </Fragment>+ ))}+ .+ </p>+ );+}++export function ResultTable() {+ const { report } = useMcpHealthContext();+ return <ResultTableStatic report={report} />;+}++export function ResultTableStatic({+ report,+}: {+ report: HealthCheckReport | null;+}) {+ const steps = report ? toStepRows(report) : EMPTY_STEPS;+ const okCount = steps.filter((s) => s.step.ok).length;++ return (+ <div className="table-wrapper">+ <table>+ <thead>+ <tr>+ <th className="w-12" />+ <th>Step</th>+ <th>Latency</th>+ <th>Notes</th>+ </tr>+ </thead>+ <tbody>+ {steps.map(({ key, label, step, note }) => {+ const row = (+ <tr+ key={key}+ className={report ? "cursor-pointer hover:bg-muted/50" : ""}+ >+ <td>+ <StatusDot input={report ? step : null} />+ </td>+ <td>{label}</td>+ <td>+ {report && step.latencyMs > 0 ? `${step.latencyMs}ms` : "—"}+ </td>+ <td>{note ?? "—"}</td>+ </tr>+ );+ return report ? (+ <StepDialog+ key={key}+ stepKey={key}+ label={label}+ step={step}+ report={report}+ >+ {row}+ </StepDialog>+ ) : (+ <Fragment key={key}>{row}</Fragment>+ );+ })}+ </tbody>+ <caption>+ {report+ ? `${VERDICT_LABEL[report.verdict]} — ${okCount} / ${steps.length} steps OK${+ report.initialize.serverInfo+ ? ` · ${report.initialize.serverInfo.name}@${report.initialize.serverInfo.version}`+ : ""+ } · click a row for the JSON-RPC request and response`+ : "Run a check to see results."}+ </caption>+ </table>+ </div>+ );+}++function StepDialog({+ stepKey,+ label,+ step,+ report,+ children,+}: {+ stepKey: StepKey;+ label: string;+ step: StepResult;+ report: HealthCheckReport;+ children: React.ReactNode;+}) {+ const requestBody = STEP_REQUEST_BODIES[stepKey];+ const extras = stepDetailRows(stepKey, report);+ return (+ <Dialog>+ <DialogTrigger asChild>{children}</DialogTrigger>+ <DialogContent className="max-h-[90vh] overflow-y-auto overflow-x-hidden rounded-none! font-mono sm:max-w-5xl">+ <DialogHeader>+ <DialogTitle>{label}</DialogTitle>+ <DialogDescription>+ JSON-RPC request and the response captured during the handshake.+ </DialogDescription>+ </DialogHeader>+ <div className="prose dark:prose-invert min-w-0 max-w-none">+ <table>+ <tbody>+ <tr>+ <td>Status</td>+ <td>{step.ok ? "OK" : step.error?.code ?? "failed"}</td>+ </tr>+ <tr>+ <td>Latency</td>+ <td>{step.latencyMs > 0 ? `${step.latencyMs}ms` : "—"}</td>+ </tr>+ {extras.map(([k, v]) => (+ <tr key={k}>+ <td>{k}</td>+ <td className="break-words">{v}</td>+ </tr>+ ))}+ {step.error && (+ <tr>+ <td>Error</td>+ <td className="break-words">+ {step.error.code}: {step.error.message}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ <Tabs defaultValue="response">+ <TabsList className="h-auto w-full rounded-none">+ <TabsTrigger+ value="response"+ className="h-auto w-full truncate rounded-none p-4"+ >+ Response+ </TabsTrigger>+ <TabsTrigger+ value="request"+ className="h-auto w-full truncate rounded-none p-4"+ >+ Request+ </TabsTrigger>+ </TabsList>+ <TabsContent value="response" className="min-w-0 overflow-x-auto">+ <pre className="my-0! whitespace-pre-wrap break-words">+ <code className="block break-words">+ {formatResponseBody(step.rawBody) || "(no body captured)"}+ </code>+ </pre>+ </TabsContent>+ <TabsContent value="request" className="min-w-0 overflow-x-auto">+ <pre className="my-0! whitespace-pre-wrap break-words">+ <code className="block break-words">+ {JSON.stringify(requestBody, null, 2)}+ </code>+ </pre>+ </TabsContent>+ </Tabs>+ </div>+ </DialogContent>+ </Dialog>+ );+}++export function AuthChallengeCallout() {+ const { report } = useMcpHealthContext();+ if (!report || report.verdict !== "auth-required" || !report.authChallenge) {+ return null;+ }+ const challenge = report.authChallenge;+ const as = challenge.authorizationServer;+ return (+ <blockquote>+ <p>+ <strong>Authentication required.</strong>{" "}+ {challenge.mechanism === "oauth"+ ? "This server uses OAuth-based MCP authentication."+ : challenge.mechanism === "bearer-static"+ ? "This server expects a static Bearer token in the Authorization header."+ : "This server returned 401 without a parseable challenge — try adding an Authorization header."}+ </p>+ {as && (+ <p>+ Authorization server: <code>{as}</code>{" "}+ <a href={originOf(as)} target="_blank" rel="noreferrer noopener">+ (open ↗)+ </a>+ </p>+ )}+ {challenge.scopes && challenge.scopes.length > 0 && (+ <p>+ Scopes: <code>{challenge.scopes.join(" ")}</code>+ </p>+ )}+ </blockquote>+ );+}++export function DetailsButtonLink() {+ const { report, id } = useMcpHealthContext();+ if (!report || !id) return null;+ return (+ <Button+ variant="default"+ className="h-auto! flex-1 rounded-none p-4 text-base"+ asChild+ >+ <Link+ href={`/play/mcp-health/${id}`}+ className="no-underline! w-full text-background!"+ >+ Share this report+ </Link>+ </Button>+ );+}++export function ToolsTable() {+ const { report } = useMcpHealthContext();+ if (!report?.toolsList.tools || report.toolsList.tools.length === 0) {+ return null;+ }+ return (+ <ToolsTableView+ tools={report.toolsList.tools}+ total={report.toolsList.toolCount}+ truncated={report.toolsList.truncated}+ />+ );+}++export function ToolsTableView({+ tools,+ total,+ truncated,+}: {+ tools: ToolInfo[];+ total?: number;+ truncated?: boolean;+}) {+ if (tools.length === 0) return null;+ return (+ <div>+ {tools.map((t) => {+ const hints = annotationHints(t.annotations);+ return (+ <details key={t.name}>+ <summary>+ {t.name}+ {t.title ? (+ <span className="text-muted-foreground"> — {t.title}</span>+ ) : null}+ </summary>+ <p>{t.description ?? "—"}</p>+ {hints.length > 0 && (+ <ul className=" text-muted-foreground text-sm">+ {hints.map((h: string) => (+ <li key={h}>{h}</li>+ ))}+ </ul>+ )}+ </details>+ );+ })}+ <p className="text-muted-foreground text-sm">+ {truncated+ ? `Showing first ${tools.length} of ${total ?? tools.length} tools`+ : `${tools.length} ${tools.length === 1 ? "tool" : "tools"}`}+ </p>+ </div>+ );+}++function stepDetailRows(+ stepKey: StepKey,+ report: HealthCheckReport,+): [string, string][] {+ if (stepKey === "initialize") {+ const init = report.initialize;+ const rows: [string, string][] = [];+ if (init.protocolVersion) rows.push(["Protocol", init.protocolVersion]);+ if (init.serverInfo) {+ rows.push([+ "Server",+ `${init.serverInfo.name}@${init.serverInfo.version}`,+ ]);+ }+ if (typeof init.hasSessionId === "boolean") {+ rows.push(["Session ID", init.hasSessionId ? "yes" : "no"]);+ }+ if (init.capabilities) {+ const keys = Object.keys(init.capabilities);+ if (keys.length > 0) rows.push(["Capabilities", keys.join(", ")]);+ }+ return rows;+ }+ if (stepKey === "toolsList") {+ const t = report.toolsList;+ const rows: [string, string][] = [];+ if (typeof t.toolCount === "number") {+ rows.push(["Tools", String(t.toolCount)]);+ }+ if (t.truncated) rows.push(["Truncated", "yes"]);+ return rows;+ }+ return [];+}++function annotationHints(ann: ToolInfo["annotations"]): string[] {+ if (!ann) return [];+ const hints: string[] = [];+ if (ann.readOnlyHint === true) hints.push("read-only");+ if (ann.destructiveHint === true) hints.push("destructive");+ if (ann.idempotentHint === true) hints.push("idempotent");+ if (ann.openWorldHint === true) hints.push("open-world");+ return hints;+}++type StepRow = {+ key: "initialize" | "ping" | "toolsList";+ label: string;+ step: StepResult;+ note: string | null;+};++function toStepRows(report: HealthCheckReport): StepRow[] {+ return [+ {+ key: "initialize",+ label: "1. initialize",+ step: report.initialize,+ note: noteFor(report.initialize, {+ protocol: report.initialize.protocolVersion,+ }),+ },+ {+ key: "ping",+ label: "2. ping",+ step: report.ping,+ note: noteFor(report.ping),+ },+ {+ key: "toolsList",+ label: "3. tools/list",+ step: report.toolsList,+ note:+ noteFor(report.toolsList) ??+ (typeof report.toolsList.toolCount === "number"+ ? `${report.toolsList.toolCount} ${report.toolsList.toolCount === 1 ? "tool" : "tools"}`+ : null),+ },+ ];+}++function noteFor(+ step: StepResult,+ extras?: { protocol?: string },+): string | null {+ if (step.error) return step.error.code;+ if (extras?.protocol) return `protocol ${extras.protocol}`;+ return null;+}++const EMPTY_STEPS: StepRow[] = [+ {+ key: "initialize",+ label: "1. initialize",+ step: { ok: false, latencyMs: 0 },+ note: null,+ },+ {+ key: "ping",+ label: "2. ping",+ step: { ok: false, latencyMs: 0 },+ note: null,+ },+ {+ key: "toolsList",+ label: "3. tools/list",+ step: { ok: false, latencyMs: 0 },+ note: null,+ },+];++function statusDotLabel(input: boolean | null | StepResult): string {+ if (input === null) return "not run";+ if (typeof input === "boolean") return input ? "ok" : "failed";+ if (input.ok) return "ok";+ return input.error?.code ?? "failed";+}++function StatusDot({ input }: { input: boolean | null | StepResult }) {+ const label = statusDotLabel(input);+ return (+ <div+ role="img"+ aria-label={label}+ title={label}+ className={cn("size-4", statusDotClass(input))}+ />+ );+}++export function VerdictBar() {+ const { report } = useMcpHealthContext();+ if (!report) return <VerdictLegend />;+ return <VerdictBarStatic report={report} />;+}++export function VerdictBarStatic({ report }: { report: HealthCheckReport }) {+ return (+ <div className="flex flex-wrap gap-2">+ <VerdictLegend />+ {report.initialize.serverInfo && (+ <span className="text-muted-foreground">+ · {report.initialize.serverInfo.name}@+ {report.initialize.serverInfo.version}+ </span>+ )}+ {report.initialize.protocolVersion && (+ <span className="text-muted-foreground">+ · protocol {report.initialize.protocolVersion}+ </span>+ )}+ {typeof report.toolsList.toolCount === "number" && (+ <span className="text-muted-foreground">+ · {report.toolsList.toolCount}{" "}+ {report.toolsList.toolCount === 1 ? "tool" : "tools"}+ </span>+ )}+ </div>+ );+}++export function VerdictLegend() {+ const verdicts: HealthCheckReport["verdict"][] = [+ "healthy",+ "partial",+ "auth-required",+ "unreachable",+ ];+ return (+ <div className="flex flex-wrap gap-2">+ {verdicts.map((v) => (+ <div+ key={v}+ className={cn("text-background text-base", VERDICT_DOT[v])}+ >+ {VERDICT_LABEL[v]}+ </div>+ ))}+ </div>+ );+}diff --git a/apps/web/src/app/(landing)/play/mcp-health/page.tsx b/apps/web/src/app/(landing)/play/mcp-health/page.tsxnew file mode 100644index 000000000..2a4dbe54c--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/page.tsx@@ -0,0 +1,75 @@+import { CustomMDX } from "@/content/mdx";+import { getToolsPage } from "@/content/utils";+import { getHealthReportById } from "@/lib/mcp/health-check";+import { BASE_URL, getPageMetadata } from "@/lib/metadata/shared-metadata";+import {+ createJsonLDGraph,+ getJsonLDBreadcrumbList,+ getJsonLDFAQPage,+ getJsonLDHowTo,+ getJsonLDWebPage,+} from "@/lib/metadata/structured-data";+import type { Metadata } from "next";+import {+ AuthChallengeCallout,+ DetailsButtonLink,+ Form,+ McpHealthProvider,+ ResultTable,+ ToolsTable,+ VerdictBar,+} from "./client";+import { searchParamsCache } from "./search-params";++export function generateMetadata(): Metadata {+ const page = getToolsPage("mcp-health");+ return getPageMetadata(page, "play");+}++export default async function Page(props: {+ searchParams: Promise<{ id?: string }>;+}) {+ const page = getToolsPage("mcp-health");++ const searchParams = await props.searchParams;+ const { id } = searchParamsCache.parse(searchParams);++ const sharedReport = id ? await getHealthReportById(id) : null;++ const jsonLDGraph = createJsonLDGraph([+ getJsonLDWebPage(page),+ getJsonLDBreadcrumbList([+ { name: "Home", url: BASE_URL },+ { name: "Playground", url: `${BASE_URL}/play` },+ { name: page.metadata.title, url: `${BASE_URL}/play/mcp-health` },+ ]),+ getJsonLDFAQPage(page),+ getJsonLDHowTo(page),+ ]);++ return (+ <section className="prose dark:prose-invert max-w-none">+ <script+ type="application/ld+json"+ suppressHydrationWarning+ // biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>+ dangerouslySetInnerHTML={{+ __html: JSON.stringify(jsonLDGraph).replace(/</g, "\\u003c"),+ }}+ />+ <h1>{page.metadata.title}</h1>+ <p className="text-lg">{page.metadata.description}</p>+ <McpHealthProvider defaultReport={sharedReport}>+ <Form defaultUrl={sharedReport?.url ?? ""} />+ <VerdictBar />+ <ResultTable />+ <AuthChallengeCallout />+ <ToolsTable />+ <div className="flex w-full gap-2">+ <DetailsButtonLink />+ </div>+ </McpHealthProvider>+ <CustomMDX source={page.content} />+ </section>+ );+}diff --git a/apps/web/src/app/(landing)/play/mcp-health/search-params.ts b/apps/web/src/app/(landing)/play/mcp-health/search-params.tsnew file mode 100644index 000000000..fc70c0e3c--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/search-params.ts@@ -0,0 +1,7 @@+import { createSearchParamsCache, parseAsString } from "nuqs/server";++export const searchParamsParsers = {+ id: parseAsString,+};++export const searchParamsCache = createSearchParamsCache(searchParamsParsers);diff --git a/apps/web/src/app/(landing)/play/mcp-health/utils.test.ts b/apps/web/src/app/(landing)/play/mcp-health/utils.test.tsnew file mode 100644index 000000000..3637e9200--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/utils.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from "bun:test";+import {+ formatResponseBody,+ formatTimestamp,+ originOf,+ statusDotClass,+} from "./utils";++describe("statusDotClass", () => {+ test("null → muted", () => {+ expect(statusDotClass(null)).toBe("bg-muted-foreground/30");+ });+ test("true → success", () => {+ expect(statusDotClass(true)).toBe("bg-success");+ });+ test("false → destructive", () => {+ expect(statusDotClass(false)).toBe("bg-destructive");+ });+ test("StepResult ok=true → success", () => {+ expect(statusDotClass({ ok: true, latencyMs: 10 })).toBe("bg-success");+ });+ test("StepResult ok=false UNAUTHORIZED → info", () => {+ expect(+ statusDotClass({+ ok: false,+ latencyMs: 10,+ error: { code: "UNAUTHORIZED", message: "401" },+ }),+ ).toBe("bg-info");+ });+ test("StepResult ok=false other error → destructive", () => {+ expect(+ statusDotClass({+ ok: false,+ latencyMs: 10,+ error: { code: "TIMEOUT", message: "timed out" },+ }),+ ).toBe("bg-destructive");+ });+});++describe("originOf", () => {+ test("strips path, query, fragment", () => {+ expect(originOf("https://example.com/api?x=1#frag")).toBe(+ "https://example.com",+ );+ });+ test("keeps explicit port", () => {+ expect(originOf("https://example.com:8443/mcp")).toBe(+ "https://example.com:8443",+ );+ });+ test("strips userinfo", () => {+ expect(originOf("https://user:[email protected]/mcp")).toBe(+ "https://example.com",+ );+ });+ test("invalid URL returns input unchanged", () => {+ expect(originOf("not a url")).toBe("not a url");+ });+});++describe("formatTimestamp", () => {+ test("returns a non-empty string with the date parts", () => {+ const out = formatTimestamp(new Date("2026-05-22T10:15:30Z"));+ expect(out.length).toBeGreaterThan(0);+ // en-US "long" month locale-independent enough to assert "2026" presence+ expect(out).toContain("2026");+ expect(out).toContain("May");+ });+});++describe("formatResponseBody", () => {+ test("undefined input → empty string", () => {+ expect(formatResponseBody(undefined)).toBe("");+ });++ test("empty / whitespace input → returns raw unchanged", () => {+ expect(formatResponseBody(" ")).toBe(" ");+ });++ test("valid JSON → pretty-printed with 2-space indent", () => {+ const out = formatResponseBody('{"jsonrpc":"2.0","id":"x","result":{}}');+ expect(out).toBe(+ JSON.stringify({ jsonrpc: "2.0", id: "x", result: {} }, null, 2),+ );+ });++ test("single SSE frame → pretty-printed JSON payload", () => {+ const sse = [+ "event: message",+ 'data: {"jsonrpc":"2.0","id":"x","result":{"ok":true}}',+ "",+ ].join("\n");+ const out = formatResponseBody(sse);+ expect(out).toBe(+ JSON.stringify(+ { jsonrpc: "2.0", id: "x", result: { ok: true } },+ null,+ 2,+ ),+ );+ });++ test("multiple SSE frames → joined with blank line", () => {+ const sse = [+ "event: message",+ 'data: {"jsonrpc":"2.0","id":1}',+ "",+ "event: message",+ 'data: {"jsonrpc":"2.0","id":2}',+ "",+ ].join("\n");+ const out = formatResponseBody(sse);+ expect(out).toBe(+ [+ JSON.stringify({ jsonrpc: "2.0", id: 1 }, null, 2),+ JSON.stringify({ jsonrpc: "2.0", id: 2 }, null, 2),+ ].join("\n\n"),+ );+ });++ test("SSE data spanning two `data:` lines → joined with newline before parse", () => {+ const sse = ['data: {"a":', "data: 1}", ""].join("\n");+ const out = formatResponseBody(sse);+ expect(out).toBe(JSON.stringify({ a: 1 }, null, 2));+ });++ test("non-JSON HTML → passed through unchanged", () => {+ const html = "<!doctype html><html>nope</html>";+ expect(formatResponseBody(html)).toBe(html);+ });++ test("truncation marker preserved on JSON path", () => {+ const raw = `${JSON.stringify({ id: "x" })}…[truncated]`;+ const out = formatResponseBody(raw);+ expect(out.startsWith(JSON.stringify({ id: "x" }, null, 2))).toBe(true);+ expect(out.endsWith("\n…[truncated]")).toBe(true);+ });++ test("truncation marker preserved on SSE path", () => {+ const raw = `${["event: message", 'data: {"id":"x"}', "", ""].join("\n")}…[truncated]`;+ const out = formatResponseBody(raw);+ expect(out.endsWith("\n…[truncated]")).toBe(true);+ expect(out).toContain(JSON.stringify({ id: "x" }, null, 2));+ });+});diff --git a/apps/web/src/app/(landing)/play/mcp-health/utils.ts b/apps/web/src/app/(landing)/play/mcp-health/utils.tsnew file mode 100644index 000000000..2080daa34--- /dev/null+++ b/apps/web/src/app/(landing)/play/mcp-health/utils.ts@@ -0,0 +1,106 @@+import type { HealthCheckReport, StepResult } from "@/lib/mcp/health-check";++export { STEP_REQUEST_BODIES, type StepKey } from "@/lib/mcp/protocol";++export const VERDICT_LABEL: Record<HealthCheckReport["verdict"], string> = {+ healthy: "GOOD",+ partial: "WARN",+ "auth-required": "AUTH",+ unreachable: "DOWN",+};++export const VERDICT_DOT: Record<HealthCheckReport["verdict"], string> = {+ healthy: "bg-success",+ partial: "bg-warning",+ "auth-required": "bg-info",+ unreachable: "bg-destructive",+};++export function statusDotClass(input: boolean | null | StepResult): string {+ if (input === null) return "bg-muted-foreground/30";+ if (typeof input === "boolean") {+ return input ? "bg-success" : "bg-destructive";+ }+ if (input.ok) return "bg-success";+ // 401 routes the verdict to AUTH (blue); the failing steps that produced it+ // should match so the row colors line up with the verdict chip.+ if (input.error?.code === "UNAUTHORIZED") return "bg-info";+ return "bg-destructive";+}++export function originOf(url: string): string {+ try {+ return new URL(url).origin;+ } catch {+ return url;+ }+}++export function formatTimestamp(date: Date): string {+ return date.toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ hour: "numeric",+ minute: "numeric",+ second: "numeric",+ });+}++/**+ * Pretty-print whatever the server actually returned. The runtime body can be:+ * - a JSON document (application/json)+ * - one or more SSE frames, each carrying a JSON payload after `data:`+ * - a non-JSON blob (HTML, plain text) — passed through unchanged+ * Truncation suffix `…[truncated]` is preserved so the reader sees the cap.+ */+export function formatResponseBody(raw: string | undefined): string {+ if (!raw) return "";+ const trimmed = raw.trim();+ if (!trimmed) return raw;++ const TRUNCATED = "…[truncated]";+ const wasTruncated = trimmed.endsWith(TRUNCATED);+ const body = wasTruncated ? trimmed.slice(0, -TRUNCATED.length) : trimmed;+ const suffix = wasTruncated ? `\n${TRUNCATED}` : "";++ const direct = tryPrettyJson(body);+ if (direct) return direct + suffix;++ const sseFrames = extractSseDataFrames(body);+ if (sseFrames.length > 0) {+ return sseFrames.join("\n\n") + suffix;+ }+ return raw;+}++function tryPrettyJson(input: string): string | null {+ try {+ return JSON.stringify(JSON.parse(input), null, 2);+ } catch {+ return null;+ }+}++function extractSseDataFrames(input: string): string[] {+ const frames: string[] = [];+ let dataLines: string[] = [];+ const flush = () => {+ if (dataLines.length === 0) return;+ const payload = dataLines.join("\n");+ dataLines = [];+ const pretty = tryPrettyJson(payload);+ frames.push(pretty ?? payload);+ };+ for (const rawLine of input.split(/\r?\n/)) {+ if (rawLine === "") {+ flush();+ continue;+ }+ if (rawLine.startsWith("data:")) {+ dataLines.push(rawLine.slice(5).replace(/^\s/, ""));+ }+ }+ flush();+ return frames;+}diff --git a/apps/web/src/app/(landing)/play/page.tsx b/apps/web/src/app/(landing)/play/page.tsxindex 2366bae94..e552f436b 100644--- a/apps/web/src/app/(landing)/play/page.tsx+++ b/apps/web/src/app/(landing)/play/page.tsx@@ -58,6 +58,11 @@ const PLAY = [description: "Test the latency of your website worldwide",href: "/play/checker",},+ {+ label: "MCP Server Health Check",+ description: "JSON-RPC ping check for Model Context Protocol servers",+ href: "/play/mcp-health",+ },{label: "cURL Builder",description: "Curl your website",diff --git a/apps/web/src/app/(landing)/status/page.tsx b/apps/web/src/app/(landing)/status/page.tsxindex 590d0b28b..9beec23e9 100644--- a/apps/web/src/app/(landing)/status/page.tsx+++ b/apps/web/src/app/(landing)/status/page.tsx@@ -60,7 +60,7 @@ export default async function Page() {await api.externalService.grid.prefetch();return (- <section className="prose dark:prose-invert flex flex-col gap-4 mb-12 max-w-none">+ <section className="prose dark:prose-invert mb-12 flex max-w-none flex-col gap-4"><ContentBoxContainer className="not-prose mb-2 px-4 py-2 text-sm"><CustomLinkhref={`${APP_URL}?ref=status-index-top`}diff --git a/apps/web/src/app/api/search/route.ts b/apps/web/src/app/api/search/route.tsindex e4a78530e..0f2498569 100644--- a/apps/web/src/app/api/search/route.ts+++ b/apps/web/src/app/api/search/route.ts@@ -52,7 +52,7 @@ function search(params: SearchParams) {let results: MDXData[] = [];if (p === "tools") {- results = getPages("tools").filter((tool) => tool.slug !== "checker-slug");+ results = getPages("tools");} else if (p === "product") {const home = getHomePage();// NOTE: we override /home with / for the home.mdx file@@ -67,7 +67,7 @@ function search(params: SearchParams) {results = [...getPages("blog"),...getPages("changelog"),- ...getPages("tools").filter((tool) => tool.slug !== "checker-slug"),+ ...getPages("tools"),...getPages("tooling"),...getPages("compare"),...getPages("product"),diff --git a/apps/web/src/app/sitemap.ts b/apps/web/src/app/sitemap.tsindex c1b0f5455..926716649 100644--- a/apps/web/src/app/sitemap.ts+++ b/apps/web/src/app/sitemap.ts@@ -22,9 +22,7 @@ const allUnrelated = getUnrelatedPages().filter((page) => page.slug !== "not-found",);const allProducts = getProductPages();-const allPlaygrounds = getToolsPages().filter(- (tool) => tool.slug !== "checker-slug",-);+const allPlaygrounds = getToolsPages();const allGuides = getGuides();const allUseCases = getUseCasePages();const allTooling = getToolingPages();diff --git a/apps/web/src/content/cmdk.tsx b/apps/web/src/content/cmdk.tsxindex 04717fad1..b456df78f 100644--- a/apps/web/src/content/cmdk.tsx+++ b/apps/web/src/content/cmdk.tsx@@ -450,7 +450,8 @@ function SearchResults({return (<CommandItem- key={item.slug}+ key={item.href}+ value={item.href}keywords={[item.metadata.title, item.content, search]}onSelect={() => {router.push(item.href);diff --git a/apps/web/src/content/mdx-components/details.tsx b/apps/web/src/content/mdx-components/details.tsxindex d3a6fd1a7..cdbed171b 100644--- a/apps/web/src/content/mdx-components/details.tsx+++ b/apps/web/src/content/mdx-components/details.tsx@@ -1,4 +1,3 @@-import React from "react";import { slugify } from "./heading";export function Details({@@ -13,10 +12,7 @@ export function Details({return (<details id={slugify(summary)} open={open}><summary>{summary}</summary>- {React.isValidElement(children)- ? // biome-ignore lint/suspicious/noExplicitAny: <explanation>- React.cloneElement(children, { hidden: "until-found" } as any)- : children}+ {children}</details>);}diff --git a/apps/web/src/content/pages/tools/checker.mdx b/apps/web/src/content/pages/tools/checker.mdxindex fcf62f443..09a895f73 100644--- a/apps/web/src/content/pages/tools/checker.mdx+++ b/apps/web/src/content/pages/tools/checker.mdx@@ -13,8 +13,6 @@ faq:answer: "You can test how fast your API or website responds worldwide, compare latency across different regions, identify network bottlenecks, and monitor uptime and availability in real time from distributed locations across Europe, Asia, North America, and beyond."----> **We support the Global Speed Checker as agentic skill! [See changelog](/changelog/global-speed-checker-skills).**-## Start monitoring your services<Grid cols={3}>diff --git a/apps/web/src/content/pages/tools/mcp-health-slug.mdx b/apps/web/src/content/pages/tools/mcp-health-slug.mdxnew file mode 100644index 000000000..2b6df32d5--- /dev/null+++ b/apps/web/src/content/pages/tools/mcp-health-slug.mdx@@ -0,0 +1,19 @@+---+title: "MCP Server Health Check"+publishedAt: "2026-05-21"+author: "Maximilian Kaske"+description: "Detailed JSON-RPC handshake report for a Model Context Protocol server."+category: "Product"+---++Each row above represents one call from the MCP `2025-06-18` handshake. Click a row to see the exact JSON-RPC request openstatus sent and the response the server returned. Request headers are never stored — re-run the check with your own `Authorization` header if the server requires auth.++Reports expire after **7 days**. To monitor an MCP server continuously, see the [monitoring guide](/docs/guides/how-to-monitor-mcp-server).++---++Need help to monitor your MCP server?++<ButtonLink href="https://app.openstatus.dev">Start monitoring your MCP server</ButtonLink>++---diff --git a/apps/web/src/content/pages/tools/mcp-health.mdx b/apps/web/src/content/pages/tools/mcp-health.mdxnew file mode 100644index 000000000..467d599b8--- /dev/null+++ b/apps/web/src/content/pages/tools/mcp-health.mdx@@ -0,0 +1,166 @@+---+title: "MCP Server Health Check"+publishedAt: "2026-05-21"+author: "Maximilian Kaske"+description: "Free online MCP server health check. Test JSON-RPC initialize, ping, and tools/list handshake from your browser — no install, no signup."+category: "Product"+howto:+ totalTime: "PT30S"+ steps:+ - name: "Paste your MCP server URL"+ text: "Enter the URL of your Model Context Protocol endpoint (for example https://hf.co/mcp). Both application/json and text/event-stream transports are supported."+ url: "#how-to-test-your-mcp-server"+ - name: "Add an authorization header if needed"+ text: "If the server requires authentication, click Add Header and set Authorization to Bearer <token>. Public MCP servers can be tested without any headers."+ url: "#how-to-test-your-mcp-server"+ - name: "Run the JSON-RPC handshake"+ text: "openstatus sends the three calls every MCP client makes on connect: initialize, ping, and tools/list. The session id is captured automatically."+ url: "#how-to-test-your-mcp-server"+ - name: "Inspect each step"+ text: "Click any row in the result table to open the exact JSON-RPC request and response, the per-step latency, and metadata captured from the handshake (protocol version, server info, session id)."+ url: "#how-to-test-your-mcp-server"+faq:+ - question: "What is an MCP health check?"+ answer: "An MCP health check verifies that a Model Context Protocol server is reachable, speaks the JSON-RPC handshake correctly, and exposes the tools it claims to. Unlike a plain HTTP ping, it sends the three calls every MCP client makes on connect — initialize, notifications/initialized, and tools/list — and validates the responses, so a server returning 200 OK with an HTML body still fails the check."+ - question: "How do I test if my MCP server is working?"+ answer: "Paste your server URL into the openstatus MCP Server Health Check and run it. The tool performs the full MCP 2025-06-18 handshake from your browser, returns a verdict (Healthy, Partial, Auth Required, or Unreachable), and shows the JSON-RPC request and response for each step so you can see exactly where the handshake failed."+ - question: "What's the difference between an MCP ping and an HTTP ping?"+ answer: "An HTTP ping only checks that the URL responds — a 200 from a misconfigured load balancer or a CDN error page would pass. An MCP ping runs the JSON-RPC initialize handshake, captures the Mcp-Session-Id, and validates that the server echoes the expected request id. A protocol-level ping is the difference between 'the box is up' and 'the box speaks the protocol my AI client expects.'"+ - question: "Do I need authentication to ping an MCP server?"+ answer: "Only if the server requires it. Public MCP servers like hf.co/mcp work without any headers. Servers that require auth respond with 401 and a WWW-Authenticate header — our tool detects this, parses the OAuth resource metadata when present, and tells you exactly which authorization server to grab a token from. You then paste the token as an Authorization header and re-run."+ - question: "Why does my MCP server return text/event-stream?"+ answer: "MCP's Streamable HTTP transport allows a server to respond with either application/json or text/event-stream — both are spec-compliant. Servers built on the official SDKs default to SSE because it supports server-initiated notifications. Our tool reads the SSE stream, finds the first event whose JSON payload's id matches the request, and treats it identically to a JSON response."+ - question: "How do I debug a 401 from my MCP server?"+ answer: "A 401 means the server requires authentication. Check the WWW-Authenticate header in the response — if it points to an OAuth resource_metadata URL, the tool surfaces the authorization server so you can fetch a token. Then click Add Header, set Authorization to Bearer <your-token>, and re-run the check."+ - question: "How does OAuth work for MCP servers?"+ answer: "MCP follows RFC 9728 (OAuth 2.0 Protected Resource Metadata). The server returns 401 with a WWW-Authenticate: Bearer resource_metadata=\"…\" header pointing at a JSON document that lists the trusted authorization servers. Clients fetch that document, complete an OAuth flow against the listed authorization server, and resend the JSON-RPC request with an Authorization: Bearer header. The health checker parses the resource metadata for you and surfaces the authorization server URL in the auth-challenge callout."+ - question: "Is the openstatus MCP Server Health Check free?"+ answer: "Yes — it is free to use, requires no account, and runs entirely in your browser. Reports you choose to share via the URL expire after 7 days. The tool is open-source, like the rest of openstatus."+ - question: "Can I monitor my MCP server continuously?"+ answer: "Yes — this tool runs a one-off check from your browser. For continuous monitoring with alerts when the handshake breaks, see the [openstatus guide to monitoring MCP servers](/docs/guides/how-to-monitor-mcp-server)."+---++> Monitor MCP servers continuously? [Read the monitoring guide](/docs/guides/how-to-monitor-mcp-server).++## What is an MCP server health check?++An MCP server health check verifies that a [Model Context Protocol](https://modelcontextprotocol.io) endpoint behaves the way an AI client expects when it first connects. It is not a plain HTTP ping — it speaks JSON-RPC, runs the spec-defined handshake, and confirms the server actually exposes the tools it promises.++A failing MCP health check tells you the server is unreachable, returning the wrong content type, missing required JSON-RPC methods, or expecting an auth header you haven't provided. A passing check tells you the server is ready to serve AI clients like Claude Desktop, Claude Code, Cursor, Continue, or your own agent.++## How to test your MCP server++1. **Paste your MCP server URL.** Any Streamable HTTP endpoint works — for example `https://hf.co/mcp` or your own deployment.+2. **Add an `Authorization` header if the server requires it.** Public servers can be tested with no headers.+3. **Run the check.** Openstatus sends the JSON-RPC `initialize`, `ping`, and `tools/list` calls in the same order an MCP client would.+4. **Inspect each step.** Click any row in the result table to open the exact JSON-RPC request and response that openstatus sent and received — along with the per-step latency, negotiated protocol version, server info, and session id.++The whole flow takes about 30 seconds and never leaves your browser session — the only data persisted is the report you explicitly choose to share.++## What this tool does++The tool runs the three calls every MCP client makes on connect:++- **`initialize`** — declares protocol version `2025-06-18`, captures the server's `serverInfo`, `capabilities`, and `Mcp-Session-Id`.+- **`notifications/initialized`** — fire-and-forget notification telling the server the client is ready.+- **`ping`** + **`tools/list`** — runs in parallel using the captured session id, reports latency and the tools the server advertises.++The verdict is one of **Healthy** (`GOOD`), **Partial** (`WARN` — server speaks MCP but exposes no tools), **Authentication Required** (`AUTH` — server returned 401 with a Bearer challenge), or **Unreachable** (`DOWN` — DNS / connection / parse failure).++## Why a JSON-RPC ping isn't a plain HTTP check++A status-code pinger checks one thing: did the URL return 200? An MCP server can return 200 and still be broken — the body might be HTML from a misconfigured proxy, the JSON-RPC `id` might not echo, the server might not implement `ping`, or `tools/list` might come back empty. AI clients fail in every one of those cases.++The handshake also captures the negotiated protocol version, which is the only reliable signal that an MCP server upgrade hasn't silently changed behaviour. If your server claims `2025-06-18` today and `2025-09-01` next week, you want to know before your users do.++## Common failure modes++- **Connection refused / DNS** — the URL is wrong, the server is down, or your firewall is in the way.+- **200 with an HTML body** — the URL points at a marketing page or load balancer, not the JSON-RPC endpoint. The most common MCP misconfiguration.+- **401 / 403** — auth header missing or rotated. The token your AI client uses is the same one you need here.+- **401 with `WWW-Authenticate: Bearer …`** — the server uses OAuth. We parse the `resource_metadata` URL and surface the authorization server so you can grab a token in one click.+- **406 Not Acceptable** — the server requires `text/event-stream` in `Accept`. We always send `application/json, text/event-stream`, so this usually means the server's Accept negotiation is broken.+- **JSON-RPC `-32601 Method not found`** — the server doesn't implement `ping`. Some MCP implementations skip optional methods; the tool still passes if `initialize` + `tools/list` succeed.+- **Session id missing** — many servers don't enforce sessions, and we proceed without one. If your server requires it, ensure `initialize` returns `Mcp-Session-Id`.++## Authentication and OAuth++MCP servers that require auth follow [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728). When the server rejects an unauthenticated `initialize`, it returns `401 Unauthorized` with a `WWW-Authenticate: Bearer resource_metadata="…"` header pointing at a JSON document that lists the authorization servers it trusts.++The health checker handles that flow for you:++- On `401`, openstatus parses the `WWW-Authenticate` header and fetches the linked `resource_metadata` document.+- The **authorization server URL** is surfaced in the auth-challenge callout so you know exactly where to obtain a token — no guessing which IdP the server delegates to.+- Once you have a token (from a `client_credentials` flow, a personal access token, or your AI client's OAuth callback), click **Add Header**, set `Authorization` to `Bearer <token>`, and re-run.++If the server returns `401` *without* a `WWW-Authenticate` header, it is non-compliant — most clients (including Claude Desktop and Claude Code) will fail to authenticate, and the tool will report `AUTH` with no resource metadata.++## Headers++The handshake always sends `Content-Type: application/json` and `Accept: application/json, text/event-stream`. Add any extra headers (most commonly `Authorization: Bearer <token>`) with the **Add Header** button.++> **Heads up.** Any token you paste here transits openstatus's edge to reach the target MCP server. Don't paste production tokens you can't rotate. Shared `?id=` reports never include the headers you sent.++## Frequently asked questions++<Details summary="What is an MCP health check?">++An MCP health check verifies that a Model Context Protocol server is reachable, speaks the JSON-RPC handshake correctly, and exposes the tools it claims to. Unlike a plain HTTP ping, it sends the three calls every MCP client makes on connect — `initialize`, `notifications/initialized`, and `tools/list` — and validates the responses, so a server returning `200 OK` with an HTML body still fails the check.++</Details>++<Details summary="How do I test if my MCP server is working?">++Paste your server URL into the openstatus MCP Server Health Check and run it. The tool performs the full MCP `2025-06-18` handshake from your browser, returns a verdict (Healthy, Partial, Auth Required, or Unreachable), and shows the JSON-RPC request and response for each step so you can see exactly where the handshake failed.++</Details>++<Details summary="What's the difference between an MCP ping and an HTTP ping?">++An HTTP ping only checks that the URL responds — a `200` from a misconfigured load balancer or a CDN error page would pass. An MCP ping runs the JSON-RPC `initialize` handshake, captures the `Mcp-Session-Id`, and validates that the server echoes the expected request id. A protocol-level ping is the difference between "the box is up" and "the box speaks the protocol my AI client expects."++</Details>++<Details summary="Do I need authentication to ping an MCP server?">++Only if the server requires it. Public MCP servers like `hf.co/mcp` work without any headers. Servers that require auth respond with `401` and a `WWW-Authenticate` header — our tool detects this, parses the OAuth resource metadata when present, and tells you exactly which authorization server to grab a token from. You then paste the token as an `Authorization` header and re-run.++</Details>++<Details summary="Why does my MCP server return text/event-stream?">++MCP's Streamable HTTP transport allows a server to respond with either `application/json` or `text/event-stream` — both are spec-compliant. Servers built on the official SDKs default to SSE because it supports server-initiated notifications. Our tool reads the SSE stream, finds the first event whose JSON payload's `id` matches the request, and treats it identically to a JSON response.++</Details>++<Details summary="How do I debug a 401 from my MCP server?">++A `401` means the server requires authentication. Check the `WWW-Authenticate` header in the response — if it points to an OAuth `resource_metadata` URL, the tool surfaces the authorization server so you can fetch a token. Then click **Add Header**, set `Authorization` to `Bearer <your-token>`, and re-run the check.++</Details>++<Details summary="How does OAuth work for MCP servers?">++MCP follows [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728). The server returns `401` with a `WWW-Authenticate: Bearer resource_metadata="…"` header pointing at a JSON document that lists the trusted authorization servers. Clients fetch that document, complete an OAuth flow against the listed authorization server, and resend the JSON-RPC request with an `Authorization: Bearer` header. The health checker parses the resource metadata for you and surfaces the authorization server URL in the auth-challenge callout.++</Details>++<Details summary="Is the openstatus MCP Server Health Check free?">++Yes — it is free to use, requires no account, and runs entirely in your browser. Reports you choose to share via the URL expire after 7 days. The tool is open-source, like the rest of openstatus.++</Details>++<Details summary="Can I monitor my MCP server continuously?">++Yes — this tool runs a one-off check from your browser. For continuous monitoring with alerts when the handshake breaks, see the [openstatus guide to monitoring MCP servers](/docs/guides/how-to-monitor-mcp-server).++</Details>++---++Need help to monitor your MCP server?++<ButtonLink href="https://app.openstatus.dev">Start monitoring your MCP server</ButtonLink>++---diff --git a/apps/web/src/content/utils.ts b/apps/web/src/content/utils.tsindex 077dbf745..bd2c42598 100644--- a/apps/web/src/content/utils.ts+++ b/apps/web/src/content/utils.ts@@ -157,11 +157,14 @@ export function getHomePage(): MDXData {);}+// `*-slug.mdx` files back dynamic routes (e.g. /play/checker/[slug],+// /play/mcp-health/[id]) and aren't standalone pages — exclude them from+// listings, sitemaps, and search. Use `getToolsPage("foo-slug")` to fetch one.export function getToolsPages(): MDXData[] {return getMDXDataFromDir(path.join(process.cwd(), "src", "content", "pages", "tools"),"/play",- );+ ).filter((page) => !page.slug.endsWith("-slug"));}export function getToolsPage(slug: string): MDXData {diff --git a/apps/web/src/data/content.ts b/apps/web/src/data/content.tsindex 2c9ca9bbf..5f2136b1f 100644--- a/apps/web/src/data/content.ts+++ b/apps/web/src/data/content.ts@@ -162,9 +162,7 @@ const toolsSection = {label: "Tools",items: [...getToolsPages()- .filter(- (page) => !["checker-slug", "severity-matrix"].includes(page.slug),- )+ .filter((page) => !["severity-matrix", "uptime-sla"].includes(page.slug)).map((page) => ({label: page.metadata.title,href: `/play/${page.slug}`,@@ -217,12 +215,10 @@ const communitySection = {export const playSection = {label: "Play",items: [- ...getToolsPages()- .filter((page) => page.slug !== "checker-slug")- .map((page) => ({- label: page.metadata.title,- href: `/play/${page.slug}`,- })),+ ...getToolsPages().map((page) => ({+ label: page.metadata.title,+ href: `/play/${page.slug}`,+ })),{label: "Theme Explorer",href: "https://themes.openstatus.dev",diff --git a/apps/web/src/lib/mcp/health-check.test.ts b/apps/web/src/lib/mcp/health-check.test.tsnew file mode 100644index 000000000..1a45cf37a--- /dev/null+++ b/apps/web/src/lib/mcp/health-check.test.ts@@ -0,0 +1,273 @@+import { afterEach, describe, expect, test } from "bun:test";+import {+ normalizeUrlForStorage,+ parseBearerChallenge,+ safeFetch,+ stepFromOutcome,+ toPersistedReport,+} from "./health-check";+import type { HealthCheckReport } from "./health-check";++function makeOutcome(o: {+ ok: boolean;+ status: number;+ rawBody?: string;+ json?: {+ jsonrpc?: string;+ id?: string | number | null;+ result?: unknown;+ error?: { code: number; message: string };+ };+ parseError?: string;+}) {+ return { headers: new Headers(), rawBody: "", ...o };+}++describe("parseBearerChallenge", () => {+ test("returns null for null/empty/non-Bearer", () => {+ expect(parseBearerChallenge(null)).toBeNull();+ expect(parseBearerChallenge("")).toBeNull();+ expect(parseBearerChallenge("Basic realm=foo")).toBeNull();+ expect(parseBearerChallenge("DPoP")).toBeNull();+ });++ test("Bearer alone with no params", () => {+ expect(parseBearerChallenge("Bearer")).toEqual({});+ });++ test("Bearer with realm and scope", () => {+ const out = parseBearerChallenge('Bearer realm="mcp", scope="read write"');+ expect(out).toEqual({ realm: "mcp", scope: "read write" });+ });++ test("Bearer with resource_metadata URL (quoted, internal comma in path)", () => {+ const header =+ 'Bearer realm="x", resource_metadata="https://example.com/.well-known/oauth-protected-resource"';+ expect(parseBearerChallenge(header)).toEqual({+ realm: "x",+ resource_metadata:+ "https://example.com/.well-known/oauth-protected-resource",+ });+ });++ test("Bearer values with commas inside quotes are preserved", () => {+ const header = 'Bearer error_description="missing, token", realm="x"';+ const out = parseBearerChallenge(header);+ expect(out?.error_description).toBe("missing, token");+ expect(out?.realm).toBe("x");+ });++ test("multi-scheme header — picks Bearer", () => {+ const header = 'DPoP algs="ES256", Bearer realm="mcp"';+ const out = parseBearerChallenge(header);+ expect(out?.realm).toBe("mcp");+ });++ test("case-insensitive Bearer", () => {+ expect(parseBearerChallenge('BEARER realm="x"')?.realm).toBe("x");+ expect(parseBearerChallenge("bearer realm=foo")?.realm).toBe("foo");+ });++ test("unquoted token68 values", () => {+ expect(parseBearerChallenge("Bearer realm=mcp scope=read")).toEqual({+ realm: "mcp",+ scope: "read",+ });+ });++ test("keys are lowercased", () => {+ expect(parseBearerChallenge('Bearer Realm="x"')?.realm).toBe("x");+ expect(parseBearerChallenge('Bearer ERROR="invalid_token"')?.error).toBe(+ "invalid_token",+ );+ });+});++describe("normalizeUrlForStorage", () => {+ test("strips userinfo, query, fragment", () => {+ expect(+ normalizeUrlForStorage("https://u:[email protected]/mcp?token=secret#x"),+ ).toBe("https://example.com/mcp");+ });++ test("keeps explicit port", () => {+ expect(normalizeUrlForStorage("https://example.com:8443/mcp")).toBe(+ "https://example.com:8443/mcp",+ );+ });++ test("invalid URL returns input unchanged", () => {+ expect(normalizeUrlForStorage("not a url")).toBe("not a url");+ });+});++describe("toPersistedReport", () => {+ const baseReport: HealthCheckReport = {+ url: "https://example.com/mcp",+ timestamp: 1_700_000_000_000,+ verdict: "healthy",+ initialize: { ok: true, latencyMs: 120 },+ ping: { ok: true, latencyMs: 45 },+ toolsList: { ok: true, latencyMs: 80 },+ };++ test("re-normalizes the URL on persist", () => {+ const out = toPersistedReport({+ ...baseReport,+ url: "https://u:[email protected]/mcp?secret=1",+ });+ expect(out.url).toBe("https://example.com/mcp");+ });++ test("caps step rawBody at 16 KB with truncation suffix", () => {+ const huge = "x".repeat(20_000);+ const out = toPersistedReport({+ ...baseReport,+ initialize: { ...baseReport.initialize, rawBody: huge },+ });+ expect(out.initialize.rawBody?.length).toBeGreaterThan(16_000);+ expect(out.initialize.rawBody?.length).toBeLessThan(huge.length);+ expect(out.initialize.rawBody?.endsWith("…[truncated]")).toBe(true);+ });++ test("short bodies are passed through unchanged", () => {+ const body = "ok";+ const out = toPersistedReport({+ ...baseReport,+ ping: { ...baseReport.ping, rawBody: body },+ });+ expect(out.ping.rawBody).toBe(body);+ });+});++describe("stepFromOutcome", () => {+ const base = { startedAt: Date.now(), expectedId: "id-1" };++ test("200 with a parse failure classifies as PARSE, not HTTP_STATUS", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({+ ok: true,+ status: 200,+ parseError: "unexpected content-type: text/html",+ }),+ });+ expect(step.ok).toBe(false);+ expect(step.error?.code).toBe("PARSE");+ });++ test("HTTP 500 classifies as HTTP_STATUS", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({ ok: false, status: 500 }),+ });+ expect(step.error?.code).toBe("HTTP_STATUS");+ expect(step.error?.message).toBe("HTTP 500");+ });++ test("401 classifies as UNAUTHORIZED", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({ ok: false, status: 401 }),+ });+ expect(step.error?.code).toBe("UNAUTHORIZED");+ });++ test("JSON-RPC error payload classifies as JSON_RPC_ERROR", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({+ ok: true,+ status: 200,+ json: { id: "id-1", error: { code: -32601, message: "no method" } },+ }),+ });+ expect(step.error?.code).toBe("JSON_RPC_ERROR");+ });++ test("mismatched id classifies as ID_MISMATCH", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({+ ok: true,+ status: 200,+ json: { id: "other", result: {} },+ }),+ });+ expect(step.error?.code).toBe("ID_MISMATCH");+ });++ test("matching id with a result is ok", () => {+ const step = stepFromOutcome({+ ...base,+ outcome: makeOutcome({+ ok: true,+ status: 200,+ json: { id: "id-1", result: {} },+ }),+ });+ expect(step.ok).toBe(true);+ });+});++describe("safeFetch", () => {+ const realFetch = globalThis.fetch;+ const signal = () => new AbortController().signal;+ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ test("returns a non-redirect response unchanged", async () => {+ globalThis.fetch = (async () =>+ new Response("ok", { status: 200 })) as typeof fetch;+ const res = await safeFetch(+ "https://example.com/mcp",+ { method: "GET" },+ signal(),+ );+ expect(res.status).toBe(200);+ expect(await res.text()).toBe("ok");+ });++ test("follows a redirect to a public URL", async () => {+ let call = 0;+ globalThis.fetch = (async () => {+ call++;+ return call === 1+ ? new Response(null, {+ status: 302,+ headers: { location: "https://example.com/final" },+ })+ : new Response("done", { status: 200 });+ }) as typeof fetch;+ const res = await safeFetch(+ "https://example.com/mcp",+ { method: "GET" },+ signal(),+ );+ expect(call).toBe(2);+ expect(res.status).toBe(200);+ });++ test("blocks a redirect to a private address", async () => {+ globalThis.fetch = (async () =>+ new Response(null, {+ status: 302,+ headers: { location: "http://169.254.169.254/latest/meta-data/" },+ })) as typeof fetch;+ await expect(+ safeFetch("https://example.com/mcp", { method: "GET" }, signal()),+ ).rejects.toThrow("not allowed");+ });++ test("throws after too many redirects", async () => {+ globalThis.fetch = (async () =>+ new Response(null, {+ status: 302,+ headers: { location: "https://example.com/loop" },+ })) as typeof fetch;+ await expect(+ safeFetch("https://example.com/mcp", { method: "GET" }, signal()),+ ).rejects.toThrow("too many redirects");+ });+});diff --git a/apps/web/src/lib/mcp/health-check.ts b/apps/web/src/lib/mcp/health-check.tsnew file mode 100644index 000000000..64a962f6a--- /dev/null+++ b/apps/web/src/lib/mcp/health-check.ts@@ -0,0 +1,935 @@+// Edge-safe: no node:* imports allowed.+// MCP spec: https://modelcontextprotocol.io/specification/2025-06-18++import { redis } from "@openstatus/upstash";+import { assertSafeUrlSync } from "@openstatus/utils";+import { z } from "zod";+import {+ PROTOCOL_VERSION,+ REQ_ID_INIT,+ REQ_ID_PING,+ REQ_ID_TOOLS,+ STEP_REQUEST_BODIES,+} from "./protocol";++const STEP_TIMEOUT_MS = 8_000;+const METADATA_FETCH_TIMEOUT_MS = 3_000;+// How much body we keep around (in memory + persisted-with-cap downstream).+const RAW_BODY_CAP = 32_768;+// How far the SSE reader scans the stream looking for the matching id frame.+// Independent of RAW_BODY_CAP — large tools/list responses can exceed the kept+// body but the matching frame still needs to be found.+const SSE_SCAN_LIMIT = 262_144;++const stepErrorCodeSchema = z.enum([+ "TIMEOUT",+ "NETWORK",+ "HTTP_STATUS",+ "PARSE",+ "ID_MISMATCH",+ "JSON_RPC_ERROR",+ "UNAUTHORIZED",+]);++const stepResultSchema = z.object({+ ok: z.boolean(),+ latencyMs: z.number(),+ rawBody: z.string().optional(),+ error: z+ .object({+ code: stepErrorCodeSchema,+ message: z.string(),+ })+ .optional(),+});++const authChallengeSchema = z.object({+ authorizationServer: z.string().optional(),+ scopes: z.array(z.string()).optional(),+ mechanism: z.enum(["oauth", "bearer-static", "unknown"]),+});++const toolAnnotationsSchema = z.object({+ readOnlyHint: z.boolean().optional(),+ destructiveHint: z.boolean().optional(),+ idempotentHint: z.boolean().optional(),+ openWorldHint: z.boolean().optional(),+});++const toolInfoSchema = z.object({+ name: z.string(),+ title: z.string().optional(),+ description: z.string().optional(),+ annotations: toolAnnotationsSchema.optional(),+});++export const healthCheckReportSchema = z.object({+ url: z.string(),+ timestamp: z.number(),+ verdict: z.enum(["healthy", "partial", "auth-required", "unreachable"]),+ initialize: stepResultSchema.extend({+ protocolVersion: z.string().optional(),+ serverInfo: z.object({ name: z.string(), version: z.string() }).optional(),+ capabilities: z.record(z.string(), z.unknown()).optional(),+ hasSessionId: z.boolean().optional(),+ }),+ ping: stepResultSchema,+ toolsList: stepResultSchema.extend({+ toolCount: z.number().optional(),+ tools: z.array(toolInfoSchema).optional(),+ truncated: z.boolean().optional(),+ }),+ authChallenge: authChallengeSchema.optional(),+});++export type StepErrorCode = z.infer<typeof stepErrorCodeSchema>;+export type StepResult = z.infer<typeof stepResultSchema>;+export type AuthChallenge = z.infer<typeof authChallengeSchema>;+export type ToolInfo = z.infer<typeof toolInfoSchema>;+export type HealthCheckReport = z.infer<typeof healthCheckReportSchema>;++export type HealthCheckInput = {+ url: string;+ headers?: Array<{ key: string; value: string }>;+};++type JsonRpcResponse = {+ jsonrpc?: string;+ id?: string | number | null;+ result?: unknown;+ error?: { code: number; message: string; data?: unknown };+};++type RpcOutcome = {+ // mirrors res.ok (HTTP 2xx); parse success lives in json/parseError so a 200+ // with an unparseable body classifies as PARSE, not HTTP_STATUS.+ ok: boolean;+ status: number;+ headers: Headers;+ rawBody: string;+ json?: JsonRpcResponse;+ parseError?: string;+};++type HeaderOpts = {+ sessionId?: string;+ protocolVersion?: string;+ // notification mode: server must not open an SSE stream (we'd stall).+ notification?: boolean;+};++// User headers must not clobber the handshake-critical headers set below;+// overriding Content-Type/Accept silently breaks the MCP transport negotiation.+const RESERVED_HEADERS = new Set([+ "content-type",+ "accept",+ "mcp-session-id",+ "mcp-protocol-version",+]);++function buildHeaders(+ extra?: HealthCheckInput["headers"],+ opts: HeaderOpts = {},+) {+ const headers = new Headers({+ "Content-Type": "application/json",+ Accept: opts.notification+ ? "application/json"+ : "application/json, text/event-stream",+ });+ if (opts.sessionId) headers.set("Mcp-Session-Id", opts.sessionId);+ // MCP 2025-06-18 §lifecycle: clients SHOULD send this on every request+ // after initialize so version-pinning gateways route correctly.+ if (opts.protocolVersion) {+ headers.set("MCP-Protocol-Version", opts.protocolVersion);+ }+ for (const { key, value } of extra ?? []) {+ if (!key || RESERVED_HEADERS.has(key.toLowerCase())) continue;+ headers.set(key, value);+ }+ return headers;+}++function capRaw(body: string) {+ if (body.length <= RAW_BODY_CAP) return body;+ return `${body.slice(0, RAW_BODY_CAP)}…[truncated]`;+}++/**+ * Reads an SSE stream until it finds the first `event: message` frame whose+ * JSON payload's `id` matches `expectedId`. Aborts the reader after parsing.+ */+async function readSseUntilId(+ body: ReadableStream<Uint8Array>,+ expectedId: string,+): Promise<{ json?: JsonRpcResponse; rawBody: string; parseError?: string }> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buf = "";+ let raw = "";+ let currentEvent = "message";+ const dataLines: string[] = [];++ const flush = (): JsonRpcResponse | undefined => {+ if (dataLines.length === 0) return undefined;+ const data = dataLines.join("\n");+ dataLines.length = 0;+ try {+ const parsed = JSON.parse(data) as JsonRpcResponse;+ if (currentEvent === "message" && parsed.id === expectedId) return parsed;+ } catch {+ /* ignore non-JSON data frames */+ }+ return undefined;+ };++ // Bytes scanned, not bytes kept: `raw` is capped via capRaw() only when we+ // return it. Letting it grow up to SSE_SCAN_LIMIT means a 100 KB tools/list+ // payload still finds its matching frame even if we only persist 32 KB.+ let scanned = 0;+ try {+ while (scanned < SSE_SCAN_LIMIT) {+ const { value, done } = await reader.read();+ if (done) break;+ const chunk = decoder.decode(value, { stream: true });+ scanned += chunk.length;+ raw += chunk;+ buf += chunk;++ let nl = buf.indexOf("\n");+ while (nl !== -1) {+ const line = buf.slice(0, nl).replace(/\r$/, "");+ buf = buf.slice(nl + 1);++ if (line === "") {+ const matched = flush();+ if (matched) {+ await reader.cancel().catch(() => {});+ return { json: matched, rawBody: capRaw(raw) };+ }+ currentEvent = "message";+ } else if (line.startsWith(":")) {+ // comment+ } else if (line.startsWith("event:")) {+ currentEvent = line.slice(6).trim();+ } else if (line.startsWith("data:")) {+ dataLines.push(line.slice(5).replace(/^\s/, ""));+ }+ nl = buf.indexOf("\n");+ }+ }+ const tail = flush();+ if (tail) return { json: tail, rawBody: capRaw(raw) };+ return {+ rawBody: capRaw(raw),+ parseError: "no matching SSE event in stream",+ };+ } catch (err) {+ return {+ rawBody: capRaw(raw),+ parseError: err instanceof Error ? err.message : String(err),+ };+ } finally {+ await reader.cancel().catch(() => {});+ }+}++const MAX_REDIRECTS = 3;++// redirect:"follow" would let a public host 3xx us into a private/internal+// address, past the pre-flight assertSafeUrlSync. Follow manually instead and+// re-validate every hop. Server runtimes surface the 3xx + Location under+// redirect:"manual"; an opaqueredirect (no readable Location) is rejected.+export async function safeFetch(+ url: string,+ init: RequestInit,+ signal: AbortSignal,+): Promise<Response> {+ let target = url;+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {+ const res = await fetch(target, { ...init, signal, redirect: "manual" });+ if (res.type === "opaqueredirect") {+ throw new Error("refusing to follow opaque redirect");+ }+ if (res.status < 300 || res.status >= 400) return res;+ const location = res.headers.get("location");+ if (!location) return res;+ target = new URL(location, target).toString();+ assertSafeUrlSync(target);+ }+ throw new Error("too many redirects");+}++async function sendRpc({+ url,+ headers,+ body,+ expectedId,+ signal,+}: {+ url: string;+ headers: Headers;+ body: unknown;+ expectedId?: string;+ signal: AbortSignal;+}): Promise<RpcOutcome> {+ const res = await safeFetch(+ url,+ { method: "POST", headers, body: JSON.stringify(body) },+ signal,+ );++ const contentType = res.headers.get("content-type")?.toLowerCase() ?? "";++ if (expectedId === undefined) {+ // fire-and-forget notification: drain a bit to be polite, but don't parse+ let raw = "";+ try {+ raw = await res.text();+ } catch {+ /* ignore */+ }+ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody: capRaw(raw),+ };+ }++ if (contentType.includes("text/event-stream") && res.body) {+ const { json, rawBody, parseError } = await readSseUntilId(+ res.body,+ expectedId,+ );+ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody,+ json,+ parseError,+ };+ }++ let rawText = "";+ try {+ rawText = await res.text();+ } catch (err) {+ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody: "",+ parseError: err instanceof Error ? err.message : String(err),+ };+ }++ if (contentType.includes("application/json")) {+ try {+ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody: capRaw(rawText),+ json: JSON.parse(rawText) as JsonRpcResponse,+ };+ } catch (err) {+ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody: capRaw(rawText),+ parseError: err instanceof Error ? err.message : String(err),+ };+ }+ }++ return {+ ok: res.ok,+ status: res.status,+ headers: res.headers,+ rawBody: capRaw(rawText),+ parseError: contentType+ ? `unexpected content-type: ${contentType}`+ : "missing content-type",+ };+}++function withTimeout(+ ms: number,+ parent?: AbortSignal,+): { signal: AbortSignal; cancel: () => void } {+ const ctrl = new AbortController();+ const timer = setTimeout(+ () => ctrl.abort(new DOMException("timeout", "TimeoutError")),+ ms,+ );+ const onAbort = () => ctrl.abort(parent?.reason);+ if (parent?.aborted) onAbort();+ else parent?.addEventListener("abort", onAbort, { once: true });+ return {+ signal: ctrl.signal,+ cancel: () => {+ clearTimeout(timer);+ parent?.removeEventListener("abort", onAbort);+ },+ };+}++function classifyFetchError(err: unknown): {+ code: StepErrorCode;+ message: string;+} {+ if (err instanceof DOMException && err.name === "TimeoutError") {+ return { code: "TIMEOUT", message: "request timed out" };+ }+ if (err instanceof DOMException && err.name === "AbortError") {+ return { code: "TIMEOUT", message: "request aborted" };+ }+ const message = err instanceof Error ? err.message : String(err);+ return { code: "NETWORK", message };+}++/**+ * RFC 6750 / RFC 7235 WWW-Authenticate parser, scoped to the `Bearer` scheme.+ * Returns parsed params (e.g. `realm`, `resource_metadata`, `scope`) or null+ * when the header isn't a Bearer challenge.+ *+ * Handles quoted values containing commas/equals, which substring matching breaks on.+ */+export function parseBearerChallenge(+ header: string | null,+): Record<string, string> | null {+ if (!header) return null;+ const trimmed = header.trim();+ // Header may list multiple schemes (e.g., "Bearer ..., DPoP ..."). Pick Bearer.+ const match = trimmed.match(/^Bearer(?:\s+(.*))?$/i);+ if (!match) {+ // Try to locate "Bearer " segment in a multi-scheme header.+ const idx = trimmed.toLowerCase().indexOf("bearer");+ if (idx === -1) return null;+ return parseBearerParams(trimmed.slice(idx + "bearer".length));+ }+ return parseBearerParams(match[1] ?? "");+}++function parseBearerParams(input: string): Record<string, string> {+ const params: Record<string, string> = {};+ let i = 0;+ const len = input.length;+ while (i < len) {+ while (i < len && /\s|,/.test(input[i])) i++;+ if (i >= len) break;+ const keyStart = i;+ while (i < len && input[i] !== "=" && !/\s|,/.test(input[i])) i++;+ const key = input.slice(keyStart, i).toLowerCase();+ if (!key) {+ i++;+ continue;+ }+ while (i < len && /\s/.test(input[i])) i++;+ if (input[i] !== "=") {+ // bare token (e.g. another scheme name); stop parsing this scheme.+ break;+ }+ i++;+ while (i < len && /\s/.test(input[i])) i++;+ let value = "";+ if (input[i] === '"') {+ i++;+ while (i < len && input[i] !== '"') {+ if (input[i] === "\\" && i + 1 < len) {+ value += input[i + 1];+ i += 2;+ } else {+ value += input[i];+ i++;+ }+ }+ if (input[i] === '"') i++;+ } else {+ const valStart = i;+ while (i < len && input[i] !== "," && !/\s/.test(input[i])) i++;+ value = input.slice(valStart, i);+ }+ params[key] = value;+ }+ return params;+}++async function resolveAuthChallenge(+ wwwAuthenticate: string | null,+ parentSignal: AbortSignal,+): Promise<AuthChallenge | undefined> {+ const params = parseBearerChallenge(wwwAuthenticate);+ if (!params) return { mechanism: "unknown" };+ const resourceMetadata = params.resource_metadata;+ if (!resourceMetadata) {+ return { mechanism: "bearer-static" };+ }++ const challenge: AuthChallenge = { mechanism: "oauth" };++ // The server supplied this URL — guard against ricochet into private IPs.+ try {+ assertSafeUrlSync(resourceMetadata);+ } catch {+ return challenge;+ }++ const { signal, cancel } = withTimeout(+ METADATA_FETCH_TIMEOUT_MS,+ parentSignal,+ );+ try {+ const res = await safeFetch(+ resourceMetadata,+ { method: "GET", headers: { Accept: "application/json" } },+ signal,+ );+ if (!res.ok) return challenge;+ const ct = res.headers.get("content-type")?.toLowerCase() ?? "";+ if (!ct.includes("json")) return challenge;+ const data = (await res.json()) as {+ authorization_servers?: unknown;+ scopes_supported?: unknown;+ };+ if (Array.isArray(data.authorization_servers)) {+ const first = data.authorization_servers.find(+ (v): v is string => typeof v === "string",+ );+ if (first) challenge.authorizationServer = first;+ }+ if (Array.isArray(data.scopes_supported)) {+ challenge.scopes = data.scopes_supported.filter(+ (v): v is string => typeof v === "string",+ );+ }+ } catch {+ /* swallow; header alone proved OAuth posture */+ } finally {+ cancel();+ }+ return challenge;+}++export function stepFromOutcome({+ outcome,+ startedAt,+ expectedId,+}: {+ outcome: RpcOutcome;+ startedAt: number;+ expectedId: string;+}): StepResult {+ const latencyMs = Date.now() - startedAt;+ const rawBody = outcome.rawBody ? capRaw(outcome.rawBody) : undefined;++ if (outcome.status === 401) {+ return {+ ok: false,+ latencyMs,+ rawBody,+ error: { code: "UNAUTHORIZED", message: "server returned 401" },+ };+ }+ if (!outcome.ok) {+ return {+ ok: false,+ latencyMs,+ rawBody,+ error: {+ code: "HTTP_STATUS",+ message:+ outcome.status === 406+ ? "HTTP 406 — server rejected `application/json, text/event-stream` Accept; it likely requires one only"+ : `HTTP ${outcome.status}`,+ },+ };+ }+ if (outcome.parseError || !outcome.json) {+ return {+ ok: false,+ latencyMs,+ rawBody,+ error: {+ code: "PARSE",+ message: outcome.parseError ?? "missing JSON-RPC body",+ },+ };+ }+ if (outcome.json.error) {+ return {+ ok: false,+ latencyMs,+ rawBody,+ error: {+ code: "JSON_RPC_ERROR",+ message: `${outcome.json.error.code}: ${outcome.json.error.message}`,+ },+ };+ }+ if (outcome.json.id !== expectedId) {+ return {+ ok: false,+ latencyMs,+ rawBody,+ error: {+ code: "ID_MISMATCH",+ message: `expected id ${expectedId}, got ${JSON.stringify(outcome.json.id)}`,+ },+ };+ }+ return { ok: true, latencyMs, rawBody };+}++function emptyStep(): StepResult {+ return { ok: false, latencyMs: 0 };+}++/**+ * Strips userinfo, query, and fragment from `url`. Returns `origin + path`.+ * Falls back to the input if parsing fails (caller already validated it).+ */+export function normalizeUrlForStorage(url: string) {+ try {+ const u = new URL(url);+ return `${u.protocol}//${u.host}${u.pathname}`;+ } catch {+ return url;+ }+}++export async function runMcpHealthCheck(+ input: HealthCheckInput,+): Promise<HealthCheckReport> {+ const { url } = input;+ const report: HealthCheckReport = {+ url: normalizeUrlForStorage(url),+ timestamp: Date.now(),+ verdict: "unreachable",+ initialize: emptyStep(),+ ping: emptyStep(),+ toolsList: emptyStep(),+ };++ // --- Step 1: initialize ---+ const initStarted = Date.now();+ let initOutcome: RpcOutcome | undefined;+ let initWwwAuthenticate: string | null = null;+ const init = withTimeout(STEP_TIMEOUT_MS);+ try {+ initOutcome = await sendRpc({+ url,+ headers: buildHeaders(input.headers),+ body: STEP_REQUEST_BODIES.initialize,+ expectedId: REQ_ID_INIT,+ signal: init.signal,+ });+ } catch (err) {+ const { code, message } = classifyFetchError(err);+ report.initialize = {+ ok: false,+ latencyMs: Date.now() - initStarted,+ error: { code, message },+ };+ report.verdict = "unreachable";+ init.cancel();+ return report;+ }+ init.cancel();+ initWwwAuthenticate = initOutcome.headers.get("www-authenticate");++ const initStep = stepFromOutcome({+ outcome: initOutcome,+ startedAt: initStarted,+ expectedId: REQ_ID_INIT,+ });+ report.initialize = { ...report.initialize, ...initStep };++ if (initOutcome.json?.result && typeof initOutcome.json.result === "object") {+ const result = initOutcome.json.result as {+ protocolVersion?: unknown;+ serverInfo?: { name?: unknown; version?: unknown };+ capabilities?: unknown;+ };+ if (typeof result.protocolVersion === "string") {+ report.initialize.protocolVersion = result.protocolVersion;+ }+ if (+ result.serverInfo &&+ typeof result.serverInfo.name === "string" &&+ typeof result.serverInfo.version === "string"+ ) {+ report.initialize.serverInfo = {+ name: result.serverInfo.name,+ version: result.serverInfo.version,+ };+ }+ if (result.capabilities && typeof result.capabilities === "object") {+ report.initialize.capabilities = result.capabilities as Record<+ string,+ unknown+ >;+ }+ }++ const sessionId = initOutcome.headers.get("mcp-session-id") ?? undefined;+ report.initialize.hasSessionId = Boolean(sessionId);+ const negotiated = report.initialize.protocolVersion ?? PROTOCOL_VERSION;++ if (initOutcome.status === 401) {+ report.authChallenge = await resolveAuthChallenge(+ initWwwAuthenticate,+ // resolve metadata with a fresh signal — the step's controller is done+ new AbortController().signal,+ );+ report.verdict = "auth-required";+ return report;+ }++ if (!initStep.ok) {+ report.verdict = "unreachable";+ return report;+ }++ // --- Step 2: notifications/initialized (fire-and-forget) ---+ const notifyCtrl = withTimeout(STEP_TIMEOUT_MS);+ try {+ await sendRpc({+ url,+ headers: buildHeaders(input.headers, {+ sessionId,+ protocolVersion: negotiated,+ notification: true,+ }),+ body: {+ jsonrpc: "2.0",+ method: "notifications/initialized",+ },+ signal: notifyCtrl.signal,+ });+ } catch {+ /* notifications are best-effort; ignore failures */+ } finally {+ notifyCtrl.cancel();+ }++ // --- Step 3: ping + tools/list in parallel ---+ const pingStarted = Date.now();+ const toolsStarted = Date.now();+ const pingCtrl = withTimeout(STEP_TIMEOUT_MS);+ const toolsCtrl = withTimeout(STEP_TIMEOUT_MS);++ type SettledRpc = {+ outcome?: RpcOutcome;+ error?: { code: StepErrorCode; message: string };+ };++ const followUpHeaders = () =>+ buildHeaders(input.headers, {+ sessionId,+ protocolVersion: negotiated,+ });++ const pingPromise: Promise<SettledRpc> = sendRpc({+ url,+ headers: followUpHeaders(),+ body: STEP_REQUEST_BODIES.ping,+ expectedId: REQ_ID_PING,+ signal: pingCtrl.signal,+ })+ .then((outcome): SettledRpc => ({ outcome }))+ .catch((err): SettledRpc => ({ error: classifyFetchError(err) }))+ .finally(() => pingCtrl.cancel());++ const toolsPromise: Promise<SettledRpc> = sendRpc({+ url,+ headers: followUpHeaders(),+ body: STEP_REQUEST_BODIES.toolsList,+ expectedId: REQ_ID_TOOLS,+ signal: toolsCtrl.signal,+ })+ .then((outcome): SettledRpc => ({ outcome }))+ .catch((err): SettledRpc => ({ error: classifyFetchError(err) }))+ .finally(() => toolsCtrl.cancel());++ const [pingRes, toolsRes] = await Promise.all([pingPromise, toolsPromise]);++ let pingWwwAuth: string | null = null;+ if (pingRes.error) {+ report.ping = {+ ok: false,+ latencyMs: Date.now() - pingStarted,+ error: pingRes.error,+ };+ } else if (pingRes.outcome) {+ pingWwwAuth = pingRes.outcome.headers.get("www-authenticate");+ report.ping = stepFromOutcome({+ outcome: pingRes.outcome,+ startedAt: pingStarted,+ expectedId: REQ_ID_PING,+ });+ }++ let toolsWwwAuth: string | null = null;+ if (toolsRes.error) {+ report.toolsList = {+ ok: false,+ latencyMs: Date.now() - toolsStarted,+ error: toolsRes.error,+ };+ } else if (toolsRes.outcome) {+ toolsWwwAuth = toolsRes.outcome.headers.get("www-authenticate");+ const toolsStep = stepFromOutcome({+ outcome: toolsRes.outcome,+ startedAt: toolsStarted,+ expectedId: REQ_ID_TOOLS,+ });+ report.toolsList = { ...report.toolsList, ...toolsStep };+ const result = toolsRes.outcome.json?.result;+ if (result && typeof result === "object" && "tools" in result) {+ const raw = (result as { tools?: unknown }).tools;+ if (Array.isArray(raw)) {+ const TOOLS_CAP = 50;+ const parsed = raw+ .map((t): ToolInfo | null => {+ if (!t || typeof t !== "object") return null;+ const obj = t as {+ name?: unknown;+ title?: unknown;+ description?: unknown;+ annotations?: {+ title?: unknown;+ readOnlyHint?: unknown;+ destructiveHint?: unknown;+ idempotentHint?: unknown;+ openWorldHint?: unknown;+ };+ };+ if (typeof obj.name !== "string") return null;+ const info: ToolInfo = { name: obj.name };+ const title =+ typeof obj.title === "string"+ ? obj.title+ : typeof obj.annotations?.title === "string"+ ? obj.annotations.title+ : undefined;+ if (title) info.title = title;+ if (typeof obj.description === "string") {+ info.description = obj.description;+ }+ const ann = obj.annotations;+ if (ann) {+ const hints: ToolInfo["annotations"] = {};+ if (typeof ann.readOnlyHint === "boolean")+ hints.readOnlyHint = ann.readOnlyHint;+ if (typeof ann.destructiveHint === "boolean")+ hints.destructiveHint = ann.destructiveHint;+ if (typeof ann.idempotentHint === "boolean")+ hints.idempotentHint = ann.idempotentHint;+ if (typeof ann.openWorldHint === "boolean")+ hints.openWorldHint = ann.openWorldHint;+ if (Object.keys(hints).length > 0) info.annotations = hints;+ }+ return info;+ })+ .filter((t): t is ToolInfo => t !== null);+ report.toolsList.toolCount = raw.length;+ report.toolsList.tools = parsed.slice(0, TOOLS_CAP);+ report.toolsList.truncated = raw.length > TOOLS_CAP;+ }+ }+ }++ // Verdict resolution+ const authStatus =+ pingRes.outcome?.status === 401 || toolsRes.outcome?.status === 401;+ if (authStatus) {+ report.authChallenge = await resolveAuthChallenge(+ pingWwwAuth ?? toolsWwwAuth,+ new AbortController().signal,+ );+ report.verdict = "auth-required";+ return report;+ }++ if (report.ping.ok && report.toolsList.ok) {+ report.verdict = "healthy";+ } else if (report.ping.ok) {+ report.verdict = "partial";+ } else {+ report.verdict = "unreachable";+ }++ return report;+}++/**+ * Persisted shape: same as `HealthCheckReport` but with stricter caps and the+ * URL re-normalized. Request headers are never persisted.+ */+export function toPersistedReport(+ report: HealthCheckReport,+): HealthCheckReport {+ const PERSIST_RAW_CAP = 16_384;+ const capStep = <T extends StepResult>(step: T): T => {+ if (!step.rawBody) return step;+ return step.rawBody.length > PERSIST_RAW_CAP+ ? {+ ...step,+ rawBody: `${step.rawBody.slice(0, PERSIST_RAW_CAP)}…[truncated]`,+ }+ : step;+ };+ return {+ ...report,+ url: normalizeUrlForStorage(report.url),+ initialize: capStep(report.initialize),+ ping: capStep(report.ping),+ toolsList: capStep(report.toolsList),+ };+}++export function reportRedisKey(id: string) {+ return `mcp-health:report:${id}`;+}++const REPORT_TTL_SECONDS = 60 * 60 * 24 * 7;++export async function storeHealthReport(+ id: string,+ report: HealthCheckReport,+): Promise<void> {+ // Validate before write so we never persist a shape `getHealthReportById`+ // would reject. Soft-fail (log + return) rather than throw so the caller's+ // `after()` callback can still run analytics.+ const result = healthCheckReportSchema.safeParse(report);+ if (!result.success) {+ console.warn("mcp-health: refused to store malformed report", result.error);+ return;+ }+ await redis.set(reportRedisKey(id), JSON.stringify(result.data), {+ ex: REPORT_TTL_SECONDS,+ });+}++export async function getHealthReportById(+ id: string,+): Promise<HealthCheckReport | null> {+ try {+ const raw = await redis.get<unknown>(reportRedisKey(id));+ if (raw == null) return null;+ const candidate = typeof raw === "string" ? JSON.parse(raw) : raw;+ const result = healthCheckReportSchema.safeParse(candidate);+ if (!result.success) {+ console.warn("mcp-health: discarded malformed report", id, result.error);+ return null;+ }+ return result.data;+ } catch (error) {+ console.error("getHealthReportById failed", error);+ return null;+ }+}diff --git a/apps/web/src/lib/mcp/protocol.ts b/apps/web/src/lib/mcp/protocol.tsnew file mode 100644index 000000000..110488188--- /dev/null+++ b/apps/web/src/lib/mcp/protocol.ts@@ -0,0 +1,31 @@+// Edge-safe + client-safe: pure constants only, no imports.+// Shared by the health-check runner (server) and the detail dialog (client) so+// the displayed request bodies can't drift from what's actually sent.+// MCP spec: https://modelcontextprotocol.io/specification/2025-06-18++export const PROTOCOL_VERSION = "2025-06-18";+export const CLIENT_INFO = {+ name: "openstatus-health-check",+ version: "1.0.0",+};++export const REQ_ID_INIT = "openstatus-init";+export const REQ_ID_PING = "openstatus-ping";+export const REQ_ID_TOOLS = "openstatus-tools";++export const STEP_REQUEST_BODIES = {+ initialize: {+ jsonrpc: "2.0",+ id: REQ_ID_INIT,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ clientInfo: CLIENT_INFO,+ capabilities: {},+ },+ },+ ping: { jsonrpc: "2.0", id: REQ_ID_PING, method: "ping" },+ toolsList: { jsonrpc: "2.0", id: REQ_ID_TOOLS, method: "tools/list" },+} as const;++export type StepKey = keyof typeof STEP_REQUEST_BODIES;diff --git a/packages/analytics/src/events.ts b/packages/analytics/src/events.tsindex a4d0c474e..c71a76a4f 100644--- a/packages/analytics/src/events.ts+++ b/packages/analytics/src/events.ts@@ -192,4 +192,8 @@ export const Events = {name: "global_speed_checker",channel: "checker",},+ MCPHealthCheck: {+ name: "mcp_health_check",+ channel: "checker",+ },} as const satisfies Record<string, EventProps>;