ext-apps/examples/map-server/server.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

268 lines
7.5 KiB
TypeScript

/**
* CesiumJS Map MCP Server
*
* Provides tools for:
* - geocode: Search for places using OpenStreetMap Nominatim
* - show-map: Display an interactive 3D globe at a given location
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import type {
CallToolResult,
ReadResourceResult,
} from "@modelcontextprotocol/sdk/types.js";
import fs from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import {
registerAppTool,
registerAppResource,
RESOURCE_MIME_TYPE,
RESOURCE_URI_META_KEY,
} from "@modelcontextprotocol/ext-apps/server";
import { startServer } from "./server-utils.js";
const DIST_DIR = path.join(import.meta.dirname, "dist");
const RESOURCE_URI = "ui://cesium-map/mcp-app.html";
// Nominatim API response type
interface NominatimResult {
place_id: number;
licence: string;
osm_type: string;
osm_id: number;
lat: string;
lon: string;
display_name: string;
boundingbox: [string, string, string, string]; // [south, north, west, east]
class: string;
type: string;
importance: number;
}
// Rate limiting for Nominatim (1 request per second per their usage policy)
let lastNominatimRequest = 0;
const NOMINATIM_RATE_LIMIT_MS = 1100; // 1.1 seconds to be safe
/**
* Query Nominatim geocoding API with rate limiting
*/
async function geocodeWithNominatim(query: string): Promise<NominatimResult[]> {
// Respect rate limit
const now = Date.now();
const timeSinceLastRequest = now - lastNominatimRequest;
if (timeSinceLastRequest < NOMINATIM_RATE_LIMIT_MS) {
await new Promise((resolve) =>
setTimeout(resolve, NOMINATIM_RATE_LIMIT_MS - timeSinceLastRequest),
);
}
lastNominatimRequest = Date.now();
const params = new URLSearchParams({
q: query,
format: "json",
limit: "5",
});
const response = await fetch(
`https://nominatim.openstreetmap.org/search?${params}`,
{
headers: {
"User-Agent":
"MCP-CesiumMap-Example/1.0 (https://github.com/modelcontextprotocol)",
},
},
);
if (!response.ok) {
throw new Error(
`Nominatim API error: ${response.status} ${response.statusText}`,
);
}
return response.json();
}
/**
* Creates a new MCP server instance with tools and resources registered.
* Each HTTP session needs its own server instance because McpServer only supports one transport.
*/
export function createServer(): McpServer {
const server = new McpServer({
name: "CesiumJS Map Server",
version: "1.0.0",
});
// CSP configuration for external tile sources
const cspMeta = {
ui: {
csp: {
// Allow fetching tiles from OSM (tiles + geocoding) and Cesium assets
connectDomains: [
"https://*.openstreetmap.org", // OSM tiles + Nominatim geocoding
"https://cesium.com",
"https://*.cesium.com",
],
// Allow loading tile images, scripts, and Cesium CDN resources
resourceDomains: [
"https://*.openstreetmap.org", // OSM map tiles (covers tile.openstreetmap.org)
"https://cesium.com",
"https://*.cesium.com",
],
},
},
};
// Register the CesiumJS map resource with CSP for external tile sources
registerAppResource(
server,
RESOURCE_URI,
RESOURCE_URI,
{ mimeType: RESOURCE_MIME_TYPE },
async (): Promise<ReadResourceResult> => {
const html = await fs.readFile(
path.join(DIST_DIR, "mcp-app.html"),
"utf-8",
);
return {
contents: [
// _meta must be on the content item, not the resource metadata
{
uri: RESOURCE_URI,
mimeType: RESOURCE_MIME_TYPE,
text: html,
_meta: cspMeta,
},
],
};
},
);
// show-map tool - displays the CesiumJS globe
// Default bounding box: London area
registerAppTool(
server,
"show-map",
{
title: "Show Map",
description:
"Display an interactive world map zoomed to a specific bounding box. Use the GeoCode tool to find the bounding box of a location.",
inputSchema: {
west: z
.number()
.optional()
.default(-0.5)
.describe("Western longitude (-180 to 180)"),
south: z
.number()
.optional()
.default(51.3)
.describe("Southern latitude (-90 to 90)"),
east: z
.number()
.optional()
.default(0.3)
.describe("Eastern longitude (-180 to 180)"),
north: z
.number()
.optional()
.default(51.7)
.describe("Northern latitude (-90 to 90)"),
label: z
.string()
.optional()
.describe("Optional label to display on the map"),
},
_meta: { [RESOURCE_URI_META_KEY]: RESOURCE_URI },
},
async ({ west, south, east, north, label }): Promise<CallToolResult> => ({
content: [
{
type: "text",
text: `Displaying globe at: W:${west.toFixed(4)}, S:${south.toFixed(4)}, E:${east.toFixed(4)}, N:${north.toFixed(4)}${label ? ` (${label})` : ""}`,
},
],
}),
);
// geocode tool - searches for places using Nominatim (no UI)
server.registerTool(
"geocode",
{
title: "Geocode",
description:
"Search for places using OpenStreetMap. Returns coordinates and bounding boxes for up to 5 matches.",
inputSchema: {
query: z
.string()
.describe(
"Place name or address to search for (e.g., 'Paris', 'Golden Gate Bridge', '1600 Pennsylvania Ave')",
),
},
},
async ({ query }): Promise<CallToolResult> => {
try {
const results = await geocodeWithNominatim(query);
if (results.length === 0) {
return {
content: [
{ type: "text", text: `No results found for "${query}"` },
],
};
}
const formattedResults = results.map((r) => ({
displayName: r.display_name,
lat: parseFloat(r.lat),
lon: parseFloat(r.lon),
boundingBox: {
south: parseFloat(r.boundingbox[0]),
north: parseFloat(r.boundingbox[1]),
west: parseFloat(r.boundingbox[2]),
east: parseFloat(r.boundingbox[3]),
},
type: r.type,
importance: r.importance,
}));
const textContent = formattedResults
.map(
(r, i) =>
`${i + 1}. ${r.displayName}\n Coordinates: ${r.lat.toFixed(6)}, ${r.lon.toFixed(6)}\n Bounding box: W:${r.boundingBox.west.toFixed(4)}, S:${r.boundingBox.south.toFixed(4)}, E:${r.boundingBox.east.toFixed(4)}, N:${r.boundingBox.north.toFixed(4)}`,
)
.join("\n\n");
return {
content: [{ type: "text", text: textContent }],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Geocoding error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
},
);
return server;
}
async function main() {
if (process.argv.includes("--stdio")) {
await createServer().connect(new StdioServerTransport());
} else {
const port = parseInt(process.env.PORT ?? "3001", 10);
await startServer(createServer, { port, name: "CesiumJS Map Server" });
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});