encarapi-mcp 1.0.0 → 1.1.0

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
@@ -28,7 +28,32 @@ All tools are read-only.
28
28
 
29
29
  ## Option 1: hosted (no install)
30
30
 
31
- Add this URL as a remote MCP server and send your key as a Bearer token:
31
+ Add this URL as a remote MCP server:
32
+
33
+ ```
34
+ https://mcp.encarapi.com/mcp
35
+ ```
36
+
37
+ In clients with OAuth support the URL is all you need. On first use a browser window opens,
38
+ you paste your EnCarAPI key once, and the client is connected:
39
+
40
+ - **Claude** (claude.ai, desktop, mobile): Settings - Connectors - Add custom connector, paste the URL
41
+ - **ChatGPT** (developer mode): Settings - Connectors - create a connector with the URL
42
+ - **Cursor**: `{"mcpServers": {"encarapi": {"url": "https://mcp.encarapi.com/mcp"}}}` in `.cursor/mcp.json`
43
+ - **VS Code**: "MCP: Add Server" - HTTP - paste the URL
44
+ - **Claude Code**:
45
+
46
+ ```bash
47
+ claude mcp add --transport http encarapi https://mcp.encarapi.com/mcp
48
+ ```
49
+
50
+ The key is checked once and is not stored on the server: it is encrypted into the token
51
+ 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
+
54
+ ### Alternative: send the key yourself
55
+
56
+ Clients without OAuth support, scripts and gateways can send the key directly:
32
57
 
33
58
  ```
34
59
  https://mcp.encarapi.com/mcp
@@ -42,9 +67,10 @@ claude mcp add --transport http encarapi https://mcp.encarapi.com/mcp \
42
67
  --header "Authorization: Bearer YOUR_ENCARAPI_KEY"
43
68
  ```
44
69
 
45
- Clients that only accept a URL can use `https://mcp.encarapi.com/mcp?key=YOUR_ENCARAPI_KEY`
46
- (the Bearer header is preferred, since URLs can end up in logs). A separate ChinaCarAPI key
47
- goes into the `x-china-key` header.
70
+ The `x-api-key: YOUR_ENCARAPI_KEY` header works as well. Clients that only accept a URL and
71
+ have no OAuth support can use `https://mcp.encarapi.com/mcp?key=YOUR_ENCARAPI_KEY` (a header
72
+ is preferred, since URLs can end up in logs). A separate ChinaCarAPI key goes into the
73
+ `x-china-key` header, or into the second field of the browser form.
48
74
 
49
75
  ## Option 2: local (npx)
50
76
 
@@ -88,6 +114,29 @@ docker run -p 3000:3000 encarapi-mcp # POST /mcp, GET /health
88
114
 
89
115
  Stateless: every request carries its own key, nothing is stored.
90
116
 
117
+ To enable the OAuth flow ("connect by URL only"), set two environment variables:
118
+
119
+ | Variable | Meaning |
120
+ |---|---|
121
+ | `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
+ | `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`. |
123
+
124
+ ```bash
125
+ docker run -p 3000:3000 -e MCP_OAUTH_SECRET="$(openssl rand -base64 48)" \
126
+ -e MCP_PUBLIC_URL=https://mcp.example.com encarapi-mcp
127
+ ```
128
+
129
+ This adds `/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server`,
130
+ `/register`, `/authorize` and `/token` (OAuth 2.1 with PKCE, dynamic client registration).
131
+ There is still no database: client ids, authorization codes and tokens are encrypted,
132
+ self-contained values (AES-256-GCM) that carry the key. Consequences:
133
+
134
+ - Changing `MCP_OAUTH_SECRET` signs out all OAuth clients (they reconnect through the browser).
135
+ - Access tokens last 1 hour, refresh tokens 90 days and are replaced on every use.
136
+ - Single use of authorization codes and of replaced refresh tokens is tracked in memory, so
137
+ it is best-effort: it does not survive a restart and is not shared between instances.
138
+ - A single token cannot be revoked on the server. Rotating the EnCarAPI key cuts off all access.
139
+
91
140
  ## Links
92
141
 
93
142
  - EnCarAPI: https://encarapi.com
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "encarapi-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
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.",
5
5
  "type": "module",
6
6
  "main": "src/server.js",
@@ -13,7 +13,7 @@
13
13
  "scripts": {
14
14
  "start": "node src/stdio.js",
15
15
  "start:http": "node src/http.js",
16
- "test": "node test/offline.test.js"
16
+ "test": "node test/offline.test.js && node test/oauth.test.js"
17
17
  },
18
18
  "mcpName": "io.github.ThatMojo/encarapi-mcp",
19
19
  "keywords": [
@@ -49,6 +49,7 @@
49
49
  "dependencies": {
50
50
  "@modelcontextprotocol/sdk": "^1.32.0",
51
51
  "encarapi": "^1.0.0",
52
- "zod": "^4.1.0"
52
+ "zod": "^4.1.0",
53
+ "express": "^5.2.1"
53
54
  }
54
55
  }
package/src/app.js ADDED
@@ -0,0 +1,150 @@
1
+ // Request handler of the hosted MCP endpoint (Streamable HTTP, stateless).
2
+ //
3
+ // /mcp accepts, in this order:
4
+ // 1. an OAuth access token issued by this server (only if MCP_OAUTH_SECRET is set),
5
+ // 2. a raw EnCarAPI key: "Authorization: Bearer <key>", "x-api-key: <key>" or
6
+ // "?key=<key>" for clients that only accept a URL.
7
+ // Optional "x-china-key" / "?china_key=" for a separate ChinaCarAPI key.
8
+ // Nothing is stored server-side.
9
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
+ import { createServer, VERSION } from "./server.js";
11
+ import { createOAuth, ACCESS_TOKEN_PREFIX } from "./oauth.js";
12
+
13
+ const MAX_BODY = 1024 * 1024;
14
+
15
+ function bearerFrom(req) {
16
+ const auth = req.headers.authorization || "";
17
+ return auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
18
+ }
19
+
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
+ };
25
+ }
26
+
27
+ function readJson(req) {
28
+ return new Promise((resolve, reject) => {
29
+ let size = 0;
30
+ const chunks = [];
31
+ req.on("data", (c) => {
32
+ size += c.length;
33
+ if (size > MAX_BODY) {
34
+ reject(new Error("body too large"));
35
+ req.destroy();
36
+ } else chunks.push(c);
37
+ });
38
+ req.on("end", () => {
39
+ try {
40
+ resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined);
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ });
45
+ req.on("error", reject);
46
+ });
47
+ }
48
+
49
+ const send = (res, status, body, headers = {}) => {
50
+ res.writeHead(status, { "Content-Type": "application/json", ...headers });
51
+ res.end(JSON.stringify(body));
52
+ };
53
+
54
+ // Browser-based MCP clients need to read the 401 challenge and send custom headers.
55
+ const MCP_CORS = {
56
+ "Access-Control-Allow-Origin": "*",
57
+ "Access-Control-Expose-Headers": "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version",
58
+ };
59
+ const MCP_PREFLIGHT = {
60
+ "Access-Control-Allow-Origin": "*",
61
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
62
+ "Access-Control-Allow-Headers":
63
+ "Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Last-Event-ID, x-api-key, x-china-key",
64
+ "Access-Control-Max-Age": "86400",
65
+ };
66
+
67
+ /**
68
+ * Builds the HTTP request listener. `env.MCP_OAUTH_SECRET` enables the OAuth
69
+ * endpoints; without it the server only accepts keys sent by the client.
70
+ * `fetchImpl` and `now` are for tests.
71
+ */
72
+ export function createHandler({ env = process.env, fetchImpl, now } = {}) {
73
+ async function handleMcp(req, res, { apiKey, chinaKey }) {
74
+ let body;
75
+ try {
76
+ body = await readJson(req);
77
+ } catch {
78
+ return send(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
79
+ }
80
+
81
+ const server = createServer({ apiKey, chinaKey, fetchImpl, transport: "hosted" });
82
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
83
+ res.on("close", () => {
84
+ transport.close();
85
+ server.close();
86
+ });
87
+ try {
88
+ await server.connect(transport);
89
+ await transport.handleRequest(req, res, body);
90
+ } catch (e) {
91
+ console.error("mcp request failed:", e?.message);
92
+ if (!res.headersSent) send(res, 500, { jsonrpc: "2.0", error: { code: -32603, message: "Internal error" }, id: null });
93
+ }
94
+ }
95
+
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;
105
+
106
+ return async (req, res) => {
107
+ const url = new URL(req.url, "http://localhost");
108
+
109
+ if (url.pathname === "/health") return send(res, 200, { ok: true, version: VERSION });
110
+ if (url.pathname === "/" && req.method === "GET") {
111
+ res.writeHead(302, { Location: "https://github.com/ThatMojo/encarapi-mcp" });
112
+ return res.end();
113
+ }
114
+ if (oauth?.owns(url.pathname)) return oauth.app(req, res);
115
+ if (url.pathname !== "/mcp") return send(res, 404, { error: "Not found. MCP endpoint: /mcp" });
116
+
117
+ if (oauth) {
118
+ if (req.method === "OPTIONS") {
119
+ res.writeHead(204, MCP_PREFLIGHT);
120
+ return res.end();
121
+ }
122
+ for (const [k, v] of Object.entries(MCP_CORS)) res.setHeader(k, v);
123
+ }
124
+
125
+ // Stateless mode: no sessions, so GET (SSE stream) and DELETE are not offered.
126
+ if (req.method !== "POST") {
127
+ res.writeHead(405, { Allow: "POST" });
128
+ return res.end();
129
+ }
130
+
131
+ // 1. OAuth access token issued by this server (verified, audience-bound, 401 when invalid or expired).
132
+ if (oauth && bearerFrom(req).startsWith(ACCESS_TOKEN_PREFIX)) return oauth.app(req, res);
133
+
134
+ // 2. Key sent by the client.
135
+ const { apiKey, chinaKey } = keysFrom(req, url);
136
+ if (!apiKey && !chinaKey) {
137
+ return send(
138
+ res,
139
+ 401,
140
+ {
141
+ jsonrpc: "2.0",
142
+ error: { code: -32001, message: "API key required: Authorization: Bearer <key> (get one at https://encarapi.com)" },
143
+ id: null,
144
+ },
145
+ oauth ? { "WWW-Authenticate": oauth.wwwAuthenticate, "Cache-Control": "no-store" } : {}
146
+ );
147
+ }
148
+ return handleMcp(req, res, { apiKey, chinaKey });
149
+ };
150
+ }
package/src/http.js CHANGED
@@ -1,96 +1,12 @@
1
1
  #!/usr/bin/env node
2
- // Hosted MCP endpoint (Streamable HTTP, stateless). Each request brings its own
3
- // key: "Authorization: Bearer <key>", "x-api-key: <key>" or "?key=<key>" for
4
- // clients that only accept a URL. Optional "x-china-key" for a separate
5
- // ChinaCarAPI key. Nothing is stored server-side.
2
+ // Hosted MCP endpoint (Streamable HTTP, stateless). See src/app.js for the
3
+ // accepted credentials and src/oauth.js for the optional OAuth flow.
6
4
  import http from "node:http";
7
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
- import { createServer, VERSION } from "./server.js";
5
+ import { createHandler } from "./app.js";
9
6
 
10
7
  const PORT = Number(process.env.PORT || 3000);
11
- const MAX_BODY = 1024 * 1024;
12
8
 
13
- function keysFrom(req, url) {
14
- const auth = req.headers.authorization || "";
15
- const bearer = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
16
- return {
17
- apiKey: bearer || req.headers["x-api-key"] || url.searchParams.get("key") || undefined,
18
- chinaKey: req.headers["x-china-key"] || url.searchParams.get("china_key") || undefined,
19
- };
20
- }
21
-
22
- function readJson(req) {
23
- return new Promise((resolve, reject) => {
24
- let size = 0;
25
- const chunks = [];
26
- req.on("data", (c) => {
27
- size += c.length;
28
- if (size > MAX_BODY) {
29
- reject(new Error("body too large"));
30
- req.destroy();
31
- } else chunks.push(c);
32
- });
33
- req.on("end", () => {
34
- try {
35
- resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined);
36
- } catch (e) {
37
- reject(e);
38
- }
39
- });
40
- req.on("error", reject);
41
- });
42
- }
43
-
44
- const send = (res, status, body) => {
45
- res.writeHead(status, { "Content-Type": "application/json" });
46
- res.end(JSON.stringify(body));
47
- };
48
-
49
- const httpServer = http.createServer(async (req, res) => {
50
- const url = new URL(req.url, "http://localhost");
51
-
52
- if (url.pathname === "/health") return send(res, 200, { ok: true, version: VERSION });
53
- if (url.pathname === "/" && req.method === "GET") {
54
- res.writeHead(302, { Location: "https://github.com/ThatMojo/encarapi-mcp" });
55
- return res.end();
56
- }
57
- if (url.pathname !== "/mcp") return send(res, 404, { error: "Not found. MCP endpoint: /mcp" });
58
-
59
- // Stateless mode: no sessions, so GET (SSE stream) and DELETE are not offered.
60
- if (req.method !== "POST") {
61
- res.writeHead(405, { Allow: "POST" });
62
- return res.end();
63
- }
64
-
65
- const { apiKey, chinaKey } = keysFrom(req, url);
66
- if (!apiKey && !chinaKey) {
67
- return send(res, 401, {
68
- jsonrpc: "2.0",
69
- error: { code: -32001, message: "API key required: Authorization: Bearer <key> (get one at https://encarapi.com)" },
70
- id: null,
71
- });
72
- }
73
-
74
- let body;
75
- try {
76
- body = await readJson(req);
77
- } catch {
78
- return send(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
79
- }
80
-
81
- const server = createServer({ apiKey, chinaKey });
82
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
83
- res.on("close", () => {
84
- transport.close();
85
- server.close();
86
- });
87
- try {
88
- await server.connect(transport);
89
- await transport.handleRequest(req, res, body);
90
- } catch (e) {
91
- console.error("mcp request failed:", e?.message);
92
- if (!res.headersSent) send(res, 500, { jsonrpc: "2.0", error: { code: -32603, message: "Internal error" }, id: null });
93
- }
9
+ http.createServer(createHandler()).listen(PORT, () => {
10
+ const oauth = process.env.MCP_OAUTH_SECRET ? "on" : "off (MCP_OAUTH_SECRET not set)";
11
+ console.log(`encarapi-mcp HTTP on :${PORT} (POST /mcp, OAuth ${oauth})`);
94
12
  });
95
-
96
- httpServer.listen(PORT, () => console.log(`encarapi-mcp HTTP on :${PORT} (POST /mcp)`));
package/src/oauth.js ADDED
@@ -0,0 +1,598 @@
1
+ // OAuth 2.1 authorization server + protected resource metadata for the hosted
2
+ // endpoint, per the MCP authorization spec. Enabled only when MCP_OAUTH_SECRET
3
+ // is set.
4
+ //
5
+ // Stateless by design (single container, no database): client ids,
6
+ // authorization codes, access tokens and refresh tokens are AES-256-GCM sealed
7
+ // blobs. The API key the user pasted on /authorize travels inside the code and
8
+ // the tokens and is only readable by this server. The only in-memory state is
9
+ // best-effort and lost on restart: the used-code set, the used-refresh-token
10
+ // set and the rate-limit counters.
11
+ //
12
+ // Protocol plumbing (parameter validation, redirect_uri matching, PKCE check,
13
+ // client authentication, metadata documents, CORS, bearer check) comes from
14
+ // the MCP SDK's server/auth handlers; this file supplies the stateless provider
15
+ // and the key form.
16
+ import crypto from "node:crypto";
17
+ import express from "express";
18
+ import encarapi from "encarapi";
19
+ import { authorizationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js";
20
+ import { tokenHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/token.js";
21
+ import { clientRegistrationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/register.js";
22
+ import { metadataHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/metadata.js";
23
+ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
24
+ import {
25
+ createOAuthMetadata,
26
+ mcpAuthMetadataRouter,
27
+ getOAuthProtectedResourceMetadataUrl,
28
+ } from "@modelcontextprotocol/sdk/server/auth/router.js";
29
+ import {
30
+ InvalidClientMetadataError,
31
+ InvalidGrantError,
32
+ InvalidTargetError,
33
+ InvalidTokenError,
34
+ } from "@modelcontextprotocol/sdk/server/auth/errors.js";
35
+
36
+ const { KoreaClient, ChinaClient } = encarapi;
37
+
38
+ export const ACCESS_TOKEN_PREFIX = "emat_";
39
+ const REFRESH_TOKEN_PREFIX = "emrt_";
40
+ const CODE_PREFIX = "emac_";
41
+ const CLIENT_PREFIX = "emc_";
42
+
43
+ const CODE_TTL = 5 * 60;
44
+ const ACCESS_TTL = 60 * 60;
45
+ const REFRESH_TTL = 90 * 24 * 60 * 60;
46
+ const CSRF_TTL = 30 * 60;
47
+ // A rotated refresh token stays usable for this long, so a client that lost the
48
+ // response (or refreshes from two workers at once) is not logged out.
49
+ const REFRESH_REUSE_GRACE = 60;
50
+
51
+ const KEY_CHECK_MAX = 10;
52
+ const KEY_CHECK_WINDOW = 10 * 60;
53
+ const KEY_CHECK_TIMEOUT_MS = 10000;
54
+
55
+ const MAX_REDIRECT_URIS = 10;
56
+ const MAX_REDIRECT_URI_LENGTH = 500;
57
+ const MAX_KEY_LENGTH = 256;
58
+ const MAX_TRACKED = 50000;
59
+
60
+ const CSRF_COOKIE = "encarapi_mcp_csrf";
61
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
62
+
63
+ const b64 = (buf) => Buffer.from(buf).toString("base64url");
64
+ const sha = (text) => crypto.createHash("sha256").update(text).digest();
65
+ const stripSlash = (s) => String(s).replace(/#.*$/, "").replace(/\/$/, "");
66
+
67
+ /** AES-256-GCM with one HKDF-derived key per purpose, so blobs cannot be swapped between roles. */
68
+ function makeSealer(secret) {
69
+ const keys = new Map();
70
+ const keyFor = (purpose) => {
71
+ if (!keys.has(purpose)) {
72
+ keys.set(purpose, Buffer.from(crypto.hkdfSync("sha256", secret, "encarapi-mcp-oauth", purpose, 32)));
73
+ }
74
+ return keys.get(purpose);
75
+ };
76
+ return {
77
+ seal(purpose, data) {
78
+ const iv = crypto.randomBytes(12);
79
+ const cipher = crypto.createCipheriv("aes-256-gcm", keyFor(purpose), iv);
80
+ const ct = Buffer.concat([cipher.update(JSON.stringify(data), "utf8"), cipher.final()]);
81
+ return b64(Buffer.concat([iv, ct, cipher.getAuthTag()]));
82
+ },
83
+ open(purpose, blob) {
84
+ try {
85
+ const raw = Buffer.from(String(blob), "base64url");
86
+ if (raw.length < 29) return null;
87
+ const decipher = crypto.createDecipheriv("aes-256-gcm", keyFor(purpose), raw.subarray(0, 12));
88
+ decipher.setAuthTag(raw.subarray(raw.length - 16));
89
+ const pt = Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]);
90
+ return JSON.parse(pt.toString("utf8"));
91
+ } catch {
92
+ return null;
93
+ }
94
+ },
95
+ };
96
+ }
97
+
98
+ /** Map of id -> expiry (seconds) that forgets expired entries and stays bounded. */
99
+ function makeTtlMap(now) {
100
+ const map = new Map();
101
+ const prune = () => {
102
+ const t = now();
103
+ for (const [k, v] of map) if (v.exp <= t) map.delete(k);
104
+ while (map.size > MAX_TRACKED) map.delete(map.keys().next().value);
105
+ };
106
+ return {
107
+ get: (k) => {
108
+ const v = map.get(k);
109
+ return v && v.exp > now() ? v : undefined;
110
+ },
111
+ set: (k, v) => {
112
+ if (map.size >= 1000) prune();
113
+ map.set(k, v);
114
+ },
115
+ };
116
+ }
117
+
118
+ /** Caller IP: Cloudflare's header first, then the proxy chain, then the socket. */
119
+ export function clientIp(req) {
120
+ const cf = req.headers["cf-connecting-ip"];
121
+ if (cf) return String(cf).trim();
122
+ const xff = req.headers["x-forwarded-for"];
123
+ if (xff) return String(xff).split(",")[0].trim();
124
+ return req.socket?.remoteAddress || "unknown";
125
+ }
126
+
127
+ const esc = (s) =>
128
+ String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
129
+
130
+ function redirectHost(uri) {
131
+ try {
132
+ const u = new URL(uri);
133
+ return u.host || u.protocol.replace(/:$/, "");
134
+ } catch {
135
+ return "the client";
136
+ }
137
+ }
138
+
139
+ function renderPage({ nonce, clientName, host, hidden, error }) {
140
+ const fields = Object.entries(hidden)
141
+ .filter(([, v]) => v !== undefined && v !== null)
142
+ .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)
143
+ .join("\n ");
144
+ return `<!doctype html>
145
+ <html lang="en">
146
+ <head>
147
+ <meta charset="utf-8">
148
+ <meta name="viewport" content="width=device-width, initial-scale=1">
149
+ <meta name="robots" content="noindex, nofollow">
150
+ <meta name="color-scheme" content="dark">
151
+ <title>Connect EnCarAPI</title>
152
+ <style nonce="${nonce}">
153
+ *, *::before, *::after { box-sizing: border-box; }
154
+ html { background: #030712; }
155
+ body {
156
+ margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
157
+ padding: 24px 16px; background: #030712; color: #f8fafc;
158
+ font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
159
+ -webkit-font-smoothing: antialiased;
160
+ }
161
+ main { width: 100%; max-width: 420px; background: #0a0f1a; border: 1px solid #1d283a; border-radius: 14px; padding: 32px 28px; }
162
+ .brand { font-size: 13px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: #94a3b8; margin: 0 0 20px; }
163
+ h1 { font-size: 22px; line-height: 1.25; font-weight: 600; letter-spacing: -.01em; margin: 0 0 10px; }
164
+ p { margin: 0; }
165
+ .who { color: #94a3b8; margin-bottom: 24px; overflow-wrap: anywhere; }
166
+ .who strong { color: #f8fafc; font-weight: 600; }
167
+ label { display: block; font-size: 13px; font-weight: 500; margin: 0 0 6px; }
168
+ label span { color: #94a3b8; font-weight: 400; }
169
+ input[type=password] {
170
+ display: block; width: 100%; height: 44px; padding: 0 12px; margin: 0 0 18px;
171
+ background: #030712; color: #f8fafc; border: 1px solid #1d283a; border-radius: 10px;
172
+ font: inherit; font-size: 16px; outline: none;
173
+ }
174
+ input[type=password]:focus-visible { border-color: #f8fafc; box-shadow: 0 0 0 3px rgba(248, 250, 252, .14); }
175
+ button {
176
+ display: block; width: 100%; height: 44px; margin: 6px 0 0; border: 0; border-radius: 10px;
177
+ background: #ffffff; color: #030712; font: inherit; font-weight: 600; cursor: pointer;
178
+ }
179
+ button:hover { background: #e2e8f0; }
180
+ button:focus-visible { outline: 2px solid #f8fafc; outline-offset: 3px; }
181
+ .error { border: 1px solid #f87171; border-radius: 10px; padding: 10px 12px; margin: 0 0 20px; color: #fca5a5; font-size: 14px; }
182
+ .error strong { display: block; color: #f87171; font-weight: 600; }
183
+ .hint { color: #94a3b8; font-size: 14px; margin-top: 20px; }
184
+ .note { color: #64748b; font-size: 12.5px; margin-top: 14px; }
185
+ a { color: #f8fafc; text-underline-offset: 3px; }
186
+ </style>
187
+ </head>
188
+ <body>
189
+ <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>
193
+ ${error ? `<div class="error" role="alert"><strong>${esc(error.title)}</strong>${esc(error.text)}</div>` : ""}
194
+ <form method="post" action="/authorize" autocomplete="off">
195
+ ${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">
200
+ <button type="submit">Connect</button>
201
+ </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
+ </main>
205
+ </body>
206
+ </html>`;
207
+ }
208
+
209
+ /**
210
+ * Checks the pasted keys with one cheap request each. Returns
211
+ * { ok: true } | { ok: false, reason: "rejected" | "unavailable", product }.
212
+ */
213
+ async function checkKeys({ apiKey, chinaKey }, fetchImpl) {
214
+ const base = fetchImpl || fetch;
215
+ const timed = (url, init) => base(url, { ...init, signal: AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS) });
216
+ const probe = async (product, fn) => {
217
+ try {
218
+ await fn();
219
+ return null;
220
+ } catch (e) {
221
+ const rejected = e?.status === 401 || e?.status === 403;
222
+ return { ok: false, reason: rejected ? "rejected" : "unavailable", product };
223
+ }
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
+ }
229
+ if (chinaKey) {
230
+ const bad = await probe("ChinaCarAPI", () => new ChinaClient(chinaKey, { fetch: timed }).catalog({ limit: 1 }));
231
+ if (bad) return bad;
232
+ }
233
+ return { ok: true };
234
+ }
235
+
236
+ /**
237
+ * @param {object} o
238
+ * @param {string} o.secret MCP_OAUTH_SECRET (at least 32 characters)
239
+ * @param {string} o.publicUrl public origin, e.g. https://mcp.encarapi.com
240
+ * @param {Function} o.handleMcp (req, res, { apiKey, chinaKey }) for an authenticated /mcp request
241
+ * @param {Function} [o.fetchImpl] fetch used for the key check (tests)
242
+ * @param {Function} [o.now] clock in ms (tests)
243
+ */
244
+ export function createOAuth({ secret, publicUrl, handleMcp, fetchImpl, now: nowMs = Date.now }) {
245
+ if (typeof secret !== "string" || secret.length < 32) {
246
+ throw new Error("MCP_OAUTH_SECRET must be at least 32 characters (e.g. openssl rand -base64 48)");
247
+ }
248
+ const issuerUrl = new URL(publicUrl);
249
+ if (issuerUrl.pathname !== "/" || issuerUrl.search || issuerUrl.hash) {
250
+ throw new Error("MCP_PUBLIC_URL must be an origin without path, e.g. https://mcp.encarapi.com");
251
+ }
252
+ const resourceUrl = new URL("/mcp", issuerUrl);
253
+ const resource = resourceUrl.href;
254
+ const secure = issuerUrl.protocol === "https:";
255
+ const now = () => Math.floor(nowMs() / 1000);
256
+ const { seal, open } = makeSealer(secret);
257
+
258
+ const usedCodes = makeTtlMap(now);
259
+ const usedRefresh = makeTtlMap(now);
260
+ const keyChecks = new Map(); // ip -> [timestamps]
261
+
262
+ const clientRef = (clientId) => b64(sha(clientId).subarray(0, 16));
263
+ const unwrap = (purpose, prefix, value) =>
264
+ typeof value === "string" && value.startsWith(prefix) ? open(purpose, value.slice(prefix.length)) : null;
265
+
266
+ const assertResource = (requested) => {
267
+ if (requested && stripSlash(requested.href ?? requested) !== stripSlash(resource)) {
268
+ throw new InvalidTargetError(`Unknown resource. This server issues tokens for ${resource} only`);
269
+ }
270
+ };
271
+
272
+ const clientsStore = {
273
+ getClient(clientId) {
274
+ const c = unwrap("client", CLIENT_PREFIX, clientId);
275
+ if (!c || !Array.isArray(c.r)) return undefined;
276
+ return {
277
+ client_id: clientId,
278
+ client_id_issued_at: c.t,
279
+ redirect_uris: c.r,
280
+ client_name: c.n,
281
+ client_uri: c.u,
282
+ token_endpoint_auth_method: c.m,
283
+ client_secret: c.s,
284
+ client_secret_expires_at: c.s ? 0 : undefined,
285
+ grant_types: ["authorization_code", "refresh_token"],
286
+ response_types: ["code"],
287
+ };
288
+ },
289
+ registerClient(meta) {
290
+ const uris = meta.redirect_uris || [];
291
+ if (!uris.length || uris.length > MAX_REDIRECT_URIS) {
292
+ throw new InvalidClientMetadataError(`redirect_uris must contain 1 to ${MAX_REDIRECT_URIS} entries`);
293
+ }
294
+ for (const uri of uris) {
295
+ const u = new URL(uri);
296
+ if (uri.length > MAX_REDIRECT_URI_LENGTH || u.hash) {
297
+ throw new InvalidClientMetadataError("redirect_uris must be short and must not contain a fragment");
298
+ }
299
+ if (u.protocol === "http:" && !LOOPBACK.has(u.hostname)) {
300
+ throw new InvalidClientMetadataError("redirect_uris must use https (http is allowed for localhost only)");
301
+ }
302
+ }
303
+ const issuedAt = now();
304
+ const method = meta.token_endpoint_auth_method === "none" ? "none" : "client_secret_post";
305
+ const clientId =
306
+ CLIENT_PREFIX +
307
+ seal("client", {
308
+ r: uris,
309
+ n: meta.client_name ? String(meta.client_name).slice(0, 80) : undefined,
310
+ u: meta.client_uri ? String(meta.client_uri).slice(0, 200) : undefined,
311
+ m: method,
312
+ s: method === "none" ? undefined : meta.client_secret,
313
+ t: issuedAt,
314
+ });
315
+ return {
316
+ ...meta,
317
+ client_id: clientId,
318
+ client_id_issued_at: issuedAt,
319
+ token_endpoint_auth_method: method,
320
+ grant_types: ["authorization_code", "refresh_token"],
321
+ response_types: ["code"],
322
+ };
323
+ },
324
+ };
325
+
326
+ function issueTokens(grant) {
327
+ const t = now();
328
+ const base = { k: grant.k, c: grant.c, cid: grant.cid, aud: resource, iat: t };
329
+ return {
330
+ access_token: ACCESS_TOKEN_PREFIX + seal("access", { ...base, exp: t + ACCESS_TTL }),
331
+ token_type: "Bearer",
332
+ expires_in: ACCESS_TTL,
333
+ refresh_token:
334
+ REFRESH_TOKEN_PREFIX + seal("refresh", { ...base, exp: t + REFRESH_TTL, jti: b64(crypto.randomBytes(12)) }),
335
+ };
336
+ }
337
+
338
+ function openCode(client, code) {
339
+ const c = unwrap("code", CODE_PREFIX, code);
340
+ if (!c || c.exp <= now() || c.cid !== clientRef(client.client_id)) {
341
+ throw new InvalidGrantError("Invalid or expired authorization code");
342
+ }
343
+ return c;
344
+ }
345
+
346
+ function keyCheckAllowed(ip) {
347
+ const t = now();
348
+ if (keyChecks.size > MAX_TRACKED) keyChecks.clear();
349
+ const recent = (keyChecks.get(ip) || []).filter((x) => x > t - KEY_CHECK_WINDOW);
350
+ if (recent.length >= KEY_CHECK_MAX) {
351
+ keyChecks.set(ip, recent);
352
+ return false;
353
+ }
354
+ recent.push(t);
355
+ keyChecks.set(ip, recent);
356
+ return true;
357
+ }
358
+
359
+ // Binds the form to the authorization request it was rendered for.
360
+ const csrfBinding = (client, params) =>
361
+ b64(sha([client.client_id, params.redirectUri, params.codeChallenge, params.state ?? ""].join("\n")));
362
+
363
+ function sendForm(res, client, params, { status = 200, error } = {}) {
364
+ const req = res.req;
365
+ const src = req.method === "POST" ? req.body || {} : req.query || {};
366
+ const cookieNonce = b64(crypto.randomBytes(18));
367
+ const styleNonce = b64(crypto.randomBytes(16));
368
+ const csrf = seal("csrf", { n: cookieNonce, b: csrfBinding(client, params), exp: now() + CSRF_TTL });
369
+ res.status(status);
370
+ res.setHeader(
371
+ "Set-Cookie",
372
+ `${CSRF_COOKIE}=${cookieNonce}; Path=/authorize; Max-Age=${CSRF_TTL}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`
373
+ );
374
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
375
+ res.setHeader("Cache-Control", "no-store");
376
+ res.setHeader("Referrer-Policy", "no-referrer");
377
+ res.setHeader("X-Frame-Options", "DENY");
378
+ res.setHeader(
379
+ "Content-Security-Policy",
380
+ `default-src 'none'; style-src 'nonce-${styleNonce}'; base-uri 'none'; frame-ancestors 'none'`
381
+ );
382
+ res.end(
383
+ renderPage({
384
+ nonce: styleNonce,
385
+ clientName: client.client_name || "An MCP client",
386
+ host: redirectHost(params.redirectUri),
387
+ error,
388
+ hidden: {
389
+ csrf,
390
+ client_id: client.client_id,
391
+ redirect_uri: params.redirectUri,
392
+ response_type: "code",
393
+ code_challenge: params.codeChallenge,
394
+ code_challenge_method: "S256",
395
+ state: params.state,
396
+ scope: typeof src.scope === "string" ? src.scope : undefined,
397
+ resource: params.resource?.href,
398
+ },
399
+ })
400
+ );
401
+ }
402
+
403
+ function csrfValid(req, client, params) {
404
+ const token = open("csrf", req.body.csrf);
405
+ if (!token || token.exp <= now() || token.b !== csrfBinding(client, params)) return false;
406
+ const cookie = String(req.headers.cookie || "")
407
+ .split(";")
408
+ .map((p) => p.trim())
409
+ .find((p) => p.startsWith(CSRF_COOKIE + "="));
410
+ const value = Buffer.from(cookie ? cookie.slice(CSRF_COOKIE.length + 1) : "");
411
+ const expected = Buffer.from(String(token.n));
412
+ return value.length === expected.length && crypto.timingSafeEqual(value, expected);
413
+ }
414
+
415
+ const provider = {
416
+ clientsStore,
417
+
418
+ // Called by the SDK handler after client_id, redirect_uri and the PKCE
419
+ // parameters are validated - for the initial GET and for the form POST
420
+ // (the form carries the original parameters, so they are validated again).
421
+ async authorize(client, params, res) {
422
+ assertResource(params.resource);
423
+ const req = res.req;
424
+ const body = req.method === "POST" ? req.body || {} : null;
425
+ if (!body || typeof body.csrf !== "string") return sendForm(res, client, params);
426
+
427
+ if (!csrfValid(req, client, params)) {
428
+ return sendForm(res, client, params, {
429
+ status: 400,
430
+ error: { title: "This form expired.", text: "Please enter your key again." },
431
+ });
432
+ }
433
+ 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) {
437
+ return sendForm(res, client, params, {
438
+ status: 400,
439
+ error: { title: "A key is required.", text: "Paste your EnCarAPI key to connect." },
440
+ });
441
+ }
442
+ if (!keyCheckAllowed(clientIp(req))) {
443
+ return sendForm(res, client, params, {
444
+ status: 429,
445
+ error: { title: "Too many attempts.", text: "Please wait a few minutes and try again." },
446
+ });
447
+ }
448
+ const check = await checkKeys({ apiKey, chinaKey }, fetchImpl);
449
+ if (!check.ok) {
450
+ return sendForm(res, client, params, {
451
+ status: check.reason === "rejected" ? 400 : 503,
452
+ error:
453
+ check.reason === "rejected"
454
+ ? { title: `This ${check.product} key was not accepted.`, text: "Check the key and that your plan is active." }
455
+ : { title: `${check.product} could not be reached.`, text: "The key was not checked. Please try again in a moment." },
456
+ });
457
+ }
458
+
459
+ const code =
460
+ CODE_PREFIX +
461
+ seal("code", {
462
+ k: apiKey || undefined,
463
+ c: chinaKey || undefined,
464
+ cid: clientRef(client.client_id),
465
+ ru: params.redirectUri,
466
+ cc: params.codeChallenge,
467
+ exp: now() + CODE_TTL,
468
+ jti: b64(crypto.randomBytes(12)),
469
+ });
470
+ const target = new URL(params.redirectUri);
471
+ target.searchParams.set("code", code);
472
+ if (params.state !== undefined) target.searchParams.set("state", params.state);
473
+ target.searchParams.set("iss", oauthMetadata.issuer);
474
+ res.setHeader("Set-Cookie", `${CSRF_COOKIE}=; Path=/authorize; Max-Age=0; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`);
475
+ res.setHeader("Referrer-Policy", "no-referrer");
476
+ res.redirect(302, target.href);
477
+ },
478
+
479
+ async challengeForAuthorizationCode(client, code) {
480
+ return openCode(client, code).cc;
481
+ },
482
+
483
+ // The SDK handler has verified the PKCE code_verifier against the challenge before this runs.
484
+ async exchangeAuthorizationCode(client, code, _verifier, redirectUri, requestedResource) {
485
+ const c = openCode(client, code);
486
+ if (redirectUri !== undefined && redirectUri !== c.ru) {
487
+ throw new InvalidGrantError("redirect_uri does not match the authorization request");
488
+ }
489
+ assertResource(requestedResource);
490
+ if (usedCodes.get(c.jti)) throw new InvalidGrantError("Authorization code was already used");
491
+ usedCodes.set(c.jti, { exp: c.exp });
492
+ return issueTokens(c);
493
+ },
494
+
495
+ async exchangeRefreshToken(client, refreshToken, _scopes, requestedResource) {
496
+ const r = unwrap("refresh", REFRESH_TOKEN_PREFIX, refreshToken);
497
+ if (!r || r.exp <= now() || r.cid !== clientRef(client.client_id) || r.aud !== resource) {
498
+ throw new InvalidGrantError("Invalid or expired refresh token");
499
+ }
500
+ assertResource(requestedResource);
501
+ const used = usedRefresh.get(r.jti);
502
+ if (used && now() - used.at > REFRESH_REUSE_GRACE) {
503
+ throw new InvalidGrantError("Refresh token was already used");
504
+ }
505
+ if (!used) usedRefresh.set(r.jti, { exp: r.exp, at: now() });
506
+ return issueTokens(r);
507
+ },
508
+
509
+ async verifyAccessToken(token) {
510
+ const a = unwrap("access", ACCESS_TOKEN_PREFIX, token);
511
+ if (!a) throw new InvalidTokenError("Invalid access token");
512
+ if (a.exp <= now()) throw new InvalidTokenError("Token has expired");
513
+ return {
514
+ token,
515
+ clientId: a.cid,
516
+ scopes: [],
517
+ expiresAt: a.exp,
518
+ resource: new URL(a.aud),
519
+ extra: { apiKey: a.k, chinaKey: a.c },
520
+ };
521
+ },
522
+ };
523
+
524
+ const oauthMetadata = {
525
+ ...createOAuthMetadata({
526
+ provider,
527
+ issuerUrl,
528
+ serviceDocumentationUrl: new URL("https://github.com/ThatMojo/encarapi-mcp"),
529
+ }),
530
+ authorization_response_iss_parameter_supported: true,
531
+ };
532
+ const resourceName = "EnCarAPI MCP server";
533
+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);
534
+ const wwwAuthenticate = `Bearer resource_metadata="${resourceMetadataUrl}"`;
535
+
536
+ // The SDK's per-IP limits, keyed by the real caller instead of the proxy. Token and
537
+ // registration limits are generous because hosted clients share egress addresses.
538
+ const limit = (max) => ({ max, keyGenerator: (req) => clientIp(req), validate: false });
539
+
540
+ const app = express();
541
+ app.disable("x-powered-by");
542
+ app.use((_req, res, next) => {
543
+ res.setHeader("X-Content-Type-Options", "nosniff");
544
+ next();
545
+ });
546
+ app.use("/authorize", authorizationHandler({ provider, rateLimit: limit(100) }));
547
+ app.use("/token", tokenHandler({ provider, rateLimit: limit(600) }));
548
+ app.use(
549
+ "/register",
550
+ clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds: 0, clientIdGeneration: false, rateLimit: limit(300) })
551
+ );
552
+ app.use("/.well-known", (_req, res, next) => {
553
+ res.setHeader("Cache-Control", "public, max-age=300");
554
+ next();
555
+ });
556
+ // /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource/mcp
557
+ app.use(
558
+ mcpAuthMetadataRouter({
559
+ oauthMetadata,
560
+ resourceServerUrl: resourceUrl,
561
+ resourceName,
562
+ serviceDocumentationUrl: new URL("https://github.com/ThatMojo/encarapi-mcp"),
563
+ })
564
+ );
565
+ // Root variant for clients that do not append the resource path.
566
+ app.use(
567
+ "/.well-known/oauth-protected-resource",
568
+ metadataHandler({
569
+ resource,
570
+ authorization_servers: [oauthMetadata.issuer],
571
+ resource_name: resourceName,
572
+ resource_documentation: "https://github.com/ThatMojo/encarapi-mcp",
573
+ })
574
+ );
575
+ app.post(
576
+ "/mcp",
577
+ requireBearerAuth({ verifier: provider, resourceMetadataUrl, expectedResource: resourceUrl }),
578
+ (req, res) => handleMcp(req, res, { apiKey: req.auth.extra.apiKey, chinaKey: req.auth.extra.chinaKey })
579
+ );
580
+ app.use((_req, res) => {
581
+ res.setHeader("Cache-Control", "no-store");
582
+ res.status(404).json({ error: "Not found. MCP endpoint: /mcp" });
583
+ });
584
+ app.use((err, _req, res, _next) => {
585
+ const status = err?.status >= 400 && err?.status < 500 ? err.status : 500;
586
+ if (!res.headersSent) res.status(status).json({ error: status === 500 ? "server_error" : "invalid_request" });
587
+ });
588
+
589
+ return {
590
+ app,
591
+ provider,
592
+ resource,
593
+ resourceMetadataUrl,
594
+ wwwAuthenticate,
595
+ owns: (pathname) =>
596
+ pathname === "/authorize" || pathname === "/token" || pathname === "/register" || pathname.startsWith("/.well-known/oauth-"),
597
+ };
598
+ }
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.0.0";
7
+ export const VERSION = "1.1.0";
8
8
  const MAX_TEXT = 40000;
9
9
 
10
10
  const asText = (data) => {
@@ -69,7 +69,16 @@ const readOnly = { readOnlyHint: true, openWorldHint: true };
69
69
  * also Chinese data if it has the China add-on), `chinaKey` an optional separate
70
70
  * ChinaCarAPI key.
71
71
  */
72
- export function createServer({ apiKey, chinaKey, fetchImpl } = {}) {
72
+ // Every API call carries "encarapi-mcp/<version> (<transport>)" as User-Agent,
73
+ // so MCP usage can be told apart from other clients on the API side.
74
+ function withUserAgent(fetchImpl, transport) {
75
+ const base = fetchImpl || globalThis.fetch;
76
+ const ua = `encarapi-mcp/${VERSION} (${transport})`;
77
+ return (url, init = {}) => base(url, { ...init, headers: { ...(init.headers || {}), "User-Agent": ua } });
78
+ }
79
+
80
+ export function createServer({ apiKey, chinaKey, fetchImpl, transport = "stdio" } = {}) {
81
+ fetchImpl = withUserAgent(fetchImpl, transport);
73
82
  const server = new McpServer(
74
83
  { name: "encarapi", title: "EnCarAPI - Korean & Chinese used car data", version: VERSION },
75
84
  {