geojson_to_csv
Convert GeoJSON geographic data to CSV format for analysis in spreadsheet applications. Include all feature properties or customize the output.
Instructions
Convert GeoJSON to CSV format
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| geojson | Yes | GeoJSON object to convert | |
| includeAllProperties | No | Include all feature properties in the CSV |
Implementation Reference
- src/index.ts:415-502 (handler)The primary handler function for the 'geojson_to_csv' tool. Converts GeoJSON FeatureCollection to CSV by extracting latitude/longitude from geometries (using centroids for non-points) and all feature properties.
async geojsonToCSV(args: any): Promise<ToolResponse> { const { geojson, includeAllProperties = true } = args; if (!geojson || !geojson.features) { throw new McpError( ErrorCode.InvalidParams, 'Invalid GeoJSON: missing features array' ); } try { console.error('[Converting] GeoJSON to CSV'); // Extract all unique property keys const properties = new Set<string>(); geojson.features.forEach((feature: any) => { if (feature.properties) { Object.keys(feature.properties).forEach(key => properties.add(key)); } }); // Always include geometry columns const headers = ['latitude', 'longitude', ...Array.from(properties)]; // Generate CSV rows let csvRows = [headers.join(',')]; geojson.features.forEach((feature: any) => { // Extract coordinates (handling different geometry types) let lat: number | string = ''; let lon: number | string = ''; if (feature.geometry.type === 'Point') { [lon, lat] = feature.geometry.coordinates; } else if (feature.geometry.type === 'Polygon') { const centroid = this.getCentroid(feature.geometry.coordinates[0]); lon = centroid[0]; lat = centroid[1]; } else if (feature.geometry.type === 'LineString' || feature.geometry.type === 'MultiPoint') { // Use first coordinate for these types [lon, lat] = feature.geometry.coordinates[0]; } else if (feature.geometry.type === 'MultiPolygon') { // Use the centroid of the first polygon const centroid = this.getCentroid(feature.geometry.coordinates[0][0]); lon = centroid[0]; lat = centroid[1]; } else if (feature.geometry.type === 'MultiLineString') { // Use the first point of the first linestring [lon, lat] = feature.geometry.coordinates[0][0]; } else if (feature.geometry.type === 'GeometryCollection') { // Use the first geometry if (feature.geometry.geometries && feature.geometry.geometries.length > 0) { const firstGeom = feature.geometry.geometries[0]; if (firstGeom.type === 'Point') { [lon, lat] = firstGeom.coordinates; } else if (firstGeom.type === 'Polygon') { const centroid = this.getCentroid(firstGeom.coordinates[0]); lon = centroid[0]; lat = centroid[1]; } } } // Convert coordinates to strings for CSV const latStr = String(lat); const lonStr = String(lon); // Build row with all properties const row = [latStr, lonStr]; properties.forEach(prop => { const value = feature.properties && feature.properties[prop] !== undefined ? feature.properties[prop] : ''; // Make sure strings with commas are properly quoted row.push(typeof value === 'string' ? `"${value.replace(/"/g, '""')}"` : value); }); csvRows.push(row.join(',')); }); return this.formatToolResponse(csvRows.join('\n')); } catch (error) { console.error('[Error] GeoJSON to CSV conversion failed:', error); throw new McpError( ErrorCode.InternalError, `GeoJSON to CSV conversion failed: ${error instanceof Error ? error.message : String(error)}` ); } } - src/index.ts:146-164 (registration)Registration of the 'geojson_to_csv' tool in the ListTools response, including name, description, and input schema definition.
{ name: 'geojson_to_csv', description: 'Convert GeoJSON to CSV format', inputSchema: { type: 'object', properties: { geojson: { type: 'object', description: 'GeoJSON object to convert', }, includeAllProperties: { type: 'boolean', description: 'Include all feature properties in the CSV', default: true, }, }, required: ['geojson'], }, }, - src/index.ts:286-287 (registration)Switch case in CallToolRequest handler that dispatches 'geojson_to_csv' calls to the geojsonToCSV handler method.
case 'geojson_to_csv': return await this.geojsonToCSV(request.params.arguments); - src/index.ts:75-86 (helper)Helper function to compute the centroid of a polygon or ring of points, used in geojsonToCSV for non-Point geometries.
private getCentroid(points: number[][]): number[] { const n = points.length; let sumX = 0; let sumY = 0; for (let i = 0; i < n; i++) { sumX += points[i][0]; sumY += points[i][1]; } return [sumX / n, sumY / n]; } - src/index.ts:63-72 (helper)General helper to format tool responses as required by MCP SDK, used by geojsonToCSV.
private formatToolResponse(text: string): ToolResponse { return { content: [ { type: 'text', text }, ], }; }