Skip to main content
Glama
saadkamal

MonstarX Singapore MCP

by saadkamal
README.md
# MonstarX Singapore MCP

A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gives AI agents and applications live, structured access to **Singapore government open data** โ€” weather, transport, carparks, property prices, company registry, geocoding, and more.

It wraps official public APIs (data.gov.sg, LTA DataMall, OneMap/SLA, NEA, ACRA, HDB, MOE) behind **35 clean, well-described tools** with a consistent, provenance-stamped response format. No API keys or authentication are required for clients โ€” the server handles upstream credentials for you.

> ๐ŸŽฎ **Live playground:** **https://sg-mcp-playground-production.up.railway.app** โ€” pick a tool, tweak the inputs, hit **Run**, and see real Singapore data render as maps, weather cards, tables and JSON, right in your browser.
>
> ๐Ÿ”Œ **MCP endpoint (staging):** `https://sg-mcp-staging.monstarxapp.com/mcp`
> Server version `0.1.0` ยท Protocol: MCP ยท Transport: **Streamable HTTP**

This repository contains the **playground / documentation site** (a self-contained static page) and a tiny server to host it. See [Run locally & deploy](#run-locally--deploy).

---

## Table of contents

- [Run locally & deploy](#run-locally--deploy)
- [Repository layout](#repository-layout)
- [Quick start](#quick-start)
- [Connecting from MCP clients](#connecting-from-mcp-clients)
  - [Claude Code](#claude-code)
  - [Claude Desktop](#claude-desktop)
  - [Cursor / Windsurf / other MCP clients](#cursor--windsurf--other-mcp-clients)
- [Endpoints](#endpoints)
- [Transport & protocol details](#transport--protocol-details)
- [Response format](#response-format)
- [Tool reference](#tool-reference)
  - [Open data catalog](#open-data-catalog)
  - [Weather & environment](#weather--environment)
  - [Carparks](#carparks)
  - [Public transport](#public-transport)
  - [Geocoding & addresses](#geocoding--addresses)
  - [Property](#property)
  - [Companies (ACRA)](#companies-acra)
  - [Education (Graduate Employment Survey)](#education-graduate-employment-survey)
  - [Public health](#public-health)
- [Example prompts for AI agents](#example-prompts-for-ai-agents)
- [Code examples](#code-examples)
- [Error handling](#error-handling)
- [Rate limits, caching & data freshness](#rate-limits-caching--data-freshness)
- [Data sources & licensing](#data-sources--licensing)

---

## Run locally & deploy

The site is a **single self-contained HTML file** (`public/index.html`) served by a tiny dependency-free Node server.

```bash
npm start           # serves public/ on http://localhost:8080  (respects $PORT)
```

Because the MCP server sends `Access-Control-Allow-Origin: *`, the in-browser playground calls it directly โ€” no backend needed.

**Deploy to [Railway](https://railway.app):**

```bash
railway up --ci     # uses railway.json (Nixpacks build, /health healthcheck)
```

**Regenerate the page** after editing content (the HTML is generated from `build/`):

```bash
python3 build/build.py     # rewrites public/index.html + singapore-mcp-playground.html
```

## Repository layout

```
โ”œโ”€โ”€ public/index.html            # the playground (what gets served)
โ”œโ”€โ”€ singapore-mcp-playground.html # standalone copy (identical; open locally)
โ”œโ”€โ”€ server.js                    # dependency-free static server, respects $PORT, /health
โ”œโ”€โ”€ package.json                 # start script, Node โ‰ฅ18
โ”œโ”€โ”€ railway.json                 # Railway build + healthcheck config
โ”œโ”€โ”€ build/
โ”‚   โ”œโ”€โ”€ build.py                 # generator for the playground HTML
โ”‚   โ””โ”€โ”€ data.min.json            # tool metadata + captured example responses
โ”œโ”€โ”€ examples/                    # standalone MCP clients (Python, TS, curl, SDK)
โ””โ”€โ”€ README.md
```

---

## Quick start

The server speaks JSON-RPC 2.0 over HTTP. You can talk to it with nothing but `curl`.

**1. Discover the server:**

```bash
curl https://sg-mcp-staging.monstarxapp.com/
```

**2. List available tools:**

```bash
curl -X POST https://sg-mcp-staging.monstarxapp.com/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "mcp-protocol-version: 2025-06-18" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
```

**3. Call a tool** โ€” how many taxis are available in Singapore right now?

```bash
curl -X POST https://sg-mcp-staging.monstarxapp.com/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "mcp-protocol-version: 2025-06-18" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call",
       "params":{"name":"sg_taxi_availability","arguments":{}}}'
```

```jsonc
{
  "result": {
    "content": [{ "type": "text", "text": "{ ...json... }" }],
    "structuredContent": {
      "source": "data.gov.sg",
      "retrieved_at": "2026-07-22T02:06:41.665Z",
      "license": "Singapore Open Data Licence",
      "api": "real-time taxi availability",
      "agency": "LTA",
      "data": { "available_taxis": 3190, "timestamp": "2026-07-22T10:06:23+08:00" }
    }
  },
  "jsonrpc": "2.0",
  "id": 2
}
```

That's it โ€” no auth, no session setup. See [Code examples](#code-examples) for Python and TypeScript clients.

---

## Connecting from MCP clients

This is a **remote (HTTP) MCP server**. Most MCP clients can connect either natively (if they support remote HTTP servers) or through the [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge.

### Claude Code

```bash
claude mcp add --transport http sg-mcp https://sg-mcp-staging.monstarxapp.com/mcp
```

Then in a session: *"Using the sg-mcp tools, what's the 2-hour weather forecast for Tampines?"*

### Claude Desktop

Edit your `claude_desktop_config.json`
(macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):

```jsonc
{
  "mcpServers": {
    "singapore": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://sg-mcp-staging.monstarxapp.com/mcp"]
    }
  }
}
```

Restart Claude Desktop; the 35 `sg_*` tools appear in the tools menu.

### Cursor / Windsurf / other MCP clients

Any client that supports **remote HTTP MCP servers** can use the URL directly:

```jsonc
{
  "mcpServers": {
    "singapore": {
      "type": "http",
      "url": "https://sg-mcp-staging.monstarxapp.com/mcp"
    }
  }
}
```

For clients that only support stdio, use the `mcp-remote` bridge shown in the Claude Desktop example.

---

## Endpoints

| Endpoint | Method | Purpose |
|---|---|---|
| `/` | `GET` | Server info โ€” name, version, build SHA, full tool list |
| `/health` | `GET` | Liveness probe (`{"status":"ok", ...}`) |
| `/mcp` | `POST` | MCP JSON-RPC endpoint (`initialize`, `tools/list`, `tools/call`) |

CORS is open (`Access-Control-Allow-Origin: *`), so browser-based clients work too.

---

## Transport & protocol details

- **Transport:** Streamable HTTP (MCP spec). POST JSON-RPC to `/mcp`.
- **Protocol version:** `2025-06-18` (send it in the `mcp-protocol-version` header).
- **Stateless:** the server does **not** issue an `mcp-session-id`. You do *not* need to call `initialize` before `tools/call` when using raw HTTP โ€” each request is independent. (Full MCP clients will still perform the `initialize` handshake, which the server supports.)
- **Accept header:** include `application/json, text/event-stream`.
- **Auth:** none required.

Minimal request skeleton:

```http
POST /mcp HTTP/1.1
Host: sg-mcp-staging.monstarxapp.com
Content-Type: application/json
Accept: application/json, text/event-stream
mcp-protocol-version: 2025-06-18

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"<tool>","arguments":{...}}}
```

---

## Response format

Every successful tool call returns an MCP result with two mirrored representations of the same payload:

- `content[0].text` โ€” the payload as a JSON **string** (for text-only clients / LLMs).
- `structuredContent` โ€” the same payload as a native **JSON object** (prefer this when parsing programmatically).

Every payload uses a **consistent provenance envelope**:

```jsonc
{
  "source":      "data.gov.sg",                    // upstream platform
  "retrieved_at":"2026-07-22T02:06:41.665Z",       // server fetch time (UTC)
  "license":     "Singapore Open Data Licence",    // when applicable
  "agency":      "LTA",                            // originating gov agency
  "api":         "real-time taxi availability",    // upstream API used
  "data":        { ... }                           // the actual result
}
```

Some tools add top-level context fields (e.g. `query`, `total`, `shown`, `found`, `dataset_id`) alongside `data`/`results`/`companies`. Timestamps in the envelope are UTC; live data timestamps from LTA/NEA are typically SGT (`+08:00`).

---

## Tool reference

All 35 tools are prefixed `sg_`. Required parameters are marked **\***.

### Open data catalog

Generic access to any tabular dataset on data.gov.sg โ€” the escape hatch when no dedicated tool exists.

| Tool | Parameters | Description |
|---|---|---|
| `sg_datasets_search` | `query`, `page` | Search data.gov.sg datasets by keyword (e.g. `"HDB resale"`, `"weather"`). |
| `sg_dataset_metadata` | `dataset_id`**\*** | Get metadata (columns, description) for a dataset ID (starts with `d_`). |
| `sg_dataset_query` | `dataset_id`**\***, `limit`, `offset`, `fields`, `filters`, `q`, `sort` | Query/paginate rows of a tabular dataset. `limit` caps at 1000; `filters` is exact-match by column. |

### Weather & environment

All are real-time NEA feeds and take **no parameters**.

| Tool | Description |
|---|---|
| `sg_weather_2h` | 2-hour weather forecast by area (~47 named areas with coordinates). |
| `sg_weather_24h` | 24-hour outlook: temperature, humidity, wind, regional forecasts. |
| `sg_weather_4day` | 4-day forecast with daily conditions and temperature ranges. |
| `sg_uv_index` | Current UV index readings. |
| `sg_psi` | Pollutant Standards Index by region. |
| `sg_air_quality` | Combined PSI and PM2.5 readings. |
| `sg_rainfall` | Live rainfall (mm) from weather stations. |
| `sg_air_temperature` | Live air temperature (ยฐC) from weather stations. |
| `sg_relative_humidity` | Live relative humidity (%) from weather stations. |

### Carparks

HDB carpark information and real-time lot availability.

| Tool | Parameters | Description |
|---|---|---|
| `sg_carpark_availability` | `carpark_number`, `limit` | Real-time lot availability. Omit `carpark_number` for a Singapore-wide list. |
| `sg_carpark_info` | `carpark_number`, `query`, `limit` | Static info: address, type, gantry height. `query` keyword-searches records. |
| `sg_carpark_search` | `query`**\***, `include_availability`, `limit` | Search carparks by area/address; optionally attach live availability. |
| `sg_carpark_details` | `carpark_number`**\*** | Combined static info + live availability for one carpark (e.g. `"HE12"`). |

### Public transport

LTA DataMall real-time and reference transport data.

| Tool | Parameters | Description |
|---|---|---|
| `sg_bus_arrival` | `bus_stop_code`**\***, `service_no` | Real-time bus arrivals for a stop (e.g. `"83139"`), optionally one service. |
| `sg_bus_stops` | `skip` | List all bus stops with coordinates. Paginate in batches of 500 via `skip`. |
| `sg_bus_services` | `skip` | List all bus services. Paginate in batches of 500. |
| `sg_bus_routes` | `service_no`, `direction`, `bus_stop_code`, `skip`, `max_pages`, `limit` | Routeโ€“stop rows incl. sequence and first/last timings. |
| `sg_bus_first_last` | `service_no`**\***, `direction`, `bus_stop_code`, `max_pages` | Scheduled first/last bus timings for a service. |
| `sg_train_service_alerts` | *(none)* | Current MRT/LRT service alerts. |
| `sg_traffic_incidents` | *(none)* | Current road traffic incidents. |
| `sg_taxi_availability` | *(none)* | Live count of available taxis. |

### Geocoding & addresses

OneMap (Singapore Land Authority) address search and geocoding.

| Tool | Parameters | Description |
|---|---|---|
| `sg_address_search` | `query`**\***, `page` | Search addresses, buildings, roads, postal codes. |
| `sg_geocode` | `query`**\***, `limit` | Address/postal code โ†’ latitude/longitude. |
| `sg_reverse_geocode` | `latitude`**\***, `longitude`**\***, `buffer`, `address_type` | WGS84 coordinate โ†’ nearby addresses. `buffer` = radius in metres. |

### Property

| Tool | Parameters | Description |
|---|---|---|
| `sg_hdb_resale_prices` | `town`, `flat_type`, `limit`, `offset`, `sort` | HDB resale flat transactions. e.g. `town:"TAMPINES"`, `flat_type:"4 ROOM"`, `sort:"month desc"`. |

### Companies (ACRA)

Singapore's registry of business entities.

| Tool | Parameters | Description |
|---|---|---|
| `sg_company_search` | `query`**\***, `limit` | Search registered entities by name (e.g. `"DBS"`). |
| `sg_company_by_uen` | `uen`**\*** | Look up an entity by Unique Entity Number (e.g. `"198600294G"`). |
| `sg_company_verify` | `company_name`**\***, `limit` | Verify whether an entity exists / find close registered matches. |

### Education (Graduate Employment Survey)

MOE Graduate Employment Survey โ€” salaries and employment outcomes by degree.

| Tool | Parameters | Description |
|---|---|---|
| `sg_ges_years` | *(none)* | List available survey years. |
| `sg_ges_search` | `degree`, `university`, `school`, `year`, `limit` | Search GES records by degree/university/school/year. |
| `sg_ges_top_degrees` | `year`, `metric`, `order`, `limit` | Rank degrees by a salary/employment metric (e.g. `metric:"gross_monthly_median"`, `order:"desc"`). |

### Public health

| Tool | Parameters | Description |
|---|---|---|
| `sg_dengue_clusters` | `min_cases`, `limit`, `include_geometry` | Active NEA dengue clusters. Set `include_geometry:true` for map polygons. |

---

## Example prompts for AI agents

Natural-language prompts an agent can satisfy using these tools:

- *"Is it going to rain in Jurong in the next 2 hours?"* โ†’ `sg_weather_2h`
- *"What's the UV index right now โ€” do I need sunscreen?"* โ†’ `sg_uv_index`
- *"Find HDB carparks near Tampines with available lots right now."* โ†’ `sg_carpark_search` (`include_availability:true`)
- *"When's the next bus 15 at stop 83139?"* โ†’ `sg_bus_arrival`
- *"Are there any train delays this morning?"* โ†’ `sg_train_service_alerts`
- *"Any traffic incidents on the expressways right now?"* โ†’ `sg_traffic_incidents`
- *"What did 4-room flats in Tampines sell for recently?"* โ†’ `sg_hdb_resale_prices`
- *"Which NUS degrees had the highest median starting salary in 2022?"* โ†’ `sg_ges_top_degrees`
- *"Is 'DBS Bank Ltd' a registered company? What's its UEN?"* โ†’ `sg_company_verify` / `sg_company_search`
- *"Get the coordinates of ION Orchard (postal 238801)."* โ†’ `sg_geocode`
- *"What's near latitude 1.2834, longitude 103.8607?"* โ†’ `sg_reverse_geocode`
- *"Where are the active dengue clusters with 10+ cases?"* โ†’ `sg_dengue_clusters`

**System-prompt hint for agents:** *"You have access to the Singapore MCP server (`sg_*` tools) for live Singapore data โ€” weather, transport, carparks, HDB prices, companies, geocoding. Prefer the specific tool over the generic `sg_dataset_query`. Always cite the `source`/`agency` and `retrieved_at` from responses when reporting live figures."*

---

## Code examples

Runnable clients live in [`examples/`](examples/):

- [`examples/curl.sh`](examples/curl.sh) โ€” pure shell / curl.
- [`examples/client.py`](examples/client.py) โ€” Python (stdlib only, no dependencies).
- [`examples/client.ts`](examples/client.ts) โ€” TypeScript / Node (fetch).
- [`examples/mcp_sdk_client.py`](examples/mcp_sdk_client.py) โ€” using the official `mcp` Python SDK.

### Python (no dependencies)

```python
import json, urllib.request

BASE = "https://sg-mcp-staging.monstarxapp.com/mcp"

def call_tool(name, arguments=None):
    body = json.dumps({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": {"name": name, "arguments": arguments or {}},
    }).encode()
    req = urllib.request.Request(BASE, data=body, headers={
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "mcp-protocol-version": "2025-06-18",
    })
    with urllib.request.urlopen(req) as r:
        result = json.load(r)["result"]
    if result.get("isError"):
        raise RuntimeError(result["content"][0]["text"])
    return result["structuredContent"]

taxis = call_tool("sg_taxi_availability")
print("Available taxis:", taxis["data"]["available_taxis"])

carparks = call_tool("sg_carpark_search",
                     {"query": "TAMPINES", "include_availability": True, "limit": 3})
print(json.dumps(carparks, indent=2))
```

### TypeScript / Node

```ts
const BASE = "https://sg-mcp-staging.monstarxapp.com/mcp";

async function callTool(name: string, args: Record<string, unknown> = {}) {
  const res = await fetch(BASE, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json, text/event-stream",
      "mcp-protocol-version": "2025-06-18",
    },
    body: JSON.stringify({
      jsonrpc: "2.0", id: 1, method: "tools/call",
      params: { name, arguments: args },
    }),
  });
  const { result } = await res.json();
  if (result.isError) throw new Error(result.content[0].text);
  return result.structuredContent;
}

const w = await callTool("sg_weather_2h");
console.log(w.data.items?.[0] ?? w.data);
```

---

## Error handling

Errors are returned as a **normal JSON-RPC result** with `isError: true` (not as a JSON-RPC top-level `error`). The message is in `content[0].text`.

**Invalid / missing arguments** โ†’ MCP error `-32602`:

```jsonc
{
  "result": {
    "content": [{ "type": "text",
      "text": "MCP error -32602: Input validation error: Invalid arguments for tool sg_company_by_uen: [{\"expected\":\"string\",\"path\":[\"uen\"],\"message\":\"expected string, received undefined\"}]" }],
    "isError": true
  }
}
```

**Unknown tool** โ†’ `MCP error -32602: Tool <name> not found`.

**No matching data** is *not* an error โ€” you get a normal envelope with an empty `data`/`results` array (e.g. querying an unknown bus stop returns `"Services": []`). Always check for empty results in addition to `isError`.

Handling pattern:

```python
if result.get("isError"):
    # inspect result["content"][0]["text"]
    ...
else:
    payload = result["structuredContent"]
    if not payload.get("data") and not payload.get("results"):
        # valid call, no matches
        ...
```

---

## Rate limits, caching & data freshness

- **Freshness:** real-time feeds (weather, taxi, bus arrivals, carpark availability, traffic) reflect the upstream agency's latest publish. Check `retrieved_at` (server fetch, UTC) and the upstream `timestamp` (usually SGT) in the payload.
- **Reference data** (bus stops/services/routes, carpark info, datasets) changes rarely; safe to cache client-side.
- **Rate limits:** the server proxies rate-limited government APIs (notably LTA DataMall). Be a good citizen โ€” cache reference data, avoid tight polling loops, and back off on errors. This is a **staging** deployment; do not use it for production load.

---

## Data sources & licensing

Data is sourced from official Singapore government platforms and remains subject to their terms:

| Platform | Agencies | Used by |
|---|---|---|
| [data.gov.sg](https://data.gov.sg) | NEA, HDB, ACRA, MOE, LTA | weather, carparks, HDB, companies, GES, catalog |
| [LTA DataMall](https://datamall.lta.gov.sg) | LTA | bus, train, traffic, taxi |
| [OneMap](https://www.onemap.gov.sg) | SLA | address search, geocoding |

Most datasets are provided under the **Singapore Open Data Licence** (echoed in each response's `license` field). LTA DataMall and OneMap data are subject to their respective terms of use. You are responsible for complying with the source licences when using or redistributing the data. This MCP server is an independent wrapper and is not endorsed by any government agency.

---

*Server: `Monstarx Singapore MCP` v0.1.0 ยท staging ยท This documentation was generated by testing the live endpoint on 2026-07-22.*