encarapi-mcp 1.0.0 → 1.2.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 +97 -6
- package/package.json +6 -4
- package/src/app.js +183 -0
- package/src/brand.js +41 -0
- package/src/http.js +6 -90
- package/src/oauth.js +657 -0
- package/src/server.js +234 -162
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
> **An API key is required.** Get one (5-day trial) at [encarapi.com](https://encarapi.com).
|
|
9
9
|
> Chinese data works with a [ChinaCarAPI](https://chinacarapi.com) key or an EnCarAPI key
|
|
10
|
-
> with the China add-on.
|
|
10
|
+
> with the China add-on. ChinaCarAPI customers: see [For ChinaCarAPI customers](#for-chinacarapi-customers).
|
|
11
11
|
|
|
12
12
|
## Tools
|
|
13
13
|
|
|
@@ -19,16 +19,42 @@
|
|
|
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.
|
|
28
29
|
|
|
29
30
|
## Option 1: hosted (no install)
|
|
30
31
|
|
|
31
|
-
Add this URL as a remote MCP server
|
|
32
|
+
Add this URL as a remote MCP server:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
https://mcp.encarapi.com/mcp
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
In clients with OAuth support the URL is all you need. On first use a browser window opens,
|
|
39
|
+
you paste your EnCarAPI key once, and the client is connected:
|
|
40
|
+
|
|
41
|
+
- **Claude** (claude.ai, desktop, mobile): Settings - Connectors - Add custom connector, paste the URL
|
|
42
|
+
- **ChatGPT** (developer mode): Settings - Connectors - create a connector with the URL
|
|
43
|
+
- **Cursor**: `{"mcpServers": {"encarapi": {"url": "https://mcp.encarapi.com/mcp"}}}` in `.cursor/mcp.json`
|
|
44
|
+
- **VS Code**: "MCP: Add Server" - HTTP - paste the URL
|
|
45
|
+
- **Claude Code**:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
claude mcp add --transport http encarapi https://mcp.encarapi.com/mcp
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The key is checked once and is not stored on the server: it is encrypted into the token
|
|
52
|
+
your client receives. To disconnect, remove the server in your client; to cut off access
|
|
53
|
+
everywhere, rotate your key at [encarapi.com](https://encarapi.com).
|
|
54
|
+
|
|
55
|
+
### Alternative: send the key yourself
|
|
56
|
+
|
|
57
|
+
Clients without OAuth support, scripts and gateways can send the key directly:
|
|
32
58
|
|
|
33
59
|
```
|
|
34
60
|
https://mcp.encarapi.com/mcp
|
|
@@ -42,9 +68,50 @@ claude mcp add --transport http encarapi https://mcp.encarapi.com/mcp \
|
|
|
42
68
|
--header "Authorization: Bearer YOUR_ENCARAPI_KEY"
|
|
43
69
|
```
|
|
44
70
|
|
|
45
|
-
Clients that only accept a URL
|
|
46
|
-
|
|
47
|
-
goes into the
|
|
71
|
+
The `x-api-key: YOUR_ENCARAPI_KEY` header works as well. Clients that only accept a URL and
|
|
72
|
+
have no OAuth support can use `https://mcp.encarapi.com/mcp?key=YOUR_ENCARAPI_KEY` (a header
|
|
73
|
+
is preferred, since URLs can end up in logs). A separate ChinaCarAPI key goes into the
|
|
74
|
+
`x-china-key` header, or into the second field of the browser form.
|
|
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
|
+
```
|
|
48
115
|
|
|
49
116
|
## Option 2: local (npx)
|
|
50
117
|
|
|
@@ -88,6 +155,30 @@ docker run -p 3000:3000 encarapi-mcp # POST /mcp, GET /health
|
|
|
88
155
|
|
|
89
156
|
Stateless: every request carries its own key, nothing is stored.
|
|
90
157
|
|
|
158
|
+
To enable the OAuth flow ("connect by URL only"), set two environment variables:
|
|
159
|
+
|
|
160
|
+
| Variable | Meaning |
|
|
161
|
+
|---|---|
|
|
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. |
|
|
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. |
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
docker run -p 3000:3000 -e MCP_OAUTH_SECRET="$(openssl rand -base64 48)" \
|
|
168
|
+
-e MCP_PUBLIC_URL=https://mcp.example.com encarapi-mcp
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
This adds `/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server`,
|
|
172
|
+
`/register`, `/authorize` and `/token` (OAuth 2.1 with PKCE, dynamic client registration).
|
|
173
|
+
There is still no database: client ids, authorization codes and tokens are encrypted,
|
|
174
|
+
self-contained values (AES-256-GCM) that carry the key. Consequences:
|
|
175
|
+
|
|
176
|
+
- Changing `MCP_OAUTH_SECRET` signs out all OAuth clients (they reconnect through the browser).
|
|
177
|
+
- Access tokens last 1 hour, refresh tokens 90 days and are replaced on every use.
|
|
178
|
+
- Single use of authorization codes and of replaced refresh tokens is tracked in memory, so
|
|
179
|
+
it is best-effort: it does not survive a restart and is not shared between instances.
|
|
180
|
+
- A single token cannot be revoked on the server. Rotating the EnCarAPI key cuts off all access.
|
|
181
|
+
|
|
91
182
|
## Links
|
|
92
183
|
|
|
93
184
|
- EnCarAPI: https://encarapi.com
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "encarapi-mcp",
|
|
3
|
-
"version": "1.
|
|
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.0",
|
|
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": {
|
|
@@ -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": [
|
|
@@ -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",
|
|
@@ -49,6 +50,7 @@
|
|
|
49
50
|
"dependencies": {
|
|
50
51
|
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
51
52
|
"encarapi": "^1.0.0",
|
|
52
|
-
"zod": "^4.1.0"
|
|
53
|
+
"zod": "^4.1.0",
|
|
54
|
+
"express": "^5.2.1"
|
|
53
55
|
}
|
|
54
56
|
}
|
package/src/app.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
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
|
+
//
|
|
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.
|
|
14
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
15
|
+
import { createServer, VERSION } from "./server.js";
|
|
16
|
+
import { createOAuth, ACCESS_TOKEN_PREFIX } from "./oauth.js";
|
|
17
|
+
import { brandFor } from "./brand.js";
|
|
18
|
+
|
|
19
|
+
const MAX_BODY = 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
function bearerFrom(req) {
|
|
22
|
+
const auth = req.headers.authorization || "";
|
|
23
|
+
return auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
|
|
24
|
+
}
|
|
25
|
+
|
|
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 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readJson(req) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
let size = 0;
|
|
36
|
+
const chunks = [];
|
|
37
|
+
req.on("data", (c) => {
|
|
38
|
+
size += c.length;
|
|
39
|
+
if (size > MAX_BODY) {
|
|
40
|
+
reject(new Error("body too large"));
|
|
41
|
+
req.destroy();
|
|
42
|
+
} else chunks.push(c);
|
|
43
|
+
});
|
|
44
|
+
req.on("end", () => {
|
|
45
|
+
try {
|
|
46
|
+
resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined);
|
|
47
|
+
} catch (e) {
|
|
48
|
+
reject(e);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
req.on("error", reject);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const send = (res, status, body, headers = {}) => {
|
|
56
|
+
res.writeHead(status, { "Content-Type": "application/json", ...headers });
|
|
57
|
+
res.end(JSON.stringify(body));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// Browser-based MCP clients need to read the 401 challenge and send custom headers.
|
|
61
|
+
const MCP_CORS = {
|
|
62
|
+
"Access-Control-Allow-Origin": "*",
|
|
63
|
+
"Access-Control-Expose-Headers": "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version",
|
|
64
|
+
};
|
|
65
|
+
const MCP_PREFLIGHT = {
|
|
66
|
+
"Access-Control-Allow-Origin": "*",
|
|
67
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
68
|
+
"Access-Control-Allow-Headers":
|
|
69
|
+
"Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Last-Event-ID, x-api-key, x-china-key",
|
|
70
|
+
"Access-Control-Max-Age": "86400",
|
|
71
|
+
};
|
|
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
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Builds the HTTP request listener. `env.MCP_OAUTH_SECRET` enables the OAuth
|
|
92
|
+
* endpoints; without it the server only accepts keys sent by the client.
|
|
93
|
+
* `fetchImpl` and `now` are for tests.
|
|
94
|
+
*/
|
|
95
|
+
export function createHandler({ env = process.env, fetchImpl, now } = {}) {
|
|
96
|
+
async function handleMcp(req, res, { apiKey, chinaKey, brand }) {
|
|
97
|
+
let body;
|
|
98
|
+
try {
|
|
99
|
+
body = await readJson(req);
|
|
100
|
+
} catch {
|
|
101
|
+
return send(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const server = createServer({ apiKey, chinaKey, fetchImpl, transport: "hosted", brand: brand.id });
|
|
105
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
106
|
+
res.on("close", () => {
|
|
107
|
+
transport.close();
|
|
108
|
+
server.close();
|
|
109
|
+
});
|
|
110
|
+
try {
|
|
111
|
+
await server.connect(transport);
|
|
112
|
+
await transport.handleRequest(req, res, body);
|
|
113
|
+
} catch (e) {
|
|
114
|
+
console.error("mcp request failed:", e?.message);
|
|
115
|
+
if (!res.headersSent) send(res, 500, { jsonrpc: "2.0", error: { code: -32603, message: "Internal error" }, id: null });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
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;
|
|
137
|
+
|
|
138
|
+
return async (req, res) => {
|
|
139
|
+
const url = new URL(req.url, "http://localhost");
|
|
140
|
+
const { brand, oauth } = sites.get(hostOf(req)) || fallback;
|
|
141
|
+
|
|
142
|
+
if (url.pathname === "/health") return send(res, 200, { ok: true, version: VERSION });
|
|
143
|
+
if (url.pathname === "/" && req.method === "GET") {
|
|
144
|
+
res.writeHead(302, { Location: "https://github.com/ThatMojo/encarapi-mcp" });
|
|
145
|
+
return res.end();
|
|
146
|
+
}
|
|
147
|
+
if (oauth?.owns(url.pathname)) return oauth.app(req, res);
|
|
148
|
+
if (url.pathname !== "/mcp") return send(res, 404, { error: "Not found. MCP endpoint: /mcp" });
|
|
149
|
+
|
|
150
|
+
if (oauth) {
|
|
151
|
+
if (req.method === "OPTIONS") {
|
|
152
|
+
res.writeHead(204, MCP_PREFLIGHT);
|
|
153
|
+
return res.end();
|
|
154
|
+
}
|
|
155
|
+
for (const [k, v] of Object.entries(MCP_CORS)) res.setHeader(k, v);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Stateless mode: no sessions, so GET (SSE stream) and DELETE are not offered.
|
|
159
|
+
if (req.method !== "POST") {
|
|
160
|
+
res.writeHead(405, { Allow: "POST" });
|
|
161
|
+
return res.end();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 1. OAuth access token issued by this server (verified, audience-bound, 401 when invalid or expired).
|
|
165
|
+
if (oauth && bearerFrom(req).startsWith(ACCESS_TOKEN_PREFIX)) return oauth.app(req, res);
|
|
166
|
+
|
|
167
|
+
// 2. Key sent by the client.
|
|
168
|
+
const { apiKey, chinaKey } = keysFrom(req, url, brand);
|
|
169
|
+
if (!apiKey && !chinaKey) {
|
|
170
|
+
return send(
|
|
171
|
+
res,
|
|
172
|
+
401,
|
|
173
|
+
{
|
|
174
|
+
jsonrpc: "2.0",
|
|
175
|
+
error: { code: -32001, message: `API key required: Authorization: Bearer <key> (get one at ${brand.signupUrl})` },
|
|
176
|
+
id: null,
|
|
177
|
+
},
|
|
178
|
+
oauth ? { "WWW-Authenticate": oauth.wwwAuthenticate, "Cache-Control": "no-store" } : {}
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
return handleMcp(req, res, { apiKey, chinaKey, brand });
|
|
182
|
+
};
|
|
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",
|
|
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/#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/http.js
CHANGED
|
@@ -1,96 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Hosted MCP endpoint (Streamable HTTP, stateless).
|
|
3
|
-
//
|
|
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 {
|
|
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
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
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)`));
|