ext-apps/tests/e2e/servers.spec.ts
Olivier Chafik 366aa9b66e
examples: Add CesiumJS Map App example (#235)
* feat: Add CesiumJS map server example

A WebGL-based 3D globe example that demonstrates:
- CesiumJS integration with MCP Apps
- CSP configuration for external tile servers
- worker-src directive usage for tile decoding

Tools:
- geocode: Search places via OpenStreetMap Nominatim
- show-map: Display interactive 3D globe at coordinates

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* comment out app.registerTool call for now

* prettier

* fix error handling in server-utils.ts

* refactor: rename cesium-map-server to map-server

- Rename examples/cesium-map-server to examples/map-server
- Update package name to @modelcontextprotocol/server-map
- Add README.md with documentation

* style: add min-height of 400px to map container

* feat(map-server): add fullscreen support, clean UI, sharp rendering

- Add fullscreen toggle button (only shown if host supports it)
- Use autoResize: false and manually send height of 400px
- Hide Cesium UI controls (home, scene mode picker)
- Remove location label (gets stale quickly)
- Use full device pixel ratio for sharp rendering on high-DPI displays
- Resize Cesium viewer when display mode changes

* feat(map-server): add reverse geocoding (logging only) and rounded corners

- Add camera move end listener for reverse geocoding
- Debounce Nominatim API calls (1.5s) to respect rate limits
- Log location name to console on camera move
- Add nominatim.openstreetmap.org to CSP connectDomains
- Add 8px rounded corners to map container

* fix(map-server): fix pixelated rendering on high-DPI displays

- Set canvas imageRendering to 'auto' (CesiumJS defaults to pixelated)
- Set resolutionScale to window.devicePixelRatio for native resolution

* tweaks

* update model context w/ current location

* fix(map-server): improve rendering quality and add visible extent logging

Rendering fixes:
- Remove incorrect resolutionScale = devicePixelRatio which was doubling
  the scaling factor on Retina displays (2x2=4x), causing blurriness
- Disable FXAA anti-aliasing which can cause blurriness on high-DPI displays
- Keep useBrowserRecommendedResolution: false to use native devicePixelRatio

Reverse geocoding improvements:
- Add getVisibleExtent() using camera.computeViewRectangle() to get the
  visible bounding box (west, south, east, north)
- Add getScaleDimensions() to calculate visible area in km
- Add calculateNominatimZoom() to map visible extent to appropriate
  Nominatim zoom level (3=country to 18=building)
- Log visible extent with dimensions on each camera move
- Pass zoom parameter to Nominatim for context-aware geocoding results
- Update model context with visible area dimensions

* fix(map-server): direct positioning + wait for tiles before showing

Changes:
- Remove zoom granularity logic from reverse geocoding (was not working)
- Keep extent logging in both console and model context
- Replace flyTo animation with instant setView positioning
- Add waitForTilesLoaded() to detect when tiles finish loading
- Keep loading spinner visible until:
  1. Tool input positions camera to destination
  2. Tiles at destination are fully loaded
- Add 5-second fallback timeout if no tool input received
- Add 10-second timeout for tile loading to prevent infinite wait

* feat(map-server): use viewbox search to find visible places

Replace center-point reverse geocoding with Nominatim viewbox search:
- Add searchPlacesInBox() that queries Nominatim with bounded viewbox
- Uses layer=address&featuretype=settlement to find cities/towns
- Returns up to 5 visible places in the current view
- Update model context with 'Visible places: City1, City2, ...'
- Still includes center coordinates and extent dimensions

This provides better context about what's actually visible on the map
rather than just the address at the center point.

* fix(map-server): use CARTO @2x retina tiles for sharp rendering

Root cause: Standard OSM tiles are 256x256 pixels. On Retina displays
(devicePixelRatio=2), these get scaled up 2x, making them look pixelated.

Solution: Switch to CARTO Voyager tiles which provide @2x retina support:
- Detect high-DPI displays using window.devicePixelRatio
- Use 512x512 tiles with @2x suffix on Retina displays
- Use 256x256 tiles on standard displays
- Set tileWidth/tileHeight to match actual tile size
- Use CARTO subdomains (a,b,c,d) for load balancing
- Update CSP to allow CARTO tile domains

CARTO Voyager provides clean OSM-based tiles with free @2x retina support,
no API key required.

* fix(map-server): use OSM tiles and fix reverse geocoding

- Switch back from CARTO to standard OSM tiles (tile.openstreetmap.org)
  for better detail and label rendering
- Fix geocoding: use reverse geocode API instead of search API
  (search API requires a q= parameter, returns 400 without it)
- Update CSP domains for OSM tile server

* fix(map-server): use *.openstreetmap.org wildcard in CSP

Simplify CSP to use wildcard for both tiles and geocoding:
- connectDomains: *.openstreetmap.org covers tile.* and nominatim.*
- resourceDomains: *.openstreetmap.org for tile images

* feat(map-server): multi-point sampling for visible places

- Sample multiple points in visible extent to discover places
- Adaptive sampling based on extent size:
  - < 30km: center only (city zoom)
  - 30-100km: center + 2 corners
  - > 100km: center + 4 quadrants
- Proper rate limiting for Nominatim (1.1s between requests)
- Shows 'Visible places: City1, City2, ...' in model context
- Fix: move geocode tool registration inside createServer()

* format

* fix(map-server): fix Express listen callback + add e2e tests

- Fix incorrect Express listen() callback signature (err param doesn't exist)
- Add map-server to e2e test suite with SLOW_SERVERS timeout (5s for tiles)
- Improve comment about experimental ui/update-model-context API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 12:13:56 +00:00

190 lines
7.1 KiB
TypeScript

import { test, expect, type Page, type ConsoleMessage } from "@playwright/test";
// Dynamic element selectors to mask for screenshot comparison
// Note: CSS modules generate unique class names, so we use attribute selectors
// with partial matches (e.g., [class*="heatmapWrapper"]) for those components
const DYNAMIC_MASKS: Record<string, string[]> = {
integration: ["#server-time"], // Server time display
"basic-preact": ["#server-time"], // Server time display
"basic-react": ["#server-time"], // Server time display
"basic-solid": ["#server-time"], // Server time display
"basic-svelte": ["#server-time"], // Server time display
"basic-vanillajs": ["#server-time"], // Server time display
"basic-vue": ["#server-time"], // Server time display
"cohort-heatmap": ['[class*="heatmapWrapper"]'], // Heatmap grid (random data)
"customer-segmentation": [".chart-container"], // Scatter plot (random data)
// Note: map-server uses SLOW_SERVERS timeout instead of masking to wait for tiles
"system-monitor": [
".chart-container", // CPU chart (highly dynamic)
"#status-text", // Current timestamp
"#memory-percent", // Memory percentage
"#memory-detail", // Memory usage details
"#memory-bar-fill", // Memory bar fill level
"#info-uptime", // System uptime
],
threejs: ["#threejs-canvas", ".threejs-container"], // 3D render canvas (dynamic animation)
"wiki-explorer": ["#graph"], // Force-directed graph (dynamic layout)
};
// Servers that need extra stabilization time (e.g., for tile loading, WebGL init)
const SLOW_SERVERS: Record<string, number> = {
"map-server": 5000, // CesiumJS needs time for tiles to load
threejs: 2000, // Three.js WebGL initialization
};
// Server configurations (key is used for screenshot filenames, name is the MCP server name)
const SERVERS = [
{ key: "integration", name: "Integration Test Server" },
{ key: "basic-preact", name: "Basic MCP App Server (Preact)" },
{ key: "basic-react", name: "Basic MCP App Server (React)" },
{ key: "basic-solid", name: "Basic MCP App Server (Solid)" },
{ key: "basic-svelte", name: "Basic MCP App Server (Svelte)" },
{ key: "basic-vanillajs", name: "Basic MCP App Server (Vanilla JS)" },
{ key: "basic-vue", name: "Basic MCP App Server (Vue)" },
{ key: "budget-allocator", name: "Budget Allocator Server" },
{ key: "cohort-heatmap", name: "Cohort Heatmap Server" },
{ key: "customer-segmentation", name: "Customer Segmentation Server" },
{ key: "map-server", name: "CesiumJS Map Server" },
{ key: "scenario-modeler", name: "SaaS Scenario Modeler" },
{ key: "sheet-music", name: "Sheet Music Server" },
{ key: "system-monitor", name: "System Monitor Server" },
{ key: "threejs", name: "Three.js Server" },
{ key: "wiki-explorer", name: "Wiki Explorer" },
];
/**
* Helper to get the app frame locator (nested: sandbox > app)
*/
function getAppFrame(page: Page) {
return page.frameLocator("iframe").first().frameLocator("iframe").first();
}
/**
* Collect console messages with [HOST] prefix
*/
function captureHostLogs(page: Page): string[] {
const logs: string[] = [];
page.on("console", (msg: ConsoleMessage) => {
const text = msg.text();
if (text.includes("[HOST]")) {
logs.push(text);
}
});
return logs;
}
/**
* Wait for the MCP App to load inside nested iframes.
* Structure: page > iframe (sandbox) > iframe (app)
*/
async function waitForAppLoad(page: Page) {
const outerFrame = page.frameLocator("iframe").first();
await expect(outerFrame.locator("iframe")).toBeVisible();
}
/**
* Load a server by selecting it by name and clicking Call Tool
*/
async function loadServer(page: Page, serverName: string) {
await page.goto("/");
// Wait for servers to connect (select becomes enabled when servers are ready)
await expect(page.locator("select").first()).toBeEnabled({ timeout: 30000 });
await page.locator("select").first().selectOption({ label: serverName });
await page.click('button:has-text("Call Tool")');
await waitForAppLoad(page);
}
/**
* Get mask locators for dynamic elements inside the nested app iframe.
*/
function getMaskLocators(page: Page, serverKey: string) {
const selectors = DYNAMIC_MASKS[serverKey];
if (!selectors) return [];
const appFrame = getAppFrame(page);
return selectors.map((selector) => appFrame.locator(selector));
}
test.describe("Host UI", () => {
test("initial state shows controls", async ({ page }) => {
await page.goto("/");
await expect(page.locator("label:has-text('Server')")).toBeVisible();
await expect(page.locator("label:has-text('Tool')")).toBeVisible();
await expect(page.locator('button:has-text("Call Tool")')).toBeVisible();
});
test("screenshot of initial state", async ({ page }) => {
await page.goto("/");
await expect(page.locator('button:has-text("Call Tool")')).toBeVisible();
await expect(page).toHaveScreenshot("host-initial.png");
});
});
// Define tests for each server using forEach to avoid for-loop issues
SERVERS.forEach((server) => {
test.describe(server.name, () => {
test("loads app UI", async ({ page }) => {
await loadServer(page, server.name);
});
test("screenshot matches golden", async ({ page }) => {
await loadServer(page, server.name);
// Some servers (WebGL, tile-based) need extra stabilization time
const stabilizationMs = SLOW_SERVERS[server.key] ?? 500;
await page.waitForTimeout(stabilizationMs);
// Get mask locators for dynamic content (timestamps, charts, etc.)
const mask = getMaskLocators(page, server.key);
await expect(page).toHaveScreenshot(`${server.key}.png`, {
mask,
maxDiffPixelRatio: 0.06,
});
});
});
});
// Interaction tests for integration server (tests all SDK communication APIs)
const integrationServer = SERVERS.find((s) => s.key === "integration")!;
test.describe(`${integrationServer.name} - Interactions`, () => {
test("Send Message button triggers host callback", async ({ page }) => {
const logs = captureHostLogs(page);
await loadServer(page, integrationServer.name);
const appFrame = getAppFrame(page);
await appFrame.locator('button:has-text("Send Message")').click();
// Wait for the async message to be processed
await page.waitForTimeout(500);
expect(logs.some((log) => log.includes("Message from MCP App"))).toBe(true);
});
test("Send Log button triggers host callback", async ({ page }) => {
const logs = captureHostLogs(page);
await loadServer(page, integrationServer.name);
const appFrame = getAppFrame(page);
await appFrame.locator('button:has-text("Send Log")').click();
await page.waitForTimeout(500);
expect(logs.some((log) => log.includes("Log message from MCP App"))).toBe(
true,
);
});
test("Open Link button triggers host callback", async ({ page }) => {
const logs = captureHostLogs(page);
await loadServer(page, integrationServer.name);
const appFrame = getAppFrame(page);
await appFrame.locator('button:has-text("Open Link")').click();
await page.waitForTimeout(500);
expect(logs.some((log) => log.includes("Open link request"))).toBe(true);
});
});