@zenlayer/lune-mcp 0.0.0-stage → 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 +266 -2
- package/dist/chunk-6A53FJ4B.js +289 -0
- package/dist/chunk-EFKSB46S.js +403 -0
- package/dist/chunk-G7ZX5GSF.js +11 -0
- package/dist/chunk-MC3S3YL6.js +11 -0
- package/dist/chunk-NN23AOUC.js +97 -0
- package/dist/chunk-OK2ZWFDB.js +158 -0
- package/dist/chunk-PQYX44KQ.js +28 -0
- package/dist/chunk-SJ6RY4EA.js +125 -0
- package/dist/chunk-TFX4RC2N.js +367 -0
- package/dist/cli.js +61 -0
- package/dist/doctor-WZJF4O2Y.js +371 -0
- package/dist/index.js +12100 -0
- package/dist/install-F4IVDNAW.js +277 -0
- package/dist/login-3X77QT2S.js +54 -0
- package/dist/logout-Q64WE4R4.js +36 -0
- package/dist/main-QRRGC4CK.js +11018 -0
- package/dist/oauth-login-72EBYFE6.js +23 -0
- package/dist/remote.js +12002 -0
- package/package.json +66 -4
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/shared/env.ts
|
|
4
|
+
function apiBase() {
|
|
5
|
+
return process.env.LUNE_MCP_API_BASE?.trim() || "https://www.lune.io/api";
|
|
6
|
+
}
|
|
7
|
+
function asIssuer() {
|
|
8
|
+
return (process.env.LUNE_MCP_AS_ISSUER?.trim() || "https://auth.lune.io/oauth").replace(/\/+$/, "");
|
|
9
|
+
}
|
|
10
|
+
var DEFAULT_REMOTE_URL = "https://www.lune.io/mcp";
|
|
11
|
+
function mcpUrl() {
|
|
12
|
+
return (process.env.LUNE_MCP_URL?.trim() || DEFAULT_REMOTE_URL).replace(/\/+$/, "");
|
|
13
|
+
}
|
|
14
|
+
function websiteOrigin() {
|
|
15
|
+
return (process.env.LUNE_MCP_WEBSITE_ORIGIN?.trim() || "https://www.lune.io").replace(/\/+$/, "");
|
|
16
|
+
}
|
|
17
|
+
function supplierOrigin() {
|
|
18
|
+
return (process.env.LUNE_MCP_SUPPLIER_ORIGIN?.trim() || "https://supplier.lune.io").replace(/\/+$/, "");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export {
|
|
22
|
+
apiBase,
|
|
23
|
+
asIssuer,
|
|
24
|
+
DEFAULT_REMOTE_URL,
|
|
25
|
+
mcpUrl,
|
|
26
|
+
websiteOrigin,
|
|
27
|
+
supplierOrigin
|
|
28
|
+
};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
log
|
|
4
|
+
} from "./chunk-TFX4RC2N.js";
|
|
5
|
+
|
|
6
|
+
// src/stdio/credential-store.ts
|
|
7
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
8
|
+
import { homedir } from "os";
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
var KEYCHAIN_SERVICE = "lune-mcp";
|
|
11
|
+
var KEYCHAIN_ACCOUNT = "default";
|
|
12
|
+
var NO_STORE_HINT = [
|
|
13
|
+
"No usable credential store: login cannot save the refresh token securely. Three options:",
|
|
14
|
+
" 1) Install a system keychain / Secret Service (macOS Keychain / Windows Credential Manager / Linux libsecret);",
|
|
15
|
+
" 2) Skip login and use the LUNE_MCP_TOKEN environment variable instead (a user JWT valid for 24h, escape hatch);",
|
|
16
|
+
" 3) Explicitly accept plaintext on disk: set LUNE_MCP_ALLOW_FILE_CREDENTIALS=1 (writes ~/.lune-mcp/credentials.json, mode 0600)."
|
|
17
|
+
].join("\n");
|
|
18
|
+
function parseStored(raw) {
|
|
19
|
+
try {
|
|
20
|
+
const data = JSON.parse(raw);
|
|
21
|
+
if (typeof data.refresh_token !== "string" || !data.refresh_token) return null;
|
|
22
|
+
return {
|
|
23
|
+
refresh_token: data.refresh_token,
|
|
24
|
+
user_id: typeof data.user_id === "string" ? data.user_id : "",
|
|
25
|
+
is_supplier: data.is_supplier === true,
|
|
26
|
+
scopes: typeof data.scopes === "string" ? data.scopes : "",
|
|
27
|
+
obtained_at: typeof data.obtained_at === "string" ? data.obtained_at : ""
|
|
28
|
+
};
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function metaOf(creds) {
|
|
34
|
+
if (!creds) return null;
|
|
35
|
+
return { user_id: creds.user_id, is_supplier: creds.is_supplier, scopes: creds.scopes };
|
|
36
|
+
}
|
|
37
|
+
var defaultEntryFactory = async (service, account) => {
|
|
38
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
39
|
+
return new AsyncEntry(service, account);
|
|
40
|
+
};
|
|
41
|
+
var KeychainStore = class {
|
|
42
|
+
kind = "keychain";
|
|
43
|
+
entryFactory;
|
|
44
|
+
constructor(entryFactory = defaultEntryFactory) {
|
|
45
|
+
this.entryFactory = entryFactory;
|
|
46
|
+
}
|
|
47
|
+
/** 读写探针:headless Linux 常见「装得上但用不了」(docs/03 §5.2),必须真写一次。 */
|
|
48
|
+
async probe() {
|
|
49
|
+
try {
|
|
50
|
+
const entry = await this.entryFactory(KEYCHAIN_SERVICE, "__probe__");
|
|
51
|
+
await entry.setPassword("probe");
|
|
52
|
+
const got = await entry.getPassword();
|
|
53
|
+
await entry.deleteCredential();
|
|
54
|
+
return got === "probe";
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
entry() {
|
|
60
|
+
return this.entryFactory(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
|
|
61
|
+
}
|
|
62
|
+
async read() {
|
|
63
|
+
try {
|
|
64
|
+
const raw = await (await this.entry()).getPassword();
|
|
65
|
+
return raw ? parseStored(raw) : null;
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async write(creds) {
|
|
71
|
+
await (await this.entry()).setPassword(JSON.stringify(creds));
|
|
72
|
+
}
|
|
73
|
+
async delete() {
|
|
74
|
+
try {
|
|
75
|
+
await (await this.entry()).deleteCredential();
|
|
76
|
+
} catch {
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async readMeta() {
|
|
80
|
+
return metaOf(await this.read());
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
var FileStore = class {
|
|
84
|
+
kind = "file";
|
|
85
|
+
path;
|
|
86
|
+
dir;
|
|
87
|
+
constructor(dir = join(homedir(), ".lune-mcp")) {
|
|
88
|
+
this.dir = dir;
|
|
89
|
+
this.path = join(dir, "credentials.json");
|
|
90
|
+
log.warn(
|
|
91
|
+
`LUNE_MCP_ALLOW_FILE_CREDENTIALS=1: the refresh token will be stored in PLAINTEXT at ${this.path} (mode 0600). Switch to a system keychain as soon as possible.`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
async read() {
|
|
95
|
+
try {
|
|
96
|
+
return parseStored(readFileSync(this.path, "utf8"));
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async write(creds) {
|
|
102
|
+
mkdirSync(this.dir, { recursive: true, mode: 448 });
|
|
103
|
+
writeFileSync(this.path, JSON.stringify(creds, null, 2), { mode: 384 });
|
|
104
|
+
chmodSync(this.path, 384);
|
|
105
|
+
}
|
|
106
|
+
async delete() {
|
|
107
|
+
rmSync(this.path, { force: true });
|
|
108
|
+
}
|
|
109
|
+
async readMeta() {
|
|
110
|
+
return metaOf(await this.read());
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
async function openCredentialStore(opts = {}) {
|
|
114
|
+
const keychain = new KeychainStore(opts.entryFactory);
|
|
115
|
+
if (await keychain.probe()) return keychain;
|
|
116
|
+
const env = opts.env ?? process.env;
|
|
117
|
+
if (env.LUNE_MCP_ALLOW_FILE_CREDENTIALS === "1") return new FileStore(opts.fileDir);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export {
|
|
122
|
+
NO_STORE_HINT,
|
|
123
|
+
KeychainStore,
|
|
124
|
+
openCredentialStore
|
|
125
|
+
};
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/core/backend/errors.ts
|
|
4
|
+
var ApiError = class extends Error {
|
|
5
|
+
status;
|
|
6
|
+
code;
|
|
7
|
+
/** 给 agent/用户的下一步指引(如 reauthHint),会进 errorResult 的结构化输出。 */
|
|
8
|
+
hint;
|
|
9
|
+
/**
|
|
10
|
+
* 形态 1 信封里 message/type/code 之外的全部键(后端 extra),或白名单映射补的键
|
|
11
|
+
* (如 404 的 `resource`)。**刻意独立成一个对象**,见文件头注「绝不平铺」。
|
|
12
|
+
*/
|
|
13
|
+
details;
|
|
14
|
+
constructor(status, code, message, hint, details) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "ApiError";
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.hint = hint;
|
|
20
|
+
if (details && Object.keys(details).length > 0) this.details = details;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
var ScopeMisuseError = class extends Error {
|
|
24
|
+
constructor(message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "ScopeMisuseError";
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
function isScopeProgrammingError(err) {
|
|
30
|
+
if (err instanceof ScopeMisuseError) return true;
|
|
31
|
+
return err instanceof ApiError && err.status === 400 && (err.code === "project_context_required" || err.code === "project_context_mismatch");
|
|
32
|
+
}
|
|
33
|
+
var ENVELOPE_CORE_KEYS = /* @__PURE__ */ new Set(["message", "type", "code"]);
|
|
34
|
+
var STRING_DETAIL_RULES = [
|
|
35
|
+
// `<resource> not found` 的 404。其中 project / workspace / transaction 来自 project_scope 作用域层
|
|
36
|
+
// (不存在 **或** 不是成员,不给成员资格 oracle);其余几种发生在成员资格确认之后 ——
|
|
37
|
+
// 说明文案按 resource 分流,见 client.ts 规约 ⑦ 的 notFoundNote
|
|
38
|
+
// `api key` / `access policy`:Access policies(ZCON-33417,access_policies.py / workspace_tokens.py)——
|
|
39
|
+
// 选的 key 已撤销或不在本 ws、策略已删除或不属于本 ws(含 list_keys 的 access_policy_id 筛选)
|
|
40
|
+
{
|
|
41
|
+
status: 404,
|
|
42
|
+
match: /^(project|workspace|token|transaction|member|invite|topup|refundable top-up|api key|access policy) not found$/,
|
|
43
|
+
code: "not_found",
|
|
44
|
+
details: (m) => ({ resource: m[1] })
|
|
45
|
+
},
|
|
46
|
+
// 退款(user.py _refund_topup)—— C8 不提供退款工具,映射保留给 get_billing 解释 refundable。
|
|
47
|
+
// 「不是付款人」是形态 1 的结构化码 `403 refund_not_initiator`(wallets.assert_refund_allowed,ZCON-33421),
|
|
48
|
+
// 原样透传、不进这张表;它**不是** permission_denied(调用者持有 wallet:manage),别翻成权限引导。
|
|
49
|
+
// 流水的 refundable 已按调用者算(not_initiator),这个 403 只剩竞态;网页对它的友好句是
|
|
50
|
+
// 「Only the person who paid can refund this top-up.」,MCP 没有退款入口,用不上。
|
|
51
|
+
{ status: 403, match: "refund window expired", code: "refund_window_expired" },
|
|
52
|
+
{ status: 409, match: "topup is not refundable", code: "topup_not_refundable" },
|
|
53
|
+
{ status: 400, match: "only card top-ups can be refunded", code: "refund_card_only" },
|
|
54
|
+
{ status: 400, match: "no payment to refund", code: "refund_no_payment" },
|
|
55
|
+
{ status: 409, match: "no unconsumed credits to refund", code: "refund_nothing_unconsumed" },
|
|
56
|
+
{ status: 409, match: "balance changed, please retry refund", code: "refund_balance_changed" },
|
|
57
|
+
// auto top-up(user.py update_auto_topup)
|
|
58
|
+
{ status: 400, match: "add a card first (no saved payment method)", code: "no_saved_card" },
|
|
59
|
+
{
|
|
60
|
+
status: 400,
|
|
61
|
+
match: "threshold_usd and amount_usd are required when enabling",
|
|
62
|
+
code: "auto_topup_fields_required"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
status: 400,
|
|
66
|
+
match: /^amount_usd exceeds the \$(\d+(?:\.\d+)?) per-charge limit$/,
|
|
67
|
+
code: "amount_over_charge_limit",
|
|
68
|
+
details: (m) => ({ limit_usd: Number(m[1]) })
|
|
69
|
+
},
|
|
70
|
+
// 杂项
|
|
71
|
+
{ status: 409, match: "project wallet not provisioned", code: "wallet_not_provisioned" },
|
|
72
|
+
{ status: 400, match: "invalid type filter", code: "invalid_type_filter" }
|
|
73
|
+
];
|
|
74
|
+
function mapStringDetail(status, detail) {
|
|
75
|
+
const text = detail.trim();
|
|
76
|
+
for (const rule of STRING_DETAIL_RULES) {
|
|
77
|
+
if (rule.status !== status) continue;
|
|
78
|
+
if (typeof rule.match === "string") {
|
|
79
|
+
if (text === rule.match) return { code: rule.code, message: detail };
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const m = text.match(rule.match);
|
|
83
|
+
if (m) {
|
|
84
|
+
const details = rule.details?.(m);
|
|
85
|
+
return details ? { code: rule.code, message: detail, details } : { code: rule.code, message: detail };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { code: `http_${status}`, message: detail };
|
|
89
|
+
}
|
|
90
|
+
function parseErrorBody(status, body) {
|
|
91
|
+
const fallbackCode = `http_${status}`;
|
|
92
|
+
let data;
|
|
93
|
+
try {
|
|
94
|
+
data = JSON.parse(body);
|
|
95
|
+
} catch {
|
|
96
|
+
const text = body.trim().slice(0, 300);
|
|
97
|
+
return { code: fallbackCode, message: text || `HTTP ${status}` };
|
|
98
|
+
}
|
|
99
|
+
if (typeof data !== "object" || data === null) {
|
|
100
|
+
const text = String(data).trim();
|
|
101
|
+
return { code: fallbackCode, message: text || `HTTP ${status}` };
|
|
102
|
+
}
|
|
103
|
+
const obj = data;
|
|
104
|
+
const detail = obj.detail;
|
|
105
|
+
if (typeof detail === "object" && detail !== null && !Array.isArray(detail)) {
|
|
106
|
+
const err = detail.error;
|
|
107
|
+
if (typeof err === "object" && err !== null) {
|
|
108
|
+
const e = err;
|
|
109
|
+
const message = typeof e.message === "string" ? e.message : JSON.stringify(err);
|
|
110
|
+
const code = typeof e.code === "string" ? e.code : typeof e.type === "string" ? e.type : fallbackCode;
|
|
111
|
+
const details = {};
|
|
112
|
+
for (const [k, v] of Object.entries(e)) {
|
|
113
|
+
if (!ENVELOPE_CORE_KEYS.has(k)) details[k] = v;
|
|
114
|
+
}
|
|
115
|
+
return Object.keys(details).length > 0 ? { code, message, details } : { code, message };
|
|
116
|
+
}
|
|
117
|
+
return { code: fallbackCode, message: JSON.stringify(detail) };
|
|
118
|
+
}
|
|
119
|
+
if (typeof detail === "string") return mapStringDetail(status, detail);
|
|
120
|
+
if (Array.isArray(detail)) {
|
|
121
|
+
const parts = detail.map((item) => {
|
|
122
|
+
if (typeof item === "object" && item !== null) {
|
|
123
|
+
const it = item;
|
|
124
|
+
const loc = Array.isArray(it.loc) ? it.loc.join(".") : "";
|
|
125
|
+
const msg = typeof it.msg === "string" ? it.msg : JSON.stringify(item);
|
|
126
|
+
return loc ? `${loc}: ${msg}` : msg;
|
|
127
|
+
}
|
|
128
|
+
return String(item);
|
|
129
|
+
});
|
|
130
|
+
return { code: "validation_error", message: parts.join("; ") };
|
|
131
|
+
}
|
|
132
|
+
if (typeof obj.message === "string") return { code: fallbackCode, message: obj.message };
|
|
133
|
+
if (typeof obj.error === "string") return { code: fallbackCode, message: obj.error };
|
|
134
|
+
return { code: fallbackCode, message: body.slice(0, 300) || `HTTP ${status}` };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// src/core/backend/client.ts
|
|
138
|
+
var PROJECT_HEADER = "x-project-id";
|
|
139
|
+
var WORKSPACE_HEADER = "x-workspace-id";
|
|
140
|
+
var WORKSPACE_FILTER_PATHS = [
|
|
141
|
+
"/v1/user/self/usage",
|
|
142
|
+
"/v1/user/self/usage/summary",
|
|
143
|
+
"/v1/user/self/logs"
|
|
144
|
+
];
|
|
145
|
+
var UNSCOPED_PREFIXES = ["/v1/auth/", "/v1/public/", "/supplier/", "/v1/invites/"];
|
|
146
|
+
var UNSCOPED_EXACT = /* @__PURE__ */ new Set(["/v1/auth", "/v1/public", "/supplier", "/v1/projects", "/v1/invites"]);
|
|
147
|
+
function normalizePath(path) {
|
|
148
|
+
const bare = path.split("?")[0] ?? path;
|
|
149
|
+
return bare.length > 1 ? bare.replace(/\/+$/, "") : bare;
|
|
150
|
+
}
|
|
151
|
+
function assertScope(method, path, scope) {
|
|
152
|
+
if (!scope) return;
|
|
153
|
+
const { projectId, workspaceId } = scope;
|
|
154
|
+
if (projectId === void 0 && workspaceId === void 0) return;
|
|
155
|
+
const p = normalizePath(path);
|
|
156
|
+
if (UNSCOPED_EXACT.has(p) || UNSCOPED_PREFIXES.some((prefix) => p.startsWith(prefix))) {
|
|
157
|
+
throw new ScopeMisuseError(
|
|
158
|
+
`${method} ${p} is not project-scoped: never send X-Project-Id / X-Workspace-Id to it (programming error).`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (projectId !== void 0 && !/^proj_\S+$/.test(projectId)) {
|
|
162
|
+
throw new ScopeMisuseError(
|
|
163
|
+
`scope.projectId must be a full proj_\u2026 id, got '${projectId}' (programming error).`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
if (workspaceId !== void 0) {
|
|
167
|
+
if (!WORKSPACE_FILTER_PATHS.includes(p)) {
|
|
168
|
+
throw new ScopeMisuseError(
|
|
169
|
+
`X-Workspace-Id is only read by ${WORKSPACE_FILTER_PATHS.join(", ")}; ${method} ${p} would silently ignore it (programming error).`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (!/^ws_\S+$/.test(workspaceId)) {
|
|
173
|
+
throw new ScopeMisuseError(
|
|
174
|
+
`scope.workspaceId must be a full ws_\u2026 id, got '${workspaceId}' (programming error).`
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
if (projectId === void 0) {
|
|
178
|
+
throw new ScopeMisuseError(
|
|
179
|
+
"X-Workspace-Id narrows a project-scoped report and must be sent together with X-Project-Id (programming error)."
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
var SCOPE_LAYER_NOT_FOUND = /* @__PURE__ */ new Set(["project", "workspace", "transaction"]);
|
|
185
|
+
function notFoundNote(resource) {
|
|
186
|
+
if (typeof resource !== "string" || !resource) return null;
|
|
187
|
+
if (SCOPE_LAYER_NOT_FOUND.has(resource)) {
|
|
188
|
+
return "it does not exist, or it belongs to an organization or workspace your account is not a member of \u2014 the backend returns 404 for both, without distinction";
|
|
189
|
+
}
|
|
190
|
+
switch (resource) {
|
|
191
|
+
case "token":
|
|
192
|
+
return "there is no such API key in this workspace \u2014 it was deleted, or it lives in another workspace of this organization";
|
|
193
|
+
case "member":
|
|
194
|
+
return "that user is not an active member of this organization \u2014 pending invitees are addressed by their invite_id, not user_id";
|
|
195
|
+
case "api key":
|
|
196
|
+
return "one of the API keys is not in this workspace any more \u2014 it was deleted (revoked) or lives in another workspace; re-read list_keys";
|
|
197
|
+
case "access policy":
|
|
198
|
+
return "there is no such access policy in this workspace \u2014 it was deleted, or it belongs to another workspace; re-read list_access_policies";
|
|
199
|
+
case "invite":
|
|
200
|
+
return "there is no such invitation in this organization \u2014 re-read the member list for the current invite_id (re-sending an invitation issues a new one)";
|
|
201
|
+
default:
|
|
202
|
+
return `there is no such ${resource} in this organization`;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
var MAX_USER_AGENT = 255;
|
|
206
|
+
var MAX_REQUEST_ID = 64;
|
|
207
|
+
function clientIdentityHeaders(identity) {
|
|
208
|
+
const headers = {};
|
|
209
|
+
if (!identity) return headers;
|
|
210
|
+
if (identity.forwardedFor) headers["x-forwarded-for"] = identity.forwardedFor;
|
|
211
|
+
if (identity.userAgent) headers["user-agent"] = identity.userAgent.slice(0, MAX_USER_AGENT);
|
|
212
|
+
if (identity.requestId) headers["x-request-id"] = identity.requestId.slice(0, MAX_REQUEST_ID);
|
|
213
|
+
return headers;
|
|
214
|
+
}
|
|
215
|
+
var DEFAULT_TIMEOUT_MS = 6e4;
|
|
216
|
+
function buildQueryString(query) {
|
|
217
|
+
if (!query) return "";
|
|
218
|
+
const sp = new URLSearchParams();
|
|
219
|
+
for (const [key, value] of Object.entries(query)) {
|
|
220
|
+
if (value === null || value === void 0) continue;
|
|
221
|
+
if (Array.isArray(value)) {
|
|
222
|
+
for (const v of value) sp.append(key, String(v));
|
|
223
|
+
} else {
|
|
224
|
+
sp.append(key, String(value));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const s = sp.toString();
|
|
228
|
+
return s ? `?${s}` : "";
|
|
229
|
+
}
|
|
230
|
+
var BackendClient = class {
|
|
231
|
+
baseUrl;
|
|
232
|
+
credentials;
|
|
233
|
+
fetchImpl;
|
|
234
|
+
timeoutMs;
|
|
235
|
+
identityHeaders;
|
|
236
|
+
constructor(options) {
|
|
237
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
238
|
+
this.credentials = options.credentials;
|
|
239
|
+
this.identityHeaders = clientIdentityHeaders(options.clientIdentity);
|
|
240
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
241
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
242
|
+
}
|
|
243
|
+
async get(path, options) {
|
|
244
|
+
return this.request("GET", path, options);
|
|
245
|
+
}
|
|
246
|
+
async post(path, options) {
|
|
247
|
+
return this.request("POST", path, options);
|
|
248
|
+
}
|
|
249
|
+
async put(path, options) {
|
|
250
|
+
return this.request("PUT", path, options);
|
|
251
|
+
}
|
|
252
|
+
async patch(path, options) {
|
|
253
|
+
return this.request("PATCH", path, options);
|
|
254
|
+
}
|
|
255
|
+
async delete(path, options) {
|
|
256
|
+
return this.request("DELETE", path, options);
|
|
257
|
+
}
|
|
258
|
+
async request(method, path, options) {
|
|
259
|
+
assertScope(method, path, options?.scope);
|
|
260
|
+
const auth = options?.auth ?? true;
|
|
261
|
+
let token = null;
|
|
262
|
+
if (auth) {
|
|
263
|
+
token = await this.credentials.getAccessToken();
|
|
264
|
+
if (token === null) {
|
|
265
|
+
throw new ApiError(
|
|
266
|
+
401,
|
|
267
|
+
"no_credentials",
|
|
268
|
+
"Not signed in: no credentials available.",
|
|
269
|
+
this.credentials.reauthHint()
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
let response = await this.send(method, path, options, token);
|
|
274
|
+
if (auth && response.status === 401) {
|
|
275
|
+
const fresh = await this.credentials.forceRefresh();
|
|
276
|
+
if (fresh !== null) {
|
|
277
|
+
response = await this.send(method, path, options, fresh);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return this.finalize(response, path, auth);
|
|
281
|
+
}
|
|
282
|
+
async send(method, path, options, token) {
|
|
283
|
+
const url = `${this.baseUrl}${path}${buildQueryString(options?.query)}`;
|
|
284
|
+
const headers = { ...this.identityHeaders, accept: "application/json" };
|
|
285
|
+
if (token !== null) headers.authorization = `Bearer ${token}`;
|
|
286
|
+
if (options?.scope?.projectId !== void 0) headers[PROJECT_HEADER] = options.scope.projectId;
|
|
287
|
+
if (options?.scope?.workspaceId !== void 0) headers[WORKSPACE_HEADER] = options.scope.workspaceId;
|
|
288
|
+
const init = {
|
|
289
|
+
method,
|
|
290
|
+
headers,
|
|
291
|
+
// 规约 ③:每请求超时(裸 fetch 默认是 undici 的 300s,太长)
|
|
292
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
293
|
+
};
|
|
294
|
+
if (options?.body !== void 0) {
|
|
295
|
+
headers["content-type"] = "application/json";
|
|
296
|
+
init.body = JSON.stringify(options.body);
|
|
297
|
+
}
|
|
298
|
+
try {
|
|
299
|
+
return await this.fetchImpl(url, init);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
302
|
+
throw new ApiError(0, "timeout", `Request timed out after ${this.timeoutMs}ms: ${method} ${path}`);
|
|
303
|
+
}
|
|
304
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
305
|
+
throw new ApiError(0, "network_error", `Network error: ${method} ${path} (${detail})`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async finalize(response, path, auth) {
|
|
309
|
+
if (response.ok) {
|
|
310
|
+
if (response.status === 204) return void 0;
|
|
311
|
+
return await response.json();
|
|
312
|
+
}
|
|
313
|
+
const bodyText = await response.text().catch(() => "");
|
|
314
|
+
const parsed = parseErrorBody(response.status, bodyText);
|
|
315
|
+
let message = parsed.message;
|
|
316
|
+
const hint = response.status === 401 && auth ? this.credentials.reauthHint() : void 0;
|
|
317
|
+
if (path.includes("/supplier/") || path.startsWith("/supplier")) {
|
|
318
|
+
if (response.status === 403) {
|
|
319
|
+
message = "Supplier features are invite-only: this account does not have supplier access yet (is_supplier is set by the platform admin and cannot be self-enabled). Contact the platform to list models.";
|
|
320
|
+
} else if (response.status === 404) {
|
|
321
|
+
message = `${message} (the resource does not exist, or is not owned by your account \u2014 the backend returns 404 for both, without distinction)`;
|
|
322
|
+
}
|
|
323
|
+
} else if (parsed.code === "not_found") {
|
|
324
|
+
const note = notFoundNote(parsed.details?.resource);
|
|
325
|
+
if (note) message = `${message} (${note})`;
|
|
326
|
+
}
|
|
327
|
+
throw new ApiError(response.status, parsed.code, message, hint, parsed.details);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
// src/shared/log.ts
|
|
332
|
+
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
333
|
+
function currentLevel() {
|
|
334
|
+
const raw = process.env.LUNE_MCP_LOG_LEVEL;
|
|
335
|
+
return raw === "debug" || raw === "info" || raw === "warn" || raw === "error" ? raw : "info";
|
|
336
|
+
}
|
|
337
|
+
var instance;
|
|
338
|
+
function write(level, args) {
|
|
339
|
+
if (WEIGHT[level] < WEIGHT[currentLevel()]) return;
|
|
340
|
+
const inst = instance ? ` inst=${instance}` : "";
|
|
341
|
+
console.error(`[lune-mcp] ${(/* @__PURE__ */ new Date()).toISOString()} ${level}${inst}:`, ...args);
|
|
342
|
+
}
|
|
343
|
+
function formatFields(fields) {
|
|
344
|
+
const parts = [];
|
|
345
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
346
|
+
if (value === void 0 || value === null) continue;
|
|
347
|
+
const raw = String(value);
|
|
348
|
+
parts.push(`${key}=${/[\s"=]/.test(raw) ? JSON.stringify(raw) : raw}`);
|
|
349
|
+
}
|
|
350
|
+
return parts.join(" ");
|
|
351
|
+
}
|
|
352
|
+
var log = {
|
|
353
|
+
debug: (...args) => write("debug", args),
|
|
354
|
+
info: (...args) => write("info", args),
|
|
355
|
+
warn: (...args) => write("warn", args),
|
|
356
|
+
error: (...args) => write("error", args),
|
|
357
|
+
/** 结构化事件行:`event=<name> k=v …`(字段顺序 = 传入顺序,便于肉眼扫)。 */
|
|
358
|
+
event: (level, name, fields = {}) => write(level, [formatFields({ event: name, ...fields })])
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
export {
|
|
362
|
+
ApiError,
|
|
363
|
+
ScopeMisuseError,
|
|
364
|
+
isScopeProgrammingError,
|
|
365
|
+
BackendClient,
|
|
366
|
+
log
|
|
367
|
+
};
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_REMOTE_URL
|
|
4
|
+
} from "./chunk-PQYX44KQ.js";
|
|
5
|
+
import {
|
|
6
|
+
BRAND_NAME,
|
|
7
|
+
VERSION
|
|
8
|
+
} from "./chunk-NN23AOUC.js";
|
|
9
|
+
|
|
10
|
+
// src/cli/main.ts
|
|
11
|
+
import { Command } from "commander";
|
|
12
|
+
var program = new Command();
|
|
13
|
+
program.name("lune-mcp").description(
|
|
14
|
+
`The ${BRAND_NAME} CLI (lune-mcp): MCP server and companion commands for the ${BRAND_NAME} platform`
|
|
15
|
+
).version(VERSION, "-v, --version");
|
|
16
|
+
program.command("mcp").description("Start the MCP server over stdio").action(async () => {
|
|
17
|
+
const { runStdio } = await import("./main-QRRGC4CK.js");
|
|
18
|
+
await runStdio();
|
|
19
|
+
});
|
|
20
|
+
program.command("login").description("OAuth sign-in; only needed for stdio mode").option("--no-browser", "do not open a browser; print the authorization URL only (for SSH sessions)").action(async (options) => {
|
|
21
|
+
const { loginCommand } = await import("./login-3X77QT2S.js");
|
|
22
|
+
process.exit(await loginCommand({ noBrowser: options.browser === false }));
|
|
23
|
+
});
|
|
24
|
+
program.command("logout").description("Revoke and clear local credentials; stdio mode only").action(async () => {
|
|
25
|
+
const { logoutCommand } = await import("./logout-Q64WE4R4.js");
|
|
26
|
+
process.exit(await logoutCommand());
|
|
27
|
+
});
|
|
28
|
+
program.command("install").description(`Write ${BRAND_NAME} config for MCP clients; the last install wins`).argument(
|
|
29
|
+
"[clients...]",
|
|
30
|
+
"client ids, one or more (claude-code / vscode / codex / gemini / cursor / claude-desktop)"
|
|
31
|
+
).option("--all", "detect all installed clients and write each one").option(
|
|
32
|
+
"--stdio",
|
|
33
|
+
"install the local stdio mode instead (launches this package via npx; requires a separate login)"
|
|
34
|
+
).option(
|
|
35
|
+
"--url <url>",
|
|
36
|
+
`override the remote service URL (default ${DEFAULT_REMOTE_URL}; for test environments)`
|
|
37
|
+
).option(
|
|
38
|
+
"--scope <scope>",
|
|
39
|
+
"where to write: user (global) or project (current directory); prompts interactively if omitted"
|
|
40
|
+
).action(
|
|
41
|
+
async (clients, options) => {
|
|
42
|
+
const { installCommand } = await import("./install-F4IVDNAW.js");
|
|
43
|
+
process.exit(
|
|
44
|
+
await installCommand(clients, {
|
|
45
|
+
all: options.all === true,
|
|
46
|
+
stdio: options.stdio === true,
|
|
47
|
+
url: options.url,
|
|
48
|
+
scope: options.scope
|
|
49
|
+
})
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
);
|
|
53
|
+
program.command("doctor").description("Ten self-checks, grouped by usage mode").action(async () => {
|
|
54
|
+
const { doctorCommand } = await import("./doctor-WZJF4O2Y.js");
|
|
55
|
+
process.exit(await doctorCommand());
|
|
56
|
+
});
|
|
57
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
58
|
+
process.stderr.write(`${err instanceof Error ? err.stack ?? err.message : String(err)}
|
|
59
|
+
`);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
});
|