# Telkomsel Product Catalog — MCP Server

[![CI](https://github.com/EgiStr/telkomsel-product-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/EgiStr/telkomsel-product-mcp/actions/workflows/ci.yml)
[![Live smoke test](https://github.com/EgiStr/telkomsel-product-mcp/actions/workflows/live-smoke.yml/badge.svg)](https://github.com/EgiStr/telkomsel-product-mcp/actions/workflows/live-smoke.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](package.json)

An MCP server that exposes the real Telkomsel product catalogue to AI agents:
the **11 top-level products** shown on telkomsel.com, plus the **live,
purchasable package catalogue** with current prices, personalised per phone
number.

Every tool is read-only. Nothing here purchases, activates or modifies an
account.

---

## Why this works without an API key

There is no public Telkomsel developer API. The catalogue was recovered by
observing the site's own XHR traffic, and the endpoints answer **with no
credential, cookie or API key at all**.

```
POST https://www.telkomsel.com/api/express-purchase/v1/package/list
content-type: application/json
{"msisdn":"081234455666","menuLevel":"…","filter":{…},"subcategory":""}
```

The full endpoint map, the `menuLevel` contract, and a significant gotcha about
package ids are documented in [`recon/FINDINGS.md`](recon/FINDINGS.md).

---

## Products covered

The catalogue mirrors the site's own `Produk` menu exactly:

| Product | Positioning | Path |
| --- | --- | --- |
| SIMPATI | Prabayar | `/simpati` |
| Halo | Pascabayar | `/halo` |
| by.U | Prabayar Digital | `/byU` |
| IndiHome | Hiburan & Internet Rumah | `/indihome` |
| Orbit | Modem WiFi | `/telkomsel-orbit` |
| EZnet | Internet Rumah Terjangkau | `/eznet` |
| EZnet Wireless | Internet Wireless Terjangkau | `/eznet-wireless` |
| Telkomsel One | Koneksi Dalam & Luar Rumah | `/one` |
| Roaming & SLI | Internet & Sambungan Internasional | `/roaming` |
| 5G | Telkomsel 5G | `/5G` |
| Bundling | Paket Smartphone | `/bundling` |

Each record carries the official display name, the site's positioning line, a
stable slug, a segment grouping, the landing-page URL, and a summary plus
section headings scraped from that page.

---

## Quick start

```bash
npm install
npm run build
```

Register the built server with any MCP client:

```json
{
  "mcpServers": {
    "telkomsel": {
      "command": "node",
      "args": ["D:\\programming\\mcp\\telkomsel-product-mcp\\dist\\index.js"],
      "env": {
        "TSEL_DEFAULT_MSISDN": "081234455666"
      }
    }
  }
}
```

Verify it end to end without a client:

```bash
npm run test:smoke
```

```
Tools exposed (21): …
ALL CHECKS PASSED
```

Or poke at it interactively:

```bash
npm run inspector
```

---

## The dummy number, and how to change it

Every package query is personalised by MSISDN — the categories, the offers, the
prices and the recommendations all change with the number. The server starts on
`081234455666`.

Three ways to change it, in order of scope:

| Scope | How |
| --- | --- |
| One call | Pass `msisdn` to any package tool, e.g. `telkomsel_search_packages { "msisdn": "081298765432" }` |
| Whole session | `telkomsel_set_default_msisdn { "msisdn": "081298765432" }` |
| Server start | Set the env var `TSEL_DEFAULT_MSISDN` |

Numbers are validated before use: they must normalise to a Telkomsel prefix
(`0811, 0812, 0813, 0821, 0822, 0823, 0851, 0852, 0853, 0855`) and be 10–13
digits. `081234455666`, `6281234455666` and `0812-3445-5666` are all accepted.

To confirm which number is live and what it resolves to:

```
telkomsel_get_config          → the number in use and where it came from
telkomsel_check_msisdn        → PREPAID/SIMPATI vs PASCABAYAR/Halo, straight from the API
```

---

## Use it in a Next.js app

```bash
npm install telkomsel-product-mcp
```

```ts
// app/api/mcp/route.ts
import { createMcpHandler } from 'telkomsel-product-mcp';

const handler = createMcpHandler({
  apiKey: process.env.MCP_API_KEY!, // at least 16 characters
});

export { handler as POST, handler as GET, handler as DELETE };

export const runtime = 'nodejs'; // the SDK uses node:crypto, so not Edge
export const dynamic = 'force-dynamic'; // Telkomsel is called live; never cache
```

Point any MCP client at `https://your-app/api/mcp` with `Authorization: Bearer
<MCP_API_KEY>`.

**Why not `spawn` the binary from a route?** A stdio server is a child process, and
serverless platforms (Vercel and the like) do not let a function keep one. The
handler runs in the same process as your route instead.

### Options

| Option | What it does |
| --- | --- |
| `apiKey` | Require `Authorization: Bearer <key>`. At least 16 characters; compared in constant time. |
| `authorize(request)` | Your own check. Return `true`, `false` (401), or a `Response` of your own. May be async. |
| `unauthenticated: true` | Opt out, for a route something else already protects. |
| `allowedOrigins` | Browser origins allowed. Clients with no `Origin` header are unaffected. |
| `defaultMsisdn` | The number used when a call names none. |
| `maxBodyBytes` | Body ceiling, default 1 MiB. |

You must choose one of the first three. The route calls Telkomsel for the caller and
accepts any phone number, so `createMcpHandler()` with no choice **throws** rather
than shipping an open proxy.

### Stateless, on purpose

Each request is served by a new server with its own session, so nothing about a
conversation is shared between requests. That is what lets it run where the next
request may reach another machine. Two consequences:

- **Pass `msisdn` on each call**, or set `defaultMsisdn` once in the handler.
  `telkomsel_set_default_msisdn` refuses on a hosted route, because a value it set
  would be gone before the next call.
- **Use `ref`, not `id`, to refer back to a package.** The upstream mints a new `id`
  on every request, so an `id` is only resolvable while this process still holds it,
  for the same number, and a serverless host may answer the next request from a
  different process. `ref` is recomputed from the catalogue and works anywhere. An
  `id` that the index does not hold is looked for in the catalogue the process is
  holding, and then refused with a not-found error that names the id — the fallback
  cannot find it in a freshly fetched catalogue, because that one carries new ids.
- Responses are JSON, not an event stream. There is no `GET` stream and no session
  to `DELETE`; both answer 405.

### What is shared inside one process

The process keeps two best-effort caches so repeated calls are cheap: the catalogue
(5 minutes) and an index of packages it has shown. **Both are partitioned by phone
number**, and a lookup names its number, so one caller cannot read the packages of
another number. Both are size-bounded, so memory does not grow with the number of
callers. Neither is a guarantee: on serverless a fresh process starts empty.

### Not Next.js? Use the factory

```ts
import { createTelkomselServer } from 'telkomsel-product-mcp';

const { server } = createTelkomselServer({ defaultMsisdn: '081234455666' });
await server.connect(yourTransport); // any MCP transport
```

`createMcpHandler` is built on this. Every call returns an independent server with
its own session, so two servers in one process never share a default number.

## Tools (21)

**Retrieval planning**

| Tool | Purpose |
| --- | --- |
| `telkomsel_get_capabilities` | Machine-readable route manifest: what this route can answer, which tool fits a question shape, which fields exist with their units, which fields this route is authoritative for, and the Indonesian catalogue vocabulary. Static, so it costs no upstream request. |

`telkomsel_get_capabilities` deliberately does not repeat tool names, descriptions or JSON schemas — MCP already publishes those through `tools/list`. It carries only the semantic layer the protocol has no field for. A retrieval router reads it once to plan, then calls the real tools.

**Products**

| Tool | Purpose |
| --- | --- |
| `telkomsel_list_products` | The 11-product catalogue, filterable by segment or type |
| `telkomsel_get_product` | One product in detail; `live: true` re-scrapes the official page |
| `telkomsel_list_segments` | Valid segment and type values, with counts |
| `telkomsel_product_page_raw` | Live headings + summary for any telkomsel.com path |
| `telkomsel_latest_content` | The newest news or promos on telkomsel.com (first page of the site list), with links and dates |
| `telkomsel_read_content` | One news article or promo page in full: text, promo period (and whether it ended), how to take part, FAQ and terms |
| `telkomsel_site_search` | The telkomsel.com search box: promo pages, FAQ entries and news for a phrase, with link and snippet. Not for package prices |

**Packages**

| Tool | Purpose |
| --- | --- |
| `telkomsel_list_package_categories` | The live categories for this number, with package counts |
| `telkomsel_list_subcategories` | Subcategory labels inside a category |
| `telkomsel_resolve_intent` | Turn what a customer says ("paket buat nonton", "mau ke luar negeri", "yang rupiah/gb nya paling kecil") into the terms the catalogue actually answers **and the order it asks for**, with live counts |
| `telkomsel_search_packages` | The main catalogue query: category, subcategory, free text, price, quota range, masa aktif, roaming, sort, paging — and computed metrics with `compute` and `sort_by` |
| `telkomsel_get_package` | Full record: price, quota, every bonus, description, terms |
| `telkomsel_compare_packages` | 2–10 packages side by side, plus price-per-GB verdict |
| `telkomsel_aggregate_packages` | Summarise everything matching a filter set: price spread, price per GB, allowance mix, masa aktif, shortlists |
| `telkomsel_get_filter_options` | The exact sort/price/quota values the API accepts |
| `telkomsel_list_roaming_countries` | 80–82 destinations, Indonesian and English names |
| `telkomsel_get_offer_break` | Featured offer groups, expandable into packages |
| `telkomsel_list_credit_options` | Pulsa denominations and the active period each grants |
| `telkomsel_get_faq` | Official FAQ for `simpati` or `halo`; `query` returns the entries that answer a question |

**Session**

| Tool | Purpose |
| --- | --- |
| `telkomsel_get_config` | Current default number and config |
| `telkomsel_set_default_msisdn` | Swap the dummy number for the session |
| `telkomsel_check_msisdn` | Validate a number and read its account type |
| `telkomsel_get_default_number_hint` | Plain-language explanation of the current number |

---

## Field selection

`telkomsel_search_packages`, `telkomsel_get_package`, `telkomsel_get_offer_break`, `telkomsel_list_products` and
`telkomsel_get_product` take a `fields` argument, so a caller retrieves what it needs instead of a subset
somebody else chose.

```jsonc
// Only these three fields come back.
{ "category": "Internet", "limit": 3, "response_format": "json", "fields": ["price", "totalQuota", "offerId"] }
```

Omit `fields` and the default is **recall-preserving**: every declared field except the multi-kilobyte
HTML blobs (`terms`, `longdesc`). Each withheld heavy field is announced as a `has*` boolean, so its
existence is never hidden — a caller that needs the terms asks for them by name on the next call.

| Shorthand | Effect |
| --- | --- |
| omitted | Every field except the heavy HTML ones |
| `["all"]` | Absolutely every field, heavy HTML included |
| `["pricing"]`, `["identity"]`, `["routing"]`, … | That group's fields, never heavy ones |
| `["bonus.quota"]` | One sub-field of the `bonus` array |

Field names, group shorthands, dotted sub-fields and the `all` keyword are all case-insensitive, so
`["ALL"]`, `["PRICING"]` and `["bonus.QUOTA"]` resolve the same as their lowercase forms. An unknown name
is rejected with the list of valid ones rather than ignored, and the result echoes a `selection` block
naming what was returned and what else exists.

**Why the default is generous.** Narrowing harder than the default is usually counterproductive.
[SchemaRouter](https://arxiv.org/abs/2608.21375) measured answer accuracy falling from 0.71 to 0.56 when
the selected-field count was minimised, for negligible token savings, while recall-preserving projection
restored it. A fixed hand-picked projection is also worse than it looks: an earlier version of this server
kept 11 of the 24 fields a package carries, so a question needing `fee`, `typeOffer`, `subCategory` or the
bonus classification could not be answered at all.

## Provenance and the trust boundary

Every result carries a `provenance` block. In a single-route system that would be decoration; in a router
that also has an indexed copy of this catalogue it is what stops two routes contradicting each other.

```json
"provenance": {
  "route": "telkomsel-product-mcp",
  "mode": "live",
  "source": "https://www.telkomsel.com/api/express-purchase/v1",
  "fetchedAt": "2026-10-16T09:12:44.118Z",
  "entity": "package",
  "authoritativeFields": ["price", "originalPrice", "fee", "totalQuota", "totalValidity", "…"],
  "license": "Catalogue data © Telkomsel, read from its public product endpoints.…",
  "version": "0.2.0"
}
```

`mode` is `live` for anything read from the API and `snapshot` for the generated product dataset —
a snapshot claims **no** authoritative fields, so a router can tell "nothing here is current" from
"this is current". The longer policy (what this route cannot answer at all) lives once in
`telkomsel_get_capabilities` rather than being repeated into every result.

## Two identifiers, for two different jobs

| Identifier | Shape | Use it for |
| --- | --- | --- |
| `ref` | `slug@quota@price` | Resolving one priced offer again, in any later session |
| `offerId` | `slug@quota` | **Keying a corpus index** |
| `id` | opaque hash | Same-session only; the API mints a new one per request |

The quota part carries the unit the package is sold in, because a ref that contradicts
its own row is worse than no ref: Talkmania RoaMAX is ten **minutes** of voice, and it
was published as `talkmania-roamax@10gb@50000` beside a `totalQuota` of `10 Min` until
0.12.0. It is `talkmania-roamax@10min@50000` now; gigabyte refs (`super-seru@53gb@100000`)
are unchanged, and an allowance that cannot be read says `na` rather than claiming
gigabytes.

`offerId` exists because `ref` is the wrong index key. Key on `ref` and a price change renames the
document instead of updating it — the index grows a duplicate and every citation to the old entry rots.
`offerId` keeps the identity while price stays ordinary mutable content, so a re-index sees an update.

## Resources: the corpus

Tools answer questions. Resources carry the corpus. The server exposes both because they are
different jobs, and the split is the design decision that matters most here:

| | Tools | Resources |
| --- | --- | --- |
| Who decides | The model, per question | The **application** — a host, or an indexer |
| What belongs | Anything personalised per number, anything that moves | The stable, readable, non-personalised corpus |
| Discovery | `tools/list` | `resources/list`, `resources/templates/list` |
| Size cap | Yes, the server enforces one | None |

That last row matters more than it looks. A corpus is larger than a single agent turn should carry,
and a tool result is the wrong place to put it.

| Resource | Volatility | What it is |
| --- | --- | --- |
| `telkomsel://catalog` | static | **Start here.** Every document with a content hash, plus what must never be embedded |
| `telkomsel://products` | static | All 11 products with summaries and section headings |
| `telkomsel://products/{slug}` | static | One product; the 11 are enumerated in `resources/list` so nothing has to be guessed |
| `telkomsel://segments` | static | The catalogue's segment and family structure, derived so it cannot contradict the products |
| `telkomsel://roaming-destinations` | reference | Every roaming destination, Indonesian and English name |

**The rule: if it varies by number, it is not corpus.** `GET mapped-regions` takes no number, so it is a
resource. `GET faq/simpati` takes an MSISDN and answers for that number, so it stays a tool — even though
it is prose, which is exactly the kind of content an indexer embeds without checking.

### Syncing an index

Read `telkomsel://catalog` once per sync:

```jsonc
{
  "documents": [
    { "uri": "telkomsel://products", "volatility": "static",
      "contentHash": "sha256:9f2c…", "sizeBytes": 41208, "lastModified": "2026-10-16T…" }
  ],
  "collections": [
    { "uriTemplate": "telkomsel://products/{slug}", "count": 11,
      "members": [{ "uri": "telkomsel://products/simpati", "contentHash": "sha256:1ab3…" }] }
  ],
  "notIndexable": [ /* what must never be embedded, and which live tool answers instead */ ],
  "sync": { "instructions": [ /* … */ ] }
}
```

Fetch only the documents whose hash changed. `contentHash` covers the `data` field and is computed over
**canonical JSON with sorted keys**, so a re-ordered upstream response is not reported as an edit. The
envelope's own timestamp is deliberately outside the hash — a digest that moved on every read could not
answer the one question it exists to answer.

A document that cannot be produced reports `contentHash: null` with a `hashError` instead of failing the
catalog, so one unreachable upstream does not block a sync of everything else.

## Using this as a retrieval data layer

This MCP is the **live, structured** route in a retrieval system: exact values that change, personalised
per number, with verifiable provenance. It is not an indexer. The split that follows from that:

| Data | Where it belongs |
| --- | --- |
| Product prose, FAQ text, package descriptions, terms | Embed in the dense/BM25 index |
| Relationships (product → segment, category → subcategory → package, package → brand/region) | The knowledge-graph route |
| Price, quota, validity, availability, promotions | **This route, every time** |

The last row is the one that matters: an indexed copy can legitimately hold last week's price, so anything
in `authoritativeFields` must be resolved here and attributed with the provenance block.

Read `telkomsel_get_capabilities` for `routingHints`, which state both directions — when this route is
the right one, and when a conceptual or relationship question should go elsewhere.

### What a text query does, and does not, decide

A `query` and the structured filters both decide *which* packages come back. Order is a separate
question, and it used to have no answer: results arrived in catalogue order, so a search for
`netflix` found all four Netflix packages and placed them at ranks 9-12, behind eight that merely
mention the word. A caller taking the top five got none of the real ones.

Results are now ranked by **Okapi BM25** (k1 1.5, b 0.75) over the same text the query was matched
against, so the packages that carry a partner outrank the ones that mention it. Three consequences
worth knowing:

- **Typos are read, not refused.** When a query matches nothing as written it is retried with a small
  edit distance per term, and `filtersApplied.queryFuzzy` reports that it happened, what the query was
  read as, and each correction. Nonsense still returns nothing rather than a guess, and the fallback
  never escapes the other filters.
- **The price is indexed**, in the shorthand a customer types: `75000`, `105000`, `100rb` and `50rb` all
  reach the offers at that price.
- **A range spoken in words is refused.** `"kuota 30gb sampai 50gb"` returns nothing on purpose: a text
  index cannot express BETWEEN, and guessing a range would be worse than a miss. Convert it to
  `min_quota`/`max_quota` — that route is exact.

### Measured retrieval quality

`npm run eval` runs a scored evaluation against the BM25 reference document, over the live catalogue.
Its scenarios, ground truth and metrics live in `eval/`, and the report it writes is `eval/REPORT.md`.
Every ground-truth set is computed from the catalogue rather than hand-listed, so a scenario cannot
pass by agreeing with an expectation the data no longer supports.

| Question | Measured | Bar |
| --- | --- | --- |
| Does a partner search find every package that bundles it? | 100% coverage, 19 brands | 95% |
| Is the first result the right one? | MRR 1.00, NDCG@10 100% | — |
| Are the returned rows relevant? | precision@10 94.0% | 95% |
| Do numeric ranges return exactly the right set? | 24 of 24 exact | 100% |
| Customer need resolves to the right intent, or to the order it names | 16 of 16 | 85% |
| Failure modes the document names (typos, `100rb`, bare prices, post-filtering) | 8 of 8 | 90% |

**Overall: 100% weighted across ten families.** The one figure below its bar is precision@10 at 94.0%,
and it is a ceiling effect rather than a defect: where a partner has fewer than ten bundling packages
(Netflix has four), the remaining slots are filled by packages that mention it in their description,
which is a legitimate match.

### When the question is an order, not a filter

The upstream API sorts by five things: `lowest_price`, `highest_price`,
`smallest_quota`, `largest_quota`, `longest_active_period`. None of them answers the
question a customer actually asks about price — the cheapest *gigabyte* is not the
cheapest package, and no sort reports the size of a discount.

`telkomsel_search_packages` computes the metric and sorts by it:

```jsonc
{
  "region": "Japan",
  "max_price": 100000,
  "sort_by": { "metric": "price_per_gb", "direction": "asc" }
}
```

Seven metrics are built in (`price_per_gb`, `price_per_internet_gb`, `price_per_day`, `saving`,
`saving_percent`, `quota_per_1000`, `price_with_fee`) and `compute` adds up to eight
of your own, over any published scalar field — `quotaValue / validityDays` for data per
day, `price / quotaValue / validityDays` for rupiah per gigabyte per day.

`price_per_gb` divides by the headline quota, which also counts quotas that only work in
video apps or abroad: SERU Nonton Rp40.000 headlines 38 GB and carries 2 GB of internet.
`price_per_internet_gb` divides by `internetQuotaGb`, the sum of the package's `data allnet`
bonuses, and is what `telkomsel_resolve_intent` suggests when the customer asked for internet.

Four properties are worth knowing before you read a result:

- **A value that cannot be computed is `null`, never 0.** `computed.stats` reports
  `computed` and `notComputable` per metric with a census of the reasons, and those rows
  sort **last in both directions**: a package with no gigabyte price is unranked, not free.
- **The statistics cover every match, not the page.** The sort happens over the whole
  match set and the page is cut afterwards, which is the entire reason to ask the server
  rather than dividing two numbers from ten rows yourself.
- **`originalPrice` is 0 on the packages with no discount** — 500 of 601 on 2026-10-18 —
  so the naive `originalPrice - price` is a large *negative* number there. Guard it, or
  sort by `saving`, which is that expression with the guard.
- **`sort` and `sort_by` are mutually exclusive**; passing both is refused rather than
  silently preferring one.

### A month is a band, the numbers are read for you, and an explicit order survives the query

Three things a router should not have to work out for itself, all of them measured on
the live catalogue (2026-10-18):

- **A month is 28 to 31 days, not a day count.** Super Seru sells a 28-day and a 30-day
  active period as the same month at the same price, so `min_validity_days: 28` with
  `max_validity_days: 28` returned one and hid the other. When both bounds are given
  and both fall inside 28–31, the window is widened to the month and
  `filtersApplied.validityWindow` reports what was asked and what was applied. A single
  bound is an inequality — "at least 30 days" — and is left exactly as asked.
- **The phrase's numbers become arguments.** `telkomsel_resolve_intent` reads a
  validity ("28 hari", "1 bulan"), a price range ("20-50", "20rb sampai 50rb",
  "20.000-50.000"), an allowance range ("30GB sampai 50GB") and an order ("kuota
  terbesar", "termurah", "masa aktif terlama") out of the phrase and returns them in
  `suggestedCall.arguments`, with the words it read them from and the inference it had
  to make in `bounds.notes` — a bare two-digit range under a price word is rupiah in
  thousands, because the catalogue's cheapest package is Rp5 000.
- **An explicit order survives the query.** A `query` decides membership; it used to
  decide order as well, so `query: "super seru"` with `sort: largest_quota` came back
  18, 8, 10, 60 GB. The caller's order now holds and relevance breaks ties, which is the
  rule a metric sort has followed since 0.10.0.

The per-GB definition is one expression, used by this sort and by
`telkomsel_aggregate_packages`, so the two agree by construction: measured on the live
catalogue, `bestValuePerGb[0]` and `sort_by: { metric: "price_per_gb" }` return the same
package, both at **250 rupiah per gigabyte** for 25.000 / 100 GB.

### "Internet" asks for a data package

The catalogue files security apps, renewals and vouchers under a subcategory named *Internet
Lainnya*, so the word `internet` matches them, and sorted by price they come first. Measured
2026-10-18, 28-31 days, `category: "Internet"`: 30 packages, 19 of them in that subcategory,
none with a GB allowance.

`telkomsel_resolve_intent` adds `min_quota: 0, quota_unit: "GB"` when what remains of the
phrase is only a data word, and reports it as `dataAllowance`. A brand beside the word
(`internet netflix`) and a stated quota (`internet 30GB sampai 50GB`) suppress it.
`Voucher Internet Hingga N GB` is excluded because its figure is only in its name; drop
`min_quota` to include it. `fields: ["coverage"]` returns, per row of a region search, the
tier and whether `totalQuota` is about the asked country.

### When the destination is a city

The catalogue sells roaming by country and customers name cities, so a city is
resolved to the country that sells it. `region=kyoto`, `region=osaka` and
`region=machu picchu` all work, and so does a whole sentence —
`telkomsel_resolve_intent` reads `saya pengen ke kyoto` as Japan.

The published destination list holds 80 single-country destinations. It is **not**
the coverage: group packages such as `Internet RoaMAX Eropa` name the countries
they cover in their description — the largest roster holds 135 names and the union
across all of them is 142 — and the same names appear again inside bonuses, where the
allowance that applies is the bonus, not the package. A country absent from the
published list can therefore still return packages, and
`filtersApplied.regionResolution.note` says which case you are in.

Measured on 2026-10-18, **79 of the 80 are reachable**, and one is published and sold
by no package: Bhutan. It answers with the destination as the reason, not as a filter
problem. Myanmar used to be the second: 116 packages reach it, but only through a
"Roaming Negara Transit" bonus of 1 GB, and since 0.11.1 those rows come back
labelled instead of looking like packages for Myanmar. The list says "Vatican City"
and "Macao" while the package text says "Vatican" and "Macau", and until 0.9.2 both
matched nothing — the resolver had found the right country and then searched for a
word the catalogue does not use. `npm run audit:regions` walks all 80, one upstream
call each (about a minute), and fails if a destination stops being reachable.

### A country named in a description is a real answer; a metric over the wrong quota is not
A region search reports which of two reasons put a row in the answer.
`destination` means the package's own name or `region` field is that country.
`roster` means the country is inside its coverage — named in its `longdesc`, or
carried by one of its bonuses — which is a real answer and not a fallback: Malé,
Havana, Kingston, the Seychelles and Myanmar are only reachable this way, and Germany
is sold by no package at all. What the census then separates is whether a metric
computed over `totalQuota` describes the country asked about, and measured on
2026-10-18 it does for 19 of the 47 rows that reach Germany:

| Row | Reached by | A metric over `totalQuota` |
| --- | --- | --- |
| `Talkmania RoaMAX`, 10 Min | the country list in its `longdesc` | is about Germany — those minutes work there |
| `Internet RoaMAX Eropa`, 2 GB | its own `RoaMAX Eropa` bonus of 2 GB | is about Germany — the bonus is the package's own allowance |
| `Internet RoaMAX Turki`, 6 GB | a `Roaming Negara Transit` bonus of 1 GB | is about Turkey |

So the rank has three groups, not two: the packages that are for the country, then the
rows whose own allowance covers it, then the rows reached only by a smaller bonus. The
caller's order still decides the order inside each group. That is the whole difference
between these two answers to "cheapest gigabyte to Kyoto", measured on 2026-10-18:
| | Before 0.11.1 | Since 0.11.1 |
|---|---|---|
| row 1 | `Internet RoaMAX Australia & New Zealand` — Rp2 296/GB | `Teman Travel Japan 10 Hari` — Rp407 000 |
| row 2 | `Internet RoaMAX Australia & Selandia Baru` — Rp2 477/GB | `Teman Travel Japan 7 Hari` — Rp349 000 |
| why | 270 GB and 220 GB of Australian allowance, Japan named in the description and covered by a 1 GB transit bonus | 75 GB and 50 GB that work in Japan |

`filtersApplied.regionRelevance` reports the census — `destination`, `roster`,
`quotaApplies` and `transitOnly` — and names the bonus behind each roster row
(`rosterPackages[].coveringBonus`, `bonusQuota`, `quotaApplies`), transit-only rows
first because those are the ones a caller is most likely to misread. `coveringBonus:
null` means the description carried the match. For Kyoto, `Roaming Negara Transit` at
1 GB is what covers Japan in the row that used to win: the honest answer there is one
gigabyte, not 270.
Five outcomes, and the last three explain themselves rather than returning an
empty result:

| The customer names | Example | What comes back |
| --- | --- | --- |
| A city in a country with its own packages | `kyoto`, `santorini` | That country's packages |
| A city in a country reached by a group package | `maldives`, `cancun` | The group packages |
| A city in Indonesia | `bali`, `jakarta` | Nothing, plus a note that roaming does not apply |
| A place the catalogue does not reach | `fiji`, `punta cana` | Nothing, plus a note saying so |
| A published destination no package names | `bhutan`, `myanmar` | Nothing, plus a note that the destination is the reason and no filter can help |

For a RAG system routing into this server, `skills/telkomsel-router/` carries the
contract: eight rules, each one a defect measured against the live catalogue, and
`router-contract.json` with the same rules as data.

### When the question is compound, misspelled, or in English

`npm run eval:deep` asks the questions the ten families above do not: a destination
and a budget in the same sentence, a customer who misspells, and a customer writing
in English. Its report is `eval/REPORT-DEEP.md`.

| Question | Measured | Bar |
| --- | --- | --- |
| Destination + budget + cheapest per GB, in either language | 38 of 38 | 100% |
| A misspelling still routes to the right intent or order | 97 of 99 (98.0%) | 90% |
| A correctly spelled phrase is not re-routed | 16 of 16 | 100% |
| English phrasing | 14 of 14 | 70% |
| Colloquial Indonesian | 10 of 10 | 70% |
| A destination is reachable in either language | 19 of 19 countries | 100% |
| Adversarial and malformed input behaves as required | 13 of 13 | 100% |

**Overall: 100.0%.** The same evaluation scored **75.6%** before this round, and what
it found is worth stating plainly, because the ten families above were at 100%
throughout:

- **A destination worked in one language only.** All 19 countries whose English and
  Indonesian names differ returned *disjoint* sets — 19 of 19, sharing nothing. For
  the question this evaluation is built around — fly to Singapore, cheapest rupiah
  per GB, under 100k — the English spelling answered Rp100.000 for 2GB (50.000/GB)
  and the Indonesian Rp55.000 for 25GB (2.200/GB): **23x worse**, and the English
  one wrong.
- **A misspelling was not read at all.** Not read *wrongly* — 23 of 99 perturbed
  phrases returned no intent, while result coverage stayed at 100%. The failure was
  in routing, not in search.
- **English phrasing scored 42.9%.** The catalogue is Indonesian, and the resolver
  carried no English triggers.

The fix for the second is the interesting one. Counting edits cannot separate a
misspelling from a different word: two deletions turn "nonton" into "nonn", and two
substitutions turn "cheap" into "chat". The *shape* of the edit does. Every genuine
typo measured was the trigger with letters dropped, and not one false match was. So a
dropped character is read through whatever the edit count says, while a substitution
still has to fit a one-edit budget. That is what took the blast radius to 100%
without costing a single correctly spelled phrase — a guard that exists because the
first, looser attempt turned "package for gaming" into a roaming question through
"going", and "cheap package" into an SMS one through "chat".

### Paging without losing rows

Page with the `page.nextOffset` the result reports, **not** `offset + limit`. A JSON page is capped by
serialised size, so it often returns fewer rows than `limit` asked for; advancing by `limit` skips the
difference silently. An inventory that made this mistake collected 94 packages and lost an
entire category without a single error.

---

## Example

```jsonc
// telkomsel_search_packages — find Netflix bundles for the dummy number
{ "query": "netflix", "limit": 2, "response_format": "json" }
```

Real output, trimmed to the first hit:

```json
{
  "msisdn": "081234455666",
  "matched": 4,
  "filtersApplied": { "query": "netflix" },
  "page": { "offset": 0, "limit": 2, "returned": 2, "hasMore": true, "nextOffset": 2 },
  "packages": [
    {
      "ref": "netflix-mobile@6gb@165000",
      "packageName": "Netflix Mobile",
      "price": 165000,
      "totalQuota": "6 GB",
      "totalValidity": "92 Days",
      "category": "Entertainment",
      "group": "Netflix",
      "isRecommended": false,
      "autoRenewal": "PURCHASE",
      "bonus": [
        { "name": "Netflix Mobile", "quota": "3 Months", "validity": "3 Months" },
        { "name": "Nonton", "quota": "6 GB", "validity": "92 Days" }
      ],
      "hasTerms": true
    }
  ]
}
```

Note the `ref`. **Use it, not `id`.** The API mints a new `id` on every single
request — verified across 108 packages — so an id is worthless outside the
current session. `ref` is derived from stable fields (`name@quota@price`) and
can be stored, quoted to a user, or reused in a later run.

Passing `ref` straight back works:

```jsonc
// telkomsel_get_package
{ "ref": "netflix-mobile@6gb@165000" }
```

---

## Configuration

| Variable | Default | Meaning |
| --- | --- | --- |
| `TSEL_DEFAULT_MSISDN` | `081234455666` | Number the server starts with |
| `TSEL_CACHE_TTL_MS` | `300000` | How long a fetched catalogue is reused |
| `TSEL_TIMEOUT_MS` | `20000` | Upstream request timeout |

---

## Project layout

```
src/
  index.ts                 The `bin`: a thin stdio launcher
  lib.ts                   The library entry (`import ... from 'telkomsel-product-mcp'`)
  server.ts                createTelkomselServer(): the one place the server is assembled
  http.ts                  createMcpHandler(): Web-standard Streamable HTTP handler + auth gate
  constants.ts             API base, prefixes, limits
  config.ts                Per-server Session (default MSISDN); nothing global
  msisdn.ts                Normalisation and validation
  types.ts                 API and catalogue types
  data/products.ts         GENERATED 11-product dataset
  services/
    telkomsel-api.ts       Typed client for the express-purchase API
    catalog.ts             Full-catalogue fetch + 5-minute cache
    package-store.ts       Session index: ephemeral ids, durable refs, corpus offerIds
    bounded.ts             Size-capped cache insert, so a hosted server cannot grow with its callers
    product-page.ts        Live product-page scraper
    schema.ts              The published schema graph: field registry, units, vocabulary
    provenance.ts          The per-result trust and attribution block
    corpus.ts              Corpus classification: volatility, hashing, the sync contract
  resources/
    corpus.ts              The corpus exposed as MCP Resources
  tools/
    config.ts products.ts packages.ts capabilities.ts shared.ts
recon/                     The reverse-engineering work, kept so it can be re-run
test/smoke.mjs             24 tools and the corpus resources, live over real MCP stdio
test/regions-audit.mjs     Every published destination, asked for by name, live
test/host.mjs              The HTTP handler, auth gate, and isolation between requests, offline
test/resources.mjs         Resources and the sync contract, offline
```

## Regenerating the product dataset

```bash
npm run recon:catalog     # re-scrape the 11 pages into src/data/products.ts
npm run build
```

---

## Limitations

- **Undocumented API.** These endpoints are not a public contract and can change
  without notice. `menuLevel` in particular looks like internal machinery.
- **Read-only.** No purchase, activation, balance or quota access — those need
  authenticated MyTelkomsel credentials, which this server never asks for.
- **Personalised results.** Two numbers can legitimately return different
  catalogues; that is the API working as designed, not a bug.
- **Catalogue snapshot.** The 11-product dataset is generated, not live. It
  records when it was scraped, and `telkomsel_get_product { "live": true }`
  re-reads the page on demand.
- Be considerate with request volume: a cold catalogue build costs ~11 upstream
  calls, cached for five minutes.
- **The protocol has no cache hint.** `ttlMs`/`cacheScope` do not exist in SDK 1.32.1, so volatility is
  published as data — in `resources/list` annotations, in each resource's `corpus` block, and in
  `telkomsel://catalog` — rather than as something a client would honour automatically.
- **JSON listings page by size, not by a fixed count.** The cost per package depends
  on the projection requested, so a listing keeps as many records as fit a character
  budget and reports `droppedForSize` when it stops early. Page with `limit`/`offset`.

## License

MIT. Not affiliated with or endorsed by Telkomsel.
