encarapi-mcp 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # EnCarAPI MCP server: Korean and Chinese used car data for AI assistants
2
2
 
3
3
  [Model Context Protocol](https://modelcontextprotocol.io) server for
4
- [EnCarAPI](https://encarapi.com). Lets Claude, Cursor, ChatGPT and other MCP clients search
4
+ [EnCarAPI](https://encarapi.com/?utm_source=readme&utm_medium=encarapi-mcp). Lets Claude, Cursor, ChatGPT and other MCP clients search
5
5
  **live used car listings from South Korea** (Encar, KB Chachacha, K Car) and **China**
6
6
  (Dongchedi, Che168), and pull full details, inspection reports and accident records.
7
7
 
8
- > **An API key is required.** Get one (5-day trial) at [encarapi.com](https://encarapi.com).
9
- > Chinese data works with a [ChinaCarAPI](https://chinacarapi.com) key or an EnCarAPI key
10
- > with the China add-on.
8
+ > **An API key is required.** Get one (5-day trial) at [encarapi.com](https://encarapi.com/?utm_source=readme&utm_medium=encarapi-mcp).
9
+ > Chinese data works with a [ChinaCarAPI](https://chinacarapi.com/?utm_source=readme&utm_medium=encarapi-mcp) key or an EnCarAPI key
10
+ > with the China add-on. ChinaCarAPI customers: see [For ChinaCarAPI customers](#for-chinacarapi-customers).
11
11
 
12
12
  ## Tools
13
13
 
@@ -19,9 +19,10 @@
19
19
  | `get_korean_accident_record` | Insurance accident history and ownership changes |
20
20
  | `find_korean_models` | Model name autocomplete across brands |
21
21
  | `korean_filter_values` | Valid filter values |
22
- | `search_chinese_cars` | Search Chinese listings (brand, model, year, price in CNY, mileage, city, export-ready) |
22
+ | `search_chinese_cars` | Search Chinese listings (brand, model, model year, registration year, price in CNY, mileage, city, fuel, source, export-ready) |
23
23
  | `get_chinese_car` | Full record for one Chinese listing |
24
24
  | `get_chinese_inspection` | Chinese inspection report (accident, flood, fire, EV battery) |
25
+ | `chinese_filter_values` | Valid makes, fuels, cities and sources with listing counts |
25
26
  | `chinese_models` | Models of a brand with listing counts |
26
27
 
27
28
  All tools are read-only.
@@ -49,7 +50,7 @@ claude mcp add --transport http encarapi https://mcp.encarapi.com/mcp
49
50
 
50
51
  The key is checked once and is not stored on the server: it is encrypted into the token
51
52
  your client receives. To disconnect, remove the server in your client; to cut off access
52
- everywhere, rotate your key at [encarapi.com](https://encarapi.com).
53
+ everywhere, rotate your key at [encarapi.com](https://encarapi.com/?utm_source=readme&utm_medium=encarapi-mcp).
53
54
 
54
55
  ### Alternative: send the key yourself
55
56
 
@@ -72,6 +73,46 @@ have no OAuth support can use `https://mcp.encarapi.com/mcp?key=YOUR_ENCARAPI_KE
72
73
  is preferred, since URLs can end up in logs). A separate ChinaCarAPI key goes into the
73
74
  `x-china-key` header, or into the second field of the browser form.
74
75
 
76
+ ## For ChinaCarAPI customers
77
+
78
+ ChinaCarAPI has its own address:
79
+
80
+ ```
81
+ https://mcp.chinacarapi.com/mcp
82
+ ```
83
+
84
+ Add it as a remote MCP server exactly as above. On first use a browser window opens and you
85
+ paste your ChinaCarAPI key once. The form detects which key it is, so an EnCarAPI key works
86
+ there as well; customers with both keys put the EnCarAPI key into the optional second field.
87
+
88
+ - **Claude** (claude.ai, desktop, mobile): Settings - Connectors - Add custom connector, paste the URL
89
+ - **Cursor**: `{"mcpServers": {"chinacarapi": {"url": "https://mcp.chinacarapi.com/mcp"}}}` in `.cursor/mcp.json`
90
+ - **Claude Code**:
91
+
92
+ ```bash
93
+ claude mcp add --transport http chinacarapi https://mcp.chinacarapi.com/mcp
94
+ ```
95
+
96
+ On this address the Chinese tools are listed first. Start with `chinese_filter_values` to
97
+ get valid makes, fuels and cities (the `city` filter needs the exact `value` from that list).
98
+
99
+ Without the browser login, send the key as a header. On mcp.chinacarapi.com a key in
100
+ `Authorization: Bearer` or `x-api-key` counts as a ChinaCarAPI key:
101
+
102
+ ```bash
103
+ claude mcp add --transport http chinacarapi https://mcp.chinacarapi.com/mcp \
104
+ --header "Authorization: Bearer YOUR_CHINACARAPI_KEY"
105
+ ```
106
+
107
+ `x-china-key: YOUR_CHINACARAPI_KEY` works on both addresses; then `Authorization` can carry
108
+ an EnCarAPI key for the Korean tools.
109
+
110
+ Locally (npx), set `CHINACARAPI_KEY` instead of `ENCARAPI_KEY`:
111
+
112
+ ```bash
113
+ claude mcp add chinacarapi -e CHINACARAPI_KEY=YOUR_CHINACARAPI_KEY -- npx -y encarapi-mcp
114
+ ```
115
+
75
116
  ## Option 2: local (npx)
76
117
 
77
118
  Claude Desktop (`claude_desktop_config.json`), Cursor (`.cursor/mcp.json`) and most other
@@ -120,6 +161,7 @@ To enable the OAuth flow ("connect by URL only"), set two environment variables:
120
161
  |---|---|
121
162
  | `MCP_OAUTH_SECRET` | At least 32 random characters, e.g. `openssl rand -base64 48`. Enables OAuth; without it the server only accepts keys sent by the client. |
122
163
  | `MCP_PUBLIC_URL` | Public origin of the server, e.g. `https://mcp.example.com` (default `https://mcp.encarapi.com`). Tokens are bound to `<MCP_PUBLIC_URL>/mcp`. |
164
+ | `MCP_PUBLIC_URLS` | Optional, several public origins separated by commas, e.g. `https://mcp.encarapi.com,https://mcp.chinacarapi.com`. Replaces `MCP_PUBLIC_URL`. The `Host` header picks the origin (unknown hosts get the first one); each origin has its own issuer and branding, and its tokens are not accepted on the others. Origins whose host contains `chinacarapi.` get the ChinaCarAPI branding. |
123
165
 
124
166
  ```bash
125
167
  docker run -p 3000:3000 -e MCP_OAUTH_SECRET="$(openssl rand -base64 48)" \
@@ -139,8 +181,8 @@ self-contained values (AES-256-GCM) that carry the key. Consequences:
139
181
 
140
182
  ## Links
141
183
 
142
- - EnCarAPI: https://encarapi.com
143
- - ChinaCarAPI: https://chinacarapi.com
184
+ - EnCarAPI: [encarapi.com](https://encarapi.com/?utm_source=readme&utm_medium=encarapi-mcp)
185
+ - ChinaCarAPI: [chinacarapi.com](https://chinacarapi.com/?utm_source=readme&utm_medium=encarapi-mcp)
144
186
  - SDKs: [Node.js](https://github.com/ThatMojo/encarapi-node), [Python](https://github.com/ThatMojo/encarapi-python)
145
187
 
146
188
  EnCarAPI is an independent service and not affiliated with Encar, KB Chachacha, K Car,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "encarapi-mcp",
3
- "version": "1.1.0",
4
- "description": "MCP server for EnCarAPI: live Korean (Encar, KB Chachacha, K Car) and Chinese (Dongchedi, Che168) used car listings for Claude, Cursor and other AI assistants.",
3
+ "version": "1.2.1",
4
+ "description": "MCP server for EnCarAPI and ChinaCarAPI: live Korean (Encar, KB Chachacha, K Car) and Chinese (Dongchedi, Che168) used car listings for Claude, Cursor and other AI assistants.",
5
5
  "type": "module",
6
6
  "main": "src/server.js",
7
7
  "bin": {
@@ -26,6 +26,7 @@
26
26
  "kcar",
27
27
  "korean car api",
28
28
  "china car api",
29
+ "chinacarapi",
29
30
  "che168",
30
31
  "dongchedi",
31
32
  "used cars",
@@ -33,7 +34,7 @@
33
34
  "claude",
34
35
  "cursor"
35
36
  ],
36
- "homepage": "https://encarapi.com",
37
+ "homepage": "https://encarapi.com/?utm_source=npm&utm_medium=encarapi-mcp",
37
38
  "repository": {
38
39
  "type": "git",
39
40
  "url": "git+https://github.com/ThatMojo/encarapi-mcp.git"
package/src/app.js CHANGED
@@ -6,9 +6,15 @@
6
6
  // "?key=<key>" for clients that only accept a URL.
7
7
  // Optional "x-china-key" / "?china_key=" for a separate ChinaCarAPI key.
8
8
  // Nothing is stored server-side.
9
+ //
10
+ // One process can serve several public hosts (MCP_PUBLIC_URLS, e.g.
11
+ // mcp.encarapi.com and mcp.chinacarapi.com). The Host header picks the OAuth
12
+ // issuer and the branding; tokens are bound to their host's /mcp resource. On a
13
+ // ChinaCarAPI host a raw key without x-china-key counts as a ChinaCarAPI key.
9
14
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
15
  import { createServer, VERSION } from "./server.js";
11
16
  import { createOAuth, ACCESS_TOKEN_PREFIX } from "./oauth.js";
17
+ import { brandFor } from "./brand.js";
12
18
 
13
19
  const MAX_BODY = 1024 * 1024;
14
20
 
@@ -17,11 +23,11 @@ function bearerFrom(req) {
17
23
  return auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
18
24
  }
19
25
 
20
- function keysFrom(req, url) {
21
- return {
22
- apiKey: bearerFrom(req) || req.headers["x-api-key"] || url.searchParams.get("key") || undefined,
23
- chinaKey: req.headers["x-china-key"] || url.searchParams.get("china_key") || undefined,
24
- };
26
+ function keysFrom(req, url, brand) {
27
+ const key = bearerFrom(req) || req.headers["x-api-key"] || url.searchParams.get("key") || undefined;
28
+ const chinaKey = req.headers["x-china-key"] || url.searchParams.get("china_key") || undefined;
29
+ if (brand.id === "china" && !chinaKey) return { apiKey: undefined, chinaKey: key };
30
+ return { apiKey: key, chinaKey };
25
31
  }
26
32
 
27
33
  function readJson(req) {
@@ -64,13 +70,30 @@ const MCP_PREFLIGHT = {
64
70
  "Access-Control-Max-Age": "86400",
65
71
  };
66
72
 
73
+ /** Public origins from MCP_PUBLIC_URLS (comma-separated) or MCP_PUBLIC_URL; the first is the default. */
74
+ export function publicUrls(env) {
75
+ const list = String(env.MCP_PUBLIC_URLS || "")
76
+ .split(",")
77
+ .map((s) => s.trim())
78
+ .filter(Boolean);
79
+ return list.length ? list : [env.MCP_PUBLIC_URL || "https://mcp.encarapi.com"];
80
+ }
81
+
82
+ // Host header without port, lower case. Traefik and Cloudflare pass the original
83
+ // Host through, so X-Forwarded-Host is not needed (and not trusted).
84
+ const hostOf = (req) =>
85
+ String(req.headers.host || "")
86
+ .trim()
87
+ .toLowerCase()
88
+ .replace(/:\d+$/, "");
89
+
67
90
  /**
68
91
  * Builds the HTTP request listener. `env.MCP_OAUTH_SECRET` enables the OAuth
69
92
  * endpoints; without it the server only accepts keys sent by the client.
70
93
  * `fetchImpl` and `now` are for tests.
71
94
  */
72
95
  export function createHandler({ env = process.env, fetchImpl, now } = {}) {
73
- async function handleMcp(req, res, { apiKey, chinaKey }) {
96
+ async function handleMcp(req, res, { apiKey, chinaKey, brand }) {
74
97
  let body;
75
98
  try {
76
99
  body = await readJson(req);
@@ -78,7 +101,7 @@ export function createHandler({ env = process.env, fetchImpl, now } = {}) {
78
101
  return send(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
79
102
  }
80
103
 
81
- const server = createServer({ apiKey, chinaKey, fetchImpl, transport: "hosted" });
104
+ const server = createServer({ apiKey, chinaKey, fetchImpl, transport: "hosted", brand: brand.id });
82
105
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
83
106
  res.on("close", () => {
84
107
  transport.close();
@@ -93,18 +116,28 @@ export function createHandler({ env = process.env, fetchImpl, now } = {}) {
93
116
  }
94
117
  }
95
118
 
96
- const oauth = env.MCP_OAUTH_SECRET
97
- ? createOAuth({
98
- secret: env.MCP_OAUTH_SECRET,
99
- publicUrl: env.MCP_PUBLIC_URL || "https://mcp.encarapi.com",
100
- handleMcp,
101
- fetchImpl,
102
- now,
103
- })
104
- : null;
119
+ // One entry per public host: { brand, oauth }. Unknown hosts get the first one.
120
+ const sites = new Map();
121
+ for (const publicUrl of publicUrls(env)) {
122
+ const host = new URL(publicUrl).hostname.toLowerCase();
123
+ const brand = brandFor(publicUrl);
124
+ const oauth = env.MCP_OAUTH_SECRET
125
+ ? createOAuth({
126
+ secret: env.MCP_OAUTH_SECRET,
127
+ publicUrl,
128
+ brand,
129
+ handleMcp: (req, res, keys) => handleMcp(req, res, { ...keys, brand }),
130
+ fetchImpl,
131
+ now,
132
+ })
133
+ : null;
134
+ if (!sites.has(host)) sites.set(host, { brand, oauth });
135
+ }
136
+ const fallback = sites.values().next().value;
105
137
 
106
138
  return async (req, res) => {
107
139
  const url = new URL(req.url, "http://localhost");
140
+ const { brand, oauth } = sites.get(hostOf(req)) || fallback;
108
141
 
109
142
  if (url.pathname === "/health") return send(res, 200, { ok: true, version: VERSION });
110
143
  if (url.pathname === "/" && req.method === "GET") {
@@ -132,19 +165,19 @@ export function createHandler({ env = process.env, fetchImpl, now } = {}) {
132
165
  if (oauth && bearerFrom(req).startsWith(ACCESS_TOKEN_PREFIX)) return oauth.app(req, res);
133
166
 
134
167
  // 2. Key sent by the client.
135
- const { apiKey, chinaKey } = keysFrom(req, url);
168
+ const { apiKey, chinaKey } = keysFrom(req, url, brand);
136
169
  if (!apiKey && !chinaKey) {
137
170
  return send(
138
171
  res,
139
172
  401,
140
173
  {
141
174
  jsonrpc: "2.0",
142
- error: { code: -32001, message: "API key required: Authorization: Bearer <key> (get one at https://encarapi.com)" },
175
+ error: { code: -32001, message: `API key required: Authorization: Bearer <key> (get one at ${brand.signupUrl})` },
143
176
  id: null,
144
177
  },
145
178
  oauth ? { "WWW-Authenticate": oauth.wwwAuthenticate, "Cache-Control": "no-store" } : {}
146
179
  );
147
180
  }
148
- return handleMcp(req, res, { apiKey, chinaKey });
181
+ return handleMcp(req, res, { apiKey, chinaKey, brand });
149
182
  };
150
183
  }
package/src/brand.js ADDED
@@ -0,0 +1,41 @@
1
+ // Per-host branding of the hosted endpoint. One app serves mcp.encarapi.com and
2
+ // mcp.chinacarapi.com: the host decides the page texts, the signup link, the
3
+ // server instructions and which product a pasted key is checked against first.
4
+
5
+ export const BRANDS = {
6
+ korea: {
7
+ id: "korea",
8
+ product: "EnCarAPI",
9
+ otherProduct: "ChinaCarAPI",
10
+ signupUrl: "https://encarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=signin#pricing",
11
+ signupText: "https://encarapi.com",
12
+ resourceName: "EnCarAPI MCP server",
13
+ // Form field names: the main field is auto-detected, the second one is for a
14
+ // separate key of the other product.
15
+ mainField: "encarapi_key",
16
+ secondField: "chinacarapi_key",
17
+ probeOrder: ["korea", "china"],
18
+ },
19
+ china: {
20
+ id: "china",
21
+ product: "ChinaCarAPI",
22
+ otherProduct: "EnCarAPI",
23
+ signupUrl: "https://chinacarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=signin#pricing",
24
+ signupText: "chinacarapi.com",
25
+ resourceName: "ChinaCarAPI MCP server",
26
+ mainField: "chinacarapi_key",
27
+ secondField: "encarapi_key",
28
+ probeOrder: ["china", "korea"],
29
+ },
30
+ };
31
+
32
+ /** Brand for a public origin or host name: chinacarapi hosts get the China brand. */
33
+ export function brandFor(hostOrUrl) {
34
+ let host = String(hostOrUrl || "");
35
+ try {
36
+ host = new URL(host).hostname;
37
+ } catch {
38
+ host = host.replace(/:\d+$/, "");
39
+ }
40
+ return /(^|\.)chinacarapi\./i.test(host) ? BRANDS.china : BRANDS.korea;
41
+ }
package/src/oauth.js CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  InvalidTargetError,
33
33
  InvalidTokenError,
34
34
  } from "@modelcontextprotocol/sdk/server/auth/errors.js";
35
+ import { brandFor } from "./brand.js";
35
36
 
36
37
  const { KoreaClient, ChinaClient } = encarapi;
37
38
 
@@ -51,6 +52,7 @@ const REFRESH_REUSE_GRACE = 60;
51
52
  const KEY_CHECK_MAX = 10;
52
53
  const KEY_CHECK_WINDOW = 10 * 60;
53
54
  const KEY_CHECK_TIMEOUT_MS = 10000;
55
+ const CHINA_API = "https://api.chinacarapi.com";
54
56
 
55
57
  const MAX_REDIRECT_URIS = 10;
56
58
  const MAX_REDIRECT_URI_LENGTH = 500;
@@ -136,7 +138,7 @@ function redirectHost(uri) {
136
138
  }
137
139
  }
138
140
 
139
- function renderPage({ nonce, clientName, host, hidden, error }) {
141
+ function renderPage({ brand, nonce, clientName, host, hidden, error }) {
140
142
  const fields = Object.entries(hidden)
141
143
  .filter(([, v]) => v !== undefined && v !== null)
142
144
  .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)
@@ -148,7 +150,7 @@ function renderPage({ nonce, clientName, host, hidden, error }) {
148
150
  <meta name="viewport" content="width=device-width, initial-scale=1">
149
151
  <meta name="robots" content="noindex, nofollow">
150
152
  <meta name="color-scheme" content="dark">
151
- <title>Connect EnCarAPI</title>
153
+ <title>Connect ${brand.product}</title>
152
154
  <style nonce="${nonce}">
153
155
  *, *::before, *::after { box-sizing: border-box; }
154
156
  html { background: #030712; }
@@ -187,61 +189,112 @@ function renderPage({ nonce, clientName, host, hidden, error }) {
187
189
  </head>
188
190
  <body>
189
191
  <main>
190
- <p class="brand">EnCarAPI</p>
191
- <h1>Connect EnCarAPI</h1>
192
- <p class="who"><strong>${esc(clientName)}</strong> wants to use EnCarAPI with your key. After connecting you return to <strong>${esc(host)}</strong>.</p>
192
+ <p class="brand">${brand.product}</p>
193
+ <h1>Connect ${brand.product}</h1>
194
+ <p class="who"><strong>${esc(clientName)}</strong> wants to use ${brand.product} with your key. After connecting you return to <strong>${esc(host)}</strong>.</p>
193
195
  ${error ? `<div class="error" role="alert"><strong>${esc(error.title)}</strong>${esc(error.text)}</div>` : ""}
194
196
  <form method="post" action="/authorize" autocomplete="off">
195
197
  ${fields}
196
- <label for="encarapi_key">EnCarAPI key</label>
197
- <input type="password" id="encarapi_key" name="encarapi_key" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false" autofocus>
198
- <label for="chinacarapi_key">ChinaCarAPI key <span>(optional)</span></label>
199
- <input type="password" id="chinacarapi_key" name="chinacarapi_key" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false">
198
+ <label for="${brand.mainField}">${brand.product} key</label>
199
+ <input type="password" id="${brand.mainField}" name="${brand.mainField}" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false" autofocus>
200
+ <label for="${brand.secondField}">${brand.otherProduct} key <span>(optional)</span></label>
201
+ <input type="password" id="${brand.secondField}" name="${brand.secondField}" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false">
200
202
  <button type="submit">Connect</button>
201
203
  </form>
202
- <p class="hint">No key yet? Get one at <a href="https://encarapi.com" target="_blank" rel="noopener noreferrer">https://encarapi.com</a></p>
203
- <p class="note">The second field is only needed for a separate ChinaCarAPI key. Keys are checked once and are not stored on this server: they are encrypted into the access token issued to this client.</p>
204
+ <p class="hint">No key yet? Get one at <a href="${brand.signupUrl}" target="_blank" rel="noopener noreferrer">${brand.signupText}</a></p>
205
+ <p class="note">The second field is only needed for a separate ${brand.otherProduct} key. Keys are checked once and are not stored on this server: they are encrypted into the access token issued to this client.</p>
204
206
  </main>
205
207
  </body>
206
208
  </html>`;
207
209
  }
208
210
 
211
+ const PRODUCT = { k: "EnCarAPI", c: "ChinaCarAPI" };
212
+ const SLOT = { korea: "k", china: "c" };
213
+
209
214
  /**
210
- * Checks the pasted keys with one cheap request each. Returns
211
- * { ok: true } | { ok: false, reason: "rejected" | "unavailable", product }.
215
+ * Checks one key against one product with a cheap request. Returns
216
+ * { result: "ok", slot } | { result: "rejected" | "unavailable" }. `slot` is where the
217
+ * key goes in the token: "k" (EnCarAPI key) or "c" (ChinaCarAPI key).
212
218
  */
213
- async function checkKeys({ apiKey, chinaKey }, fetchImpl) {
219
+ async function probeKey(slot, key, fetchImpl) {
214
220
  const base = fetchImpl || fetch;
215
221
  const timed = (url, init) => base(url, { ...init, signal: AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS) });
216
- const probe = async (product, fn) => {
222
+ const fail = (e) => ({ result: e?.status === 401 || e?.status === 403 ? "rejected" : "unavailable" });
223
+ if (slot === "k") {
217
224
  try {
218
- await fn();
219
- return null;
225
+ await new KoreaClient(key, { fetch: timed }).modelSearch("k5", { limit: 1 });
226
+ return { result: "ok", slot: "k" };
220
227
  } catch (e) {
221
- const rejected = e?.status === 401 || e?.status === 403;
222
- return { ok: false, reason: rejected ? "rejected" : "unavailable", product };
228
+ return fail(e);
223
229
  }
224
- };
225
- if (apiKey) {
226
- const bad = await probe("EnCarAPI", () => new KoreaClient(apiKey, { fetch: timed }).modelSearch("k5", { limit: 1 }));
227
- if (bad) return bad;
228
230
  }
229
- if (chinaKey) {
230
- const bad = await probe("ChinaCarAPI", () => new ChinaClient(chinaKey, { fetch: timed }).catalog({ limit: 1 }));
231
- if (bad) return bad;
231
+ // China: GET /api/me does not count against any request budget. 200 { product, plan, ... }
232
+ // with product "chinacarapi" or "encarapi-addon"; an add-on key is kept as an
233
+ // EnCarAPI key, so the Korean tools work with it as well.
234
+ try {
235
+ const res = await timed(`${CHINA_API}/api/me`, { headers: { "x-api-key": key, Accept: "application/json" } });
236
+ if (res.status === 200) {
237
+ let me = null;
238
+ try {
239
+ me = JSON.parse(await res.text());
240
+ } catch {}
241
+ const product = String(me?.product || "chinacarapi").toLowerCase();
242
+ return { result: "ok", slot: product === "chinacarapi" ? "c" : "k" };
243
+ }
244
+ if (res.status !== 404) return fail(res);
245
+ } catch (e) {
246
+ return fail(e);
247
+ }
248
+ // Older API without /api/me.
249
+ try {
250
+ await new ChinaClient(key, { fetch: timed }).catalog({ limit: 1 });
251
+ return { result: "ok", slot: "c" };
252
+ } catch (e) {
253
+ return fail(e);
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Checks the pasted keys. The main key is tried against the products in the
259
+ * brand's order (the first that accepts it wins), the optional second key against
260
+ * the other product. Returns { ok: true, k, c } |
261
+ * { ok: false, reason: "rejected" | "unavailable", product }.
262
+ */
263
+ async function checkKeys({ main, second, brand }, fetchImpl) {
264
+ const keys = {};
265
+ let taken = null;
266
+ if (main) {
267
+ let unavailable = null;
268
+ for (const product of brand.probeOrder) {
269
+ const r = await probeKey(SLOT[product], main, fetchImpl);
270
+ if (r.result === "ok") {
271
+ taken = SLOT[product];
272
+ keys[r.slot] = main;
273
+ break;
274
+ }
275
+ if (r.result === "unavailable" && !unavailable) unavailable = PRODUCT[SLOT[product]];
276
+ }
277
+ if (!taken) return { ok: false, reason: unavailable ? "unavailable" : "rejected", product: unavailable || brand.product };
278
+ }
279
+ if (second) {
280
+ const slot = taken ? (taken === "k" ? "c" : "k") : SLOT[brand.probeOrder[1]];
281
+ const r = await probeKey(slot, second, fetchImpl);
282
+ if (r.result !== "ok") return { ok: false, reason: r.result, product: PRODUCT[slot] };
283
+ keys[slot] = second;
232
284
  }
233
- return { ok: true };
285
+ return { ok: true, ...keys };
234
286
  }
235
287
 
236
288
  /**
237
289
  * @param {object} o
238
290
  * @param {string} o.secret MCP_OAUTH_SECRET (at least 32 characters)
239
291
  * @param {string} o.publicUrl public origin, e.g. https://mcp.encarapi.com
292
+ * @param {object} [o.brand] page texts and key order (src/brand.js), default from publicUrl
240
293
  * @param {Function} o.handleMcp (req, res, { apiKey, chinaKey }) for an authenticated /mcp request
241
294
  * @param {Function} [o.fetchImpl] fetch used for the key check (tests)
242
295
  * @param {Function} [o.now] clock in ms (tests)
243
296
  */
244
- export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowMs = Date.now }) {
297
+ export function createOAuth({ secret, publicUrl, brand, handleMcp, fetchImpl, now: nowMs = Date.now }) {
245
298
  if (typeof secret !== "string" || secret.length < 32) {
246
299
  throw new Error("MCP_OAUTH_SECRET must be at least 32 characters (e.g. openssl rand -base64 48)");
247
300
  }
@@ -249,6 +302,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
249
302
  if (issuerUrl.pathname !== "/" || issuerUrl.search || issuerUrl.hash) {
250
303
  throw new Error("MCP_PUBLIC_URL must be an origin without path, e.g. https://mcp.encarapi.com");
251
304
  }
305
+ brand = brand || brandFor(issuerUrl.href);
252
306
  const resourceUrl = new URL("/mcp", issuerUrl);
253
307
  const resource = resourceUrl.href;
254
308
  const secure = issuerUrl.protocol === "https:";
@@ -272,7 +326,8 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
272
326
  const clientsStore = {
273
327
  getClient(clientId) {
274
328
  const c = unwrap("client", CLIENT_PREFIX, clientId);
275
- if (!c || !Array.isArray(c.r)) return undefined;
329
+ // Clients registered before 1.2.0 carry no resource and stay valid.
330
+ if (!c || !Array.isArray(c.r) || (c.a && c.a !== resource)) return undefined;
276
331
  return {
277
332
  client_id: clientId,
278
333
  client_id_issued_at: c.t,
@@ -311,6 +366,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
311
366
  m: method,
312
367
  s: method === "none" ? undefined : meta.client_secret,
313
368
  t: issuedAt,
369
+ a: resource,
314
370
  });
315
371
  return {
316
372
  ...meta,
@@ -337,7 +393,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
337
393
 
338
394
  function openCode(client, code) {
339
395
  const c = unwrap("code", CODE_PREFIX, code);
340
- if (!c || c.exp <= now() || c.cid !== clientRef(client.client_id)) {
396
+ if (!c || c.exp <= now() || c.cid !== clientRef(client.client_id) || c.aud !== resource) {
341
397
  throw new InvalidGrantError("Invalid or expired authorization code");
342
398
  }
343
399
  return c;
@@ -381,6 +437,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
381
437
  );
382
438
  res.end(
383
439
  renderPage({
440
+ brand,
384
441
  nonce: styleNonce,
385
442
  clientName: client.client_name || "An MCP client",
386
443
  host: redirectHost(params.redirectUri),
@@ -431,12 +488,12 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
431
488
  });
432
489
  }
433
490
  const clean = (v) => (typeof v === "string" ? v.trim().slice(0, MAX_KEY_LENGTH) : "");
434
- const apiKey = clean(body.encarapi_key);
435
- const chinaKey = clean(body.chinacarapi_key);
436
- if (!apiKey && !chinaKey) {
491
+ const main = clean(body[brand.mainField]);
492
+ const second = clean(body[brand.secondField]);
493
+ if (!main && !second) {
437
494
  return sendForm(res, client, params, {
438
495
  status: 400,
439
- error: { title: "A key is required.", text: "Paste your EnCarAPI key to connect." },
496
+ error: { title: "A key is required.", text: `Paste your ${brand.product} key to connect.` },
440
497
  });
441
498
  }
442
499
  if (!keyCheckAllowed(clientIp(req))) {
@@ -445,7 +502,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
445
502
  error: { title: "Too many attempts.", text: "Please wait a few minutes and try again." },
446
503
  });
447
504
  }
448
- const check = await checkKeys({ apiKey, chinaKey }, fetchImpl);
505
+ const check = await checkKeys({ main, second, brand }, fetchImpl);
449
506
  if (!check.ok) {
450
507
  return sendForm(res, client, params, {
451
508
  status: check.reason === "rejected" ? 400 : 503,
@@ -459,9 +516,10 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
459
516
  const code =
460
517
  CODE_PREFIX +
461
518
  seal("code", {
462
- k: apiKey || undefined,
463
- c: chinaKey || undefined,
519
+ k: check.k,
520
+ c: check.c,
464
521
  cid: clientRef(client.client_id),
522
+ aud: resource,
465
523
  ru: params.redirectUri,
466
524
  cc: params.codeChallenge,
467
525
  exp: now() + CODE_TTL,
@@ -529,7 +587,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
529
587
  }),
530
588
  authorization_response_iss_parameter_supported: true,
531
589
  };
532
- const resourceName = "EnCarAPI MCP server";
590
+ const resourceName = brand.resourceName;
533
591
  const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);
534
592
  const wwwAuthenticate = `Bearer resource_metadata="${resourceMetadataUrl}"`;
535
593
 
@@ -588,6 +646,7 @@ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowM
588
646
 
589
647
  return {
590
648
  app,
649
+ brand,
591
650
  provider,
592
651
  resource,
593
652
  resourceMetadataUrl,
package/src/server.js CHANGED
@@ -4,7 +4,7 @@ import encarapi from "encarapi";
4
4
 
5
5
  const { KoreaClient, ChinaClient } = encarapi;
6
6
 
7
- export const VERSION = "1.1.0";
7
+ export const VERSION = "1.2.1";
8
8
  const MAX_TEXT = 40000;
9
9
 
10
10
  const asText = (data) => {
@@ -13,10 +13,18 @@ const asText = (data) => {
13
13
  return { content: [{ type: "text", text }] };
14
14
  };
15
15
 
16
- const asError = (e) => ({
17
- isError: true,
18
- content: [{ type: "text", text: e?.body ? `${e.message}` : String(e?.message || e) }],
19
- });
16
+ // Plan gates (403) and rate limits (429) answer with { error, hint }: the agent gets
17
+ // that text as is, since it says what the plan covers and how to get more.
18
+ const asError = (e) => {
19
+ let text = String(e?.message || e);
20
+ if (e?.status === 403 || e?.status === 429) {
21
+ try {
22
+ const body = JSON.parse(e.body);
23
+ if (body?.error && body?.hint) text = `${body.error} ${body.hint}`;
24
+ } catch {}
25
+ }
26
+ return { isError: true, content: [{ type: "text", text }] };
27
+ };
20
28
 
21
29
  const firstPhoto = (photos) => {
22
30
  const p = Array.isArray(photos) ? photos[0] : null;
@@ -64,11 +72,11 @@ const chinaItem = (c) => ({
64
72
 
65
73
  const readOnly = { readOnlyHint: true, openWorldHint: true };
66
74
 
67
- /**
68
- * Builds an MCP server for one caller. `apiKey` is an EnCarAPI key (Korean data;
69
- * also Chinese data if it has the China add-on), `chinaKey` an optional separate
70
- * ChinaCarAPI key.
71
- */
75
+ const chinaSource = z
76
+ .enum(["dongchedi", "che168"])
77
+ .optional()
78
+ .describe("Marketplace of the id, from the search result; needed when an id exists on both");
79
+
72
80
  // Every API call carries "encarapi-mcp/<version> (<transport>)" as User-Agent,
73
81
  // so MCP usage can be told apart from other clients on the API side.
74
82
  function withUserAgent(fetchImpl, transport) {
@@ -77,27 +85,45 @@ function withUserAgent(fetchImpl, transport) {
77
85
  return (url, init = {}) => base(url, { ...init, headers: { ...(init.headers || {}), "User-Agent": ua } });
78
86
  }
79
87
 
80
- export function createServer({ apiKey, chinaKey, fetchImpl, transport = "stdio" } = {}) {
88
+ const SERVER_INFO = {
89
+ korea: {
90
+ info: { name: "encarapi", title: "EnCarAPI - Korean & Chinese used car data", version: VERSION },
91
+ instructions:
92
+ "Live used car listings from South Korea (Encar, KB Chachacha, K Car) and China (Dongchedi, Che168). " +
93
+ "Korean prices are in KRW, Chinese prices in CNY with USD/EUR conversions. " +
94
+ "Use find_korean_models or korean_filter_values to get exact names before filtering. " +
95
+ "Requires an API key from https://encarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=instructions (China: https://chinacarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=instructions).",
96
+ },
97
+ china: {
98
+ info: { name: "chinacarapi", title: "ChinaCarAPI - Chinese & Korean used car data", version: VERSION },
99
+ instructions:
100
+ "Live used car listings from China (Dongchedi, Che168) and South Korea (Encar, KB Chachacha, K Car). " +
101
+ "Chinese prices are in CNY with USD/EUR conversions, Korean prices in KRW. " +
102
+ "Use chinese_filter_values (makes, fuels, cities) and chinese_models to get exact values before filtering " +
103
+ "search_chinese_cars; for Korea use find_korean_models or korean_filter_values. " +
104
+ "Requires an API key from https://chinacarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=instructions (Korea: https://encarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=instructions).",
105
+ },
106
+ };
107
+
108
+ /**
109
+ * Builds an MCP server for one caller. `apiKey` is an EnCarAPI key (Korean data;
110
+ * also Chinese data if it has the China add-on), `chinaKey` an optional separate
111
+ * ChinaCarAPI key. `brand` ("korea" | "china") sets the server instructions and
112
+ * which tools are listed first.
113
+ */
114
+ export function createServer({ apiKey, chinaKey, fetchImpl, transport = "stdio", brand = "korea" } = {}) {
81
115
  fetchImpl = withUserAgent(fetchImpl, transport);
82
- const server = new McpServer(
83
- { name: "encarapi", title: "EnCarAPI - Korean & Chinese used car data", version: VERSION },
84
- {
85
- instructions:
86
- "Live used car listings from South Korea (Encar, KB Chachacha, K Car) and China (Dongchedi, Che168). " +
87
- "Korean prices are in KRW, Chinese prices in CNY with USD/EUR conversions. " +
88
- "Use find_korean_models or korean_filter_values to get exact names before filtering. " +
89
- "Requires an API key from https://encarapi.com (China: https://chinacarapi.com).",
90
- }
91
- );
116
+ const meta = SERVER_INFO[brand] || SERVER_INFO.korea;
117
+ const server = new McpServer(meta.info, { instructions: meta.instructions });
92
118
 
93
119
  const korea = apiKey ? new KoreaClient(apiKey, { fetch: fetchImpl }) : null;
94
120
  const china = chinaKey || apiKey ? new ChinaClient(chinaKey || apiKey, { fetch: fetchImpl }) : null;
95
121
  const needKorea = () => {
96
- if (!korea) throw new Error("No EnCarAPI key configured (ENCARAPI_KEY). Get one at https://encarapi.com");
122
+ if (!korea) throw new Error("No EnCarAPI key configured (ENCARAPI_KEY). Get one at https://encarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=error");
97
123
  return korea;
98
124
  };
99
125
  const needChina = () => {
100
- if (!china) throw new Error("No ChinaCarAPI key configured (CHINACARAPI_KEY). Get one at https://chinacarapi.com");
126
+ if (!china) throw new Error("No ChinaCarAPI key configured (CHINACARAPI_KEY). Get one at https://chinacarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=error");
101
127
  return china;
102
128
  };
103
129
  const run = (fn) => async (args) => {
@@ -110,164 +136,201 @@ export function createServer({ apiKey, chinaKey, fetchImpl, transport = "stdio"
110
136
 
111
137
  // -- Korea -----------------------------------------------------------------
112
138
 
113
- server.registerTool(
114
- "search_korean_cars",
115
- {
116
- title: "Search Korean used cars",
117
- description:
118
- "Search live used car listings in South Korea. Default source is Encar; 'kbc' = KB Chachacha, " +
119
- "'kcar' = K Car, 'all' = all three deduplicated (plan-dependent). Prices are filtered in 10,000 KRW " +
120
- "units (e.g. max_price 3000 = 30,000,000 KRW). Returns the total count and compact listings.",
121
- inputSchema: {
122
- source: z.enum(["encar", "kbc", "kcar", "all"]).optional().describe("Marketplace; default encar"),
123
- manufacturer: z.string().optional().describe("Brand in English, e.g. Hyundai, Kia, Genesis, BMW. Comma = OR"),
124
- model_group: z.string().optional().describe("Model line, e.g. Grandeur, Sorento, 5 Series"),
125
- model: z.string().optional().describe("Specific generation"),
126
- model_search: z.string().optional().describe("Free-text model search across brands, e.g. 'GV80' or 's63 coupe'"),
127
- fuel: z.enum(["gasoline", "diesel", "hybrid", "electric", "lpg", "hydrogen", "other"]).optional(),
128
- transmission: z.enum(["automatic", "manual", "cvt", "semi-automatic", "other"]).optional(),
129
- category: z.enum(["suv", "rv", "large", "midsize", "compact", "small", "kei", "van", "light-van", "truck", "sports", "other"]).optional(),
130
- min_year: z.number().int().optional(),
131
- max_year: z.number().int().optional(),
132
- min_price: z.number().int().optional().describe("Minimum price in 10,000 KRW"),
133
- max_price: z.number().int().optional().describe("Maximum price in 10,000 KRW"),
134
- max_mileage: z.number().int().optional().describe("Maximum mileage in km"),
135
- frame_clean: z.boolean().optional().describe("Only cars with an accident-free chassis frame"),
136
- no_damage_cost: z.boolean().optional().describe("Only cars with zero insurance-reported repair cost"),
137
- has_inspection: z.boolean().optional().describe("Only cars with an official inspection report"),
138
- sort: z.enum(["newest", "price_asc", "price_desc", "mileage_asc", "mileage_desc", "year_desc", "year_asc"]).optional(),
139
- limit: z.number().int().min(1).max(50).optional().describe("Results per page, default 10"),
140
- page: z.number().int().min(1).optional(),
139
+ const registerKorea = () => {
140
+ server.registerTool(
141
+ "search_korean_cars",
142
+ {
143
+ title: "Search Korean used cars",
144
+ description:
145
+ "Search live used car listings in South Korea. Default source is Encar; 'kbc' = KB Chachacha, " +
146
+ "'kcar' = K Car, 'all' = all three deduplicated (plan-dependent). Prices are filtered in 10,000 KRW " +
147
+ "units (e.g. max_price 3000 = 30,000,000 KRW). Returns the total count and compact listings.",
148
+ inputSchema: {
149
+ source: z.enum(["encar", "kbc", "kcar", "all"]).optional().describe("Marketplace; default encar"),
150
+ manufacturer: z.string().optional().describe("Brand in English, e.g. Hyundai, Kia, Genesis, BMW. Comma = OR"),
151
+ model_group: z.string().optional().describe("Model line, e.g. Grandeur, Sorento, 5 Series"),
152
+ model: z.string().optional().describe("Specific generation"),
153
+ model_search: z.string().optional().describe("Free-text model search across brands, e.g. 'GV80' or 's63 coupe'"),
154
+ fuel: z.enum(["gasoline", "diesel", "hybrid", "electric", "lpg", "hydrogen", "other"]).optional(),
155
+ transmission: z.enum(["automatic", "manual", "cvt", "semi-automatic", "other"]).optional(),
156
+ category: z.enum(["suv", "rv", "large", "midsize", "compact", "small", "kei", "van", "light-van", "truck", "sports", "other"]).optional(),
157
+ min_year: z.number().int().optional(),
158
+ max_year: z.number().int().optional(),
159
+ min_price: z.number().int().optional().describe("Minimum price in 10,000 KRW"),
160
+ max_price: z.number().int().optional().describe("Maximum price in 10,000 KRW"),
161
+ max_mileage: z.number().int().optional().describe("Maximum mileage in km"),
162
+ frame_clean: z.boolean().optional().describe("Only cars with an accident-free chassis frame"),
163
+ no_damage_cost: z.boolean().optional().describe("Only cars with zero insurance-reported repair cost"),
164
+ has_inspection: z.boolean().optional().describe("Only cars with an official inspection report"),
165
+ sort: z.enum(["newest", "price_asc", "price_desc", "mileage_asc", "mileage_desc", "year_desc", "year_asc"]).optional(),
166
+ limit: z.number().int().min(1).max(50).optional().describe("Results per page, default 10"),
167
+ page: z.number().int().min(1).optional(),
168
+ },
169
+ annotations: readOnly,
141
170
  },
142
- annotations: readOnly,
143
- },
144
- run(async (args) => {
145
- const res = await needKorea().catalog({ ...args, limit: args.limit || 10, lang: "en", count: true });
146
- return { total: res.Count, page: args.page || 1, results: (res.SearchResults || []).map(koreaItem) };
147
- })
148
- );
171
+ run(async (args) => {
172
+ const res = await needKorea().catalog({ ...args, limit: args.limit || 10, lang: "en", count: true });
173
+ return { total: res.Count, page: args.page || 1, results: (res.SearchResults || []).map(koreaItem) };
174
+ })
175
+ );
149
176
 
150
- server.registerTool(
151
- "get_korean_car",
152
- {
153
- title: "Get a Korean car",
154
- description: "Full details for one Korean listing: specs, options, photos, price history, seller. Id: Encar id, 'kbc:<id>' or 'kcar:<id>'.",
155
- inputSchema: { id: z.string().describe("Listing id from search_korean_cars") },
156
- annotations: readOnly,
157
- },
158
- run(({ id }) => needKorea().vehicle(id, { lang: "en" }))
159
- );
177
+ server.registerTool(
178
+ "get_korean_car",
179
+ {
180
+ title: "Get a Korean car",
181
+ description: "Full details for one Korean listing: specs, options, photos, price history, seller. Id: Encar id, 'kbc:<id>' or 'kcar:<id>'.",
182
+ inputSchema: { id: z.string().describe("Listing id from search_korean_cars") },
183
+ annotations: readOnly,
184
+ },
185
+ run(({ id }) => needKorea().vehicle(id, { lang: "en" }))
186
+ );
160
187
 
161
- server.registerTool(
162
- "get_korean_inspection",
163
- {
164
- title: "Get a Korean inspection report",
165
- description: "Official Korean inspection report (performance check) for one car: panels, frame, mechanical condition.",
166
- inputSchema: { id: z.string() },
167
- annotations: readOnly,
168
- },
169
- run(({ id }) => needKorea().inspection(id))
170
- );
188
+ server.registerTool(
189
+ "get_korean_inspection",
190
+ {
191
+ title: "Get a Korean inspection report",
192
+ description: "Official Korean inspection report (performance check) for one car: panels, frame, mechanical condition.",
193
+ inputSchema: { id: z.string() },
194
+ annotations: readOnly,
195
+ },
196
+ run(({ id }) => needKorea().inspection(id))
197
+ );
171
198
 
172
- server.registerTool(
173
- "get_korean_accident_record",
174
- {
175
- title: "Get a Korean accident & ownership record",
176
- description: "Insurance accident history and ownership changes for one Korean car (own vs. other-party damage in KRW).",
177
- inputSchema: { id: z.string() },
178
- annotations: readOnly,
179
- },
180
- run(({ id }) => needKorea().record(id))
181
- );
199
+ server.registerTool(
200
+ "get_korean_accident_record",
201
+ {
202
+ title: "Get a Korean accident & ownership record",
203
+ description: "Insurance accident history and ownership changes for one Korean car (own vs. other-party damage in KRW).",
204
+ inputSchema: { id: z.string() },
205
+ annotations: readOnly,
206
+ },
207
+ run(({ id }) => needKorea().record(id))
208
+ );
182
209
 
183
- server.registerTool(
184
- "find_korean_models",
185
- {
186
- title: "Find Korean model names",
187
- description: "Autocomplete model names across brands (e.g. 'sorento', 'gv70'). Use the result to filter search_korean_cars.",
188
- inputSchema: { search: z.string(), limit: z.number().int().min(1).max(50).optional() },
189
- annotations: readOnly,
190
- },
191
- run(({ search, limit }) => needKorea().modelSearch(search, { limit: limit || 10 }))
192
- );
210
+ server.registerTool(
211
+ "find_korean_models",
212
+ {
213
+ title: "Find Korean model names",
214
+ description: "Autocomplete model names across brands (e.g. 'sorento', 'gv70'). Use the result to filter search_korean_cars.",
215
+ inputSchema: { search: z.string(), limit: z.number().int().min(1).max(50).optional() },
216
+ annotations: readOnly,
217
+ },
218
+ run(({ search, limit }) => needKorea().modelSearch(search, { limit: limit || 10 }))
219
+ );
220
+
221
+ server.registerTool(
222
+ "korean_filter_values",
223
+ {
224
+ title: "Korean filter values",
225
+ description: "Valid values for the Korean search filters (fuels, colors, categories, ...).",
226
+ inputSchema: { source: z.enum(["encar", "kbc", "kcar", "all"]).optional() },
227
+ annotations: readOnly,
228
+ },
229
+ run((args) => needKorea().enums(args))
230
+ );
193
231
 
194
- server.registerTool(
195
- "korean_filter_values",
196
- {
197
- title: "Korean filter values",
198
- description: "Valid values for the Korean search filters (fuels, colors, categories, ...).",
199
- inputSchema: { source: z.enum(["encar", "kbc", "kcar", "all"]).optional() },
200
- annotations: readOnly,
201
- },
202
- run((args) => needKorea().enums(args))
203
- );
232
+ };
204
233
 
205
234
  // -- China -----------------------------------------------------------------
206
235
 
207
- server.registerTool(
208
- "search_chinese_cars",
209
- {
210
- title: "Search Chinese used cars",
211
- description:
212
- "Search live used car listings in China (Dongchedi and Che168, duplicates merged), in English. " +
213
- "Prices are in CNY; results include USD and EUR conversions.",
214
- inputSchema: {
215
- make: z.string().optional().describe("Brand in English, e.g. BYD, Toyota, Audi"),
216
- model: z.string().optional(),
217
- source: z.enum(["dongchedi", "che168"]).optional(),
218
- year_min: z.number().int().optional(),
219
- year_max: z.number().int().optional(),
220
- price_min: z.number().int().optional().describe("Minimum price in CNY"),
221
- price_max: z.number().int().optional().describe("Maximum price in CNY"),
222
- mileage_max: z.number().int().optional().describe("Maximum mileage in km"),
223
- city: z.string().optional(),
224
- fuel: z.string().optional(),
225
- export_ready: z.boolean().optional().describe("Only cars that can be exported now"),
226
- has_report: z.boolean().optional().describe("Only cars with an inspection report"),
227
- sort: z.enum(["newest", "price_asc", "price_desc", "mileage_asc", "year_desc"]).optional(),
228
- limit: z.number().int().min(1).max(50).optional().describe("Results per page, default 10"),
229
- page: z.number().int().min(1).optional(),
236
+ const registerChina = () => {
237
+ server.registerTool(
238
+ "search_chinese_cars",
239
+ {
240
+ title: "Search Chinese used cars",
241
+ description:
242
+ "Search live used car listings in China (Dongchedi and Che168, duplicates merged), in English. " +
243
+ "Prices are in CNY; results include USD and EUR conversions. " +
244
+ "Use chinese_filter_values and chinese_models for exact make, model, fuel and city values.",
245
+ inputSchema: {
246
+ make: z.string().optional().describe("Brand in English, e.g. BYD, Toyota, Audi"),
247
+ model: z.string().optional().describe("Model name or id from chinese_models"),
248
+ source: z.enum(["dongchedi", "che168"]).optional().describe("Marketplace; default both"),
249
+ duplicates: z
250
+ .enum(["include"])
251
+ .optional()
252
+ .describe("'include' also returns Che168 listings that duplicate a Dongchedi listing (hidden by default)"),
253
+ year_min: z.number().int().optional().describe("Model year from"),
254
+ year_max: z.number().int().optional().describe("Model year to"),
255
+ reg_year_min: z.number().int().optional().describe("First registration year from"),
256
+ reg_year_max: z.number().int().optional().describe("First registration year to"),
257
+ price_min: z.number().int().optional().describe("Minimum price in CNY"),
258
+ price_max: z.number().int().optional().describe("Maximum price in CNY"),
259
+ mileage_max: z.number().int().optional().describe("Maximum mileage in km"),
260
+ city: z.string().optional().describe("City: pass the exact 'value' of an entry in chinese_filter_values (list 'cities')"),
261
+ fuel: z.string().optional().describe("Fuel type in English, see chinese_filter_values (list 'fuels')"),
262
+ export_ready: z.boolean().optional().describe("Only cars that can be exported now"),
263
+ has_report: z.boolean().optional().describe("Only cars with an inspection report"),
264
+ sort: z.enum(["newest", "price_asc", "price_desc", "mileage_asc", "year_desc"]).optional(),
265
+ lang: z.enum(["en", "zh"]).optional().describe("'zh' returns the original Chinese values; default English"),
266
+ limit: z.number().int().min(1).max(50).optional().describe("Results per page, default 10"),
267
+ page: z.number().int().min(1).optional(),
268
+ },
269
+ annotations: readOnly,
230
270
  },
231
- annotations: readOnly,
232
- },
233
- run(async (args) => {
234
- const res = await needChina().catalog({ ...args, limit: args.limit || 10 });
235
- return { total: res.total, page: res.page, results: (res.results || []).map(chinaItem) };
236
- })
237
- );
271
+ run(async (args) => {
272
+ const res = await needChina().catalog({ ...args, limit: args.limit || 10 });
273
+ return { total: res.total, page: res.page, results: (res.results || []).map(chinaItem) };
274
+ })
275
+ );
238
276
 
239
- server.registerTool(
240
- "get_chinese_car",
241
- {
242
- title: "Get a Chinese car",
243
- description: "Full record for one Chinese listing: price history, photos, seller, export status, same car on the other marketplace.",
244
- inputSchema: { id: z.string().describe("Listing id from search_chinese_cars") },
245
- annotations: readOnly,
246
- },
247
- run(({ id }) => needChina().vehicle(id))
248
- );
277
+ server.registerTool(
278
+ "get_chinese_car",
279
+ {
280
+ title: "Get a Chinese car",
281
+ description: "Full record for one Chinese listing: price history, photos, seller, export status, same car on the other marketplace.",
282
+ inputSchema: { id: z.string().describe("Listing id from search_chinese_cars"), source: chinaSource },
283
+ annotations: readOnly,
284
+ },
285
+ run(({ id, source }) => needChina().vehicle(id, { source }))
286
+ );
249
287
 
250
- server.registerTool(
251
- "get_chinese_inspection",
252
- {
253
- title: "Get a Chinese inspection report",
254
- description: "Inspection report for one Chinese car: accident, flood and fire checks, battery data for EVs.",
255
- inputSchema: { id: z.string() },
256
- annotations: readOnly,
257
- },
258
- run(({ id }) => needChina().inspection(id))
259
- );
288
+ server.registerTool(
289
+ "get_chinese_inspection",
290
+ {
291
+ title: "Get a Chinese inspection report",
292
+ description: "Inspection report for one Chinese car: accident, flood and fire checks, battery data for EVs.",
293
+ inputSchema: { id: z.string(), source: chinaSource },
294
+ annotations: readOnly,
295
+ },
296
+ run(({ id, source }) => needChina().inspection(id, { source }))
297
+ );
260
298
 
261
- server.registerTool(
262
- "chinese_models",
263
- {
264
- title: "Chinese models of a brand",
265
- description: "Models of one brand in the Chinese catalog, with listing counts.",
266
- inputSchema: { make: z.string().describe("Brand name in English or brand id") },
267
- annotations: readOnly,
268
- },
269
- run(({ make }) => needChina().models(make))
270
- );
299
+ server.registerTool(
300
+ "chinese_filter_values",
301
+ {
302
+ title: "Chinese filter values",
303
+ description:
304
+ "Valid values for the Chinese search filters, with listing counts: makes, fuels, cities, sources, sorts. " +
305
+ "City filters need the exact 'value' of a city entry. Pass list to get one list only.",
306
+ inputSchema: { list: z.enum(["makes", "fuels", "cities", "sources", "sorts"]).optional() },
307
+ annotations: readOnly,
308
+ },
309
+ run(async ({ list }) => {
310
+ const res = await needChina().enums();
311
+ // Compact JSON: the full set is large and must not hit the text limit.
312
+ return JSON.stringify(list ? { [list]: res?.[list] } : res);
313
+ })
314
+ );
315
+
316
+ server.registerTool(
317
+ "chinese_models",
318
+ {
319
+ title: "Chinese models of a brand",
320
+ description: "Models of one brand in the Chinese catalog, with listing counts.",
321
+ inputSchema: { make: z.string().describe("Brand name in English or brand id") },
322
+ annotations: readOnly,
323
+ },
324
+ run(({ make }) => needChina().models(make))
325
+ );
326
+ };
271
327
 
328
+ if (brand === "china") {
329
+ registerChina();
330
+ registerKorea();
331
+ } else {
332
+ registerKorea();
333
+ registerChina();
334
+ }
272
335
  return server;
273
336
  }
package/src/stdio.js CHANGED
@@ -7,7 +7,7 @@ const chinaKey = process.env.CHINACARAPI_KEY;
7
7
 
8
8
  if (!apiKey && !chinaKey) {
9
9
  console.error(
10
- "encarapi-mcp: set ENCARAPI_KEY (Korea, https://encarapi.com) and/or CHINACARAPI_KEY (China, https://chinacarapi.com)."
10
+ "encarapi-mcp: set ENCARAPI_KEY (Korea, https://encarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=error) and/or CHINACARAPI_KEY (China, https://chinacarapi.com/?utm_source=mcp&utm_medium=encarapi-mcp&utm_content=error)."
11
11
  );
12
12
  process.exit(1);
13
13
  }