@zenlayer/lune-mcp 0.0.0-stage → 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 +253 -2
- package/dist/chunk-2UUMFH2N.js +357 -0
- package/dist/chunk-3OSHCYWX.js +97 -0
- package/dist/chunk-4UMZU6R2.js +11 -0
- package/dist/chunk-6CLUCGIJ.js +125 -0
- package/dist/chunk-JFOGRJQA.js +289 -0
- package/dist/chunk-MC3S3YL6.js +11 -0
- package/dist/chunk-NBO4ZVRK.js +403 -0
- package/dist/chunk-PQYX44KQ.js +28 -0
- package/dist/chunk-QASEPHOI.js +158 -0
- package/dist/cli.js +61 -0
- package/dist/doctor-M5AXEIYG.js +371 -0
- package/dist/index.js +10243 -0
- package/dist/install-7XAHE2K6.js +277 -0
- package/dist/login-FNMGXSJT.js +54 -0
- package/dist/logout-4ICTJPUQ.js +36 -0
- package/dist/main-47XGXIDD.js +9180 -0
- package/dist/oauth-login-47OUBG5B.js +23 -0
- package/dist/remote.js +10150 -0
- package/package.json +66 -4
package/README.md
CHANGED
|
@@ -1,3 +1,254 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zenlayer/lune-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP server for the Lune.io platform. It lets Claude, Cursor, and other AI
|
|
4
|
+
clients operate your Lune.io account directly: check model pricing, manage API keys, review
|
|
5
|
+
usage, credits and billing, set budgets, and run your organizations — workspaces, members
|
|
6
|
+
and invitations — and, for suppliers, manage listings and payouts.
|
|
7
|
+
|
|
8
|
+
> **Coming from `@zenlayer/tkex-mcp`?** The package, connector name, environment variables and
|
|
9
|
+
> server address all changed — see [Moving from @zenlayer/tkex-mcp](#moving-from-zenlayertkex-mcp).
|
|
10
|
+
> If you were on `@zenlayer/tkex-mcp` 1.0.2 or earlier, also read
|
|
11
|
+
> [Tool changes since tkex-mcp 1.0.2](#tool-changes-since-tkex-mcp-102).
|
|
12
|
+
|
|
13
|
+
## What you can do
|
|
14
|
+
|
|
15
|
+
Once connected, just ask your AI client:
|
|
16
|
+
|
|
17
|
+
- "What does DeepSeek V4 cost per million tokens on Lune.io?"
|
|
18
|
+
- "Create an API key in the Production workspace that can only call qwen3.7-plus, capped at $50."
|
|
19
|
+
- "How much did the Production workspace spend this week, and did any requests fail?"
|
|
20
|
+
- "Cap the Staging workspace at $200 a month."
|
|
21
|
+
- "Invite alice@example.com to Acme as a member."
|
|
22
|
+
- "Which workspace in Acme spent the most this month?"
|
|
23
|
+
- Suppliers: "Show this week's net earnings — any failed payouts?"
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
Two transports; pick either one. Both can be configured automatically with a single CLI
|
|
28
|
+
command, or by hand.
|
|
29
|
+
|
|
30
|
+
### a. Remote (recommended)
|
|
31
|
+
|
|
32
|
+
The service runs at `https://www.lune.io/mcp` (Streamable HTTP). Nothing runs on your
|
|
33
|
+
machine — the first tool call opens a browser sign-in to authorize your Lune.io account.
|
|
34
|
+
|
|
35
|
+
**Automatic:**
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx @zenlayer/lune-mcp install
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**Manual:**
|
|
42
|
+
|
|
43
|
+
- **Claude Code**: `claude mcp add --transport http lune-io https://www.lune.io/mcp`
|
|
44
|
+
- **claude.ai / Claude Desktop**: Settings → Connectors → Add custom connector, Name `Lune.io`, URL `https://www.lune.io/mcp`
|
|
45
|
+
- **Cursor**: add `"lune-io": { "url": "https://www.lune.io/mcp" }` under `mcpServers` in `~/.cursor/mcp.json`
|
|
46
|
+
- **VS Code**: `code --add-mcp '{"name":"lune-io","type":"http","url":"https://www.lune.io/mcp"}'`
|
|
47
|
+
- **Codex CLI**: `codex mcp add lune-io --url https://www.lune.io/mcp`
|
|
48
|
+
- **Gemini CLI**: `gemini mcp add -t http lune-io https://www.lune.io/mcp`
|
|
49
|
+
|
|
50
|
+
### b. Local stdio
|
|
51
|
+
|
|
52
|
+
The MCP server runs on your machine via npx — for environments that cannot reach the
|
|
53
|
+
remote endpoint directly.
|
|
54
|
+
|
|
55
|
+
**Automatic:**
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npx @zenlayer/lune-mcp install --stdio
|
|
59
|
+
npx @zenlayer/lune-mcp login
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**Manual:**
|
|
63
|
+
|
|
64
|
+
- **Claude Code**: `claude mcp add lune-io -- npx -y @zenlayer/lune-mcp@1 mcp`
|
|
65
|
+
- **Codex CLI**: `codex mcp add lune-io -- npx -y @zenlayer/lune-mcp@1 mcp`
|
|
66
|
+
- **Gemini CLI**: `gemini mcp add lune-io npx -y @zenlayer/lune-mcp@1 mcp`
|
|
67
|
+
- **VS Code**: `code --add-mcp '{"name":"lune-io","command":"npx","args":["-y","@zenlayer/lune-mcp@1","mcp"]}'`
|
|
68
|
+
- **Cursor**: add
|
|
69
|
+
`"lune-io": { "command": "npx", "args": ["-y", "@zenlayer/lune-mcp@1", "mcp"] }`
|
|
70
|
+
under `mcpServers` in `~/.cursor/mcp.json`
|
|
71
|
+
- **Claude Desktop**: add the same entry as Cursor under `mcpServers` in
|
|
72
|
+
`claude_desktop_config.json` (macOS `~/Library/Application Support/Claude/`,
|
|
73
|
+
Windows `%APPDATA%\Claude\`)
|
|
74
|
+
|
|
75
|
+
On Windows, write the launch command as `cmd /c npx -y @zenlayer/lune-mcp@1 mcp`.
|
|
76
|
+
|
|
77
|
+
## Sign-in and authorization
|
|
78
|
+
|
|
79
|
+
- Both transports authorize through browser OAuth against your Lune.io account — **no tokens
|
|
80
|
+
to copy and paste**.
|
|
81
|
+
- The remote transport asks for up to five permissions: `buyer:read`, `buyer:write` and
|
|
82
|
+
`buyer:admin` (members and invitations, workspaces, organization settings, creating
|
|
83
|
+
organizations), plus
|
|
84
|
+
`supplier:read` / `supplier:write` for supplier accounts. It only shows the tools your
|
|
85
|
+
connection was granted.
|
|
86
|
+
|
|
87
|
+
## Tools (46)
|
|
88
|
+
|
|
89
|
+
Tools marked ✏️ are write operations; every one goes through two-step confirmation (see below).
|
|
90
|
+
|
|
91
|
+
### Public (2)
|
|
92
|
+
|
|
93
|
+
| Tool | What it does |
|
|
94
|
+
|---|---|
|
|
95
|
+
| `list_public_models` | Model catalog and public pricing |
|
|
96
|
+
| `search_docs` | Official platform documentation |
|
|
97
|
+
|
|
98
|
+
### Lune.io Console (27)
|
|
99
|
+
|
|
100
|
+
Every buyer tool works in one of your contexts — your personal space or an organization you
|
|
101
|
+
belong to — and, where it applies, one of its workspaces. Name them with `project_id` /
|
|
102
|
+
`workspace_id` (an id, a Lune.io Console URL, or an exact name); with only one, it is picked
|
|
103
|
+
automatically, and with several the tool lists the choices instead of guessing. Each result
|
|
104
|
+
says which organization and workspace it covers. What you can do follows your role: an
|
|
105
|
+
organization member asking for an admin-only action gets a plain "only admins can…" answer,
|
|
106
|
+
not an error.
|
|
107
|
+
|
|
108
|
+
| Tool | What it does |
|
|
109
|
+
|---|---|
|
|
110
|
+
| `get_account` | Your profile, every context you belong to with your role and permissions, organizations you can still create |
|
|
111
|
+
| `list_workspaces` | Workspaces in a context, with API key counts, budgets and this month's spend |
|
|
112
|
+
| `get_org_settings` / `update_org_settings` ✏️ | Name, icon and minimum data policy of an organization or your personal space |
|
|
113
|
+
| `create_workspace` ✏️ / `update_workspace` ✏️ / `delete_workspace` ✏️ | Workspace management |
|
|
114
|
+
| `list_keys` / `create_key` ✏️ / `update_key` ✏️ / `delete_key` ✏️ | API keys in a workspace |
|
|
115
|
+
| `list_available_models` | Models callable in a context (the ids `allowed_models` accepts) |
|
|
116
|
+
| `get_usage` / `get_logs` | Usage totals and request-level logs for a workspace |
|
|
117
|
+
| `get_credits` | Balance, lifetime top-ups and spend, estimated runway, auto top-up settings |
|
|
118
|
+
| `get_billing` | Transactions (top-ups, refunds, promos) and monthly statements |
|
|
119
|
+
| `set_auto_topup` ✏️ | Turn auto top-up on or off, change its threshold and amount |
|
|
120
|
+
| `list_budgets` / `set_budget` ✏️ | Daily / weekly / monthly budgets on workspaces and members |
|
|
121
|
+
| `get_analytics` | This month's organization spend by workspace and by member (admins) |
|
|
122
|
+
| `list_members` / `invite_members` ✏️ / `revoke_invite` ✏️ / `update_member_role` ✏️ / `remove_member` ✏️ | Members and invitations (admins) |
|
|
123
|
+
| `leave_organization` ✏️ | Leave an organization |
|
|
124
|
+
| `create_organization` ✏️ | Create an organization (organizations can't be deleted) |
|
|
125
|
+
|
|
126
|
+
Top-ups, refunds and accepting invitations are deliberately not available as tools — use
|
|
127
|
+
the Lune.io Console for those.
|
|
128
|
+
|
|
129
|
+
### Supplier (17, supplier accounts only)
|
|
130
|
+
|
|
131
|
+
| Tool | What it does |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `supplier_overview` | Supply overview |
|
|
134
|
+
| `list_providers` / `create_provider` ✏️ / `update_provider` ✏️ | Supplier endpoint management |
|
|
135
|
+
| `list_provider_keys` / `add_provider_key` ✏️ / `delete_provider_key` ✏️ | Upstream key management |
|
|
136
|
+
| `list_listings` / `create_listing` ✏️ / `update_listing` ✏️ / `delete_listing` ✏️ | Listing management |
|
|
137
|
+
| `list_model_catalog` | Canonical model catalog |
|
|
138
|
+
| `list_upstream_models` | Upstream models synced for a supplier |
|
|
139
|
+
| `supplier_usage` / `supplier_logs` | Usage and logs hitting your models |
|
|
140
|
+
| `supplier_earnings` / `list_payouts` | Earnings and payout history |
|
|
141
|
+
|
|
142
|
+
### Write operations = two-step confirmation
|
|
143
|
+
|
|
144
|
+
The first call to any ✏️ tool returns only a **plan summary** (what will happen, what it
|
|
145
|
+
affects) without executing. After you confirm, the agent calls the tool again with the
|
|
146
|
+
returned planId — only then does it execute.
|
|
147
|
+
|
|
148
|
+
## CLI commands
|
|
149
|
+
|
|
150
|
+
This is the Lune.io CLI (`lune-mcp`).
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
npx @zenlayer/lune-mcp <command>
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
| Command | What it does |
|
|
157
|
+
|---|---|
|
|
158
|
+
| `mcp` | Starts the MCP server over stdio (written into client configs; rarely typed by hand) |
|
|
159
|
+
| `login [--no-browser]` | OAuth sign-in, **stdio only** (the remote transport is authorized by your MCP client automatically — this command is not needed there); `--no-browser` prints the authorization URL instead of opening a browser (SSH sessions) |
|
|
160
|
+
| `logout` | Revokes and clears local credentials (**stdio only**; for remote, disconnect in your MCP client) |
|
|
161
|
+
| `install [clients...] [--all] [--stdio] [--url <url>] [--scope user\|project]` | Writes the Lune.io server entry (named `lune-io`) into client MCP configs: remote by default, `--stdio` for local, `--url` overrides the remote URL; prompts interactively when clients or scope are not specified. **Re-running install keeps only the last configuration**: before writing, stale `lune-io` entries in the client's other scopes and transports are removed (switching stdio↔remote or user↔project leaves no shadow config) |
|
|
162
|
+
| `doctor` | Ten self-checks grouped by transport (common / remote service / stdio credential chain), including whether the backend you point at is organization-enabled; each with a suggested fix |
|
|
163
|
+
|
|
164
|
+
## Environment variables
|
|
165
|
+
|
|
166
|
+
Both apply to the local stdio transport and the CLI.
|
|
167
|
+
|
|
168
|
+
| Variable | Effect |
|
|
169
|
+
|---|---|
|
|
170
|
+
| `LUNE_MCP_ALLOW_FILE_CREDENTIALS=1` | Fallback for machines without a usable system keychain (e.g. headless Linux without Secret Service). `login` then stores the refresh token in **plaintext** at `~/.lune-mcp/credentials.json` (mode 0600): anyone who can read that file can act as your account. Ignored while the keychain works; `logout` when you are done |
|
|
171
|
+
| `LUNE_MCP_LOG_LEVEL` | `debug` \| `info` \| `warn` \| `error` (default `info`; any other value means `info`). Logs go to stderr |
|
|
172
|
+
|
|
173
|
+
## Security notes
|
|
174
|
+
|
|
175
|
+
- The plaintext API key returned by `create_key` **appears in your AI client's conversation
|
|
176
|
+
history**. Treat that conversation like a password; `delete_key` any key you no longer need.
|
|
177
|
+
- Write operations are gated by two-step confirmation, but keeping manual approval for
|
|
178
|
+
write tools in your MCP client is still a good habit.
|
|
179
|
+
- To revoke credentials: `logout`, or change your password in the Lune.io Console (this
|
|
180
|
+
immediately invalidates every credential issued to the account).
|
|
181
|
+
|
|
182
|
+
## Moving from @zenlayer/tkex-mcp
|
|
183
|
+
|
|
184
|
+
The package is now `@zenlayer/lune-mcp` (versions continue from the old package), and the
|
|
185
|
+
service moved to `www.lune.io`. Nothing from the old setup is migrated or recognized, so redo
|
|
186
|
+
the setup once:
|
|
187
|
+
|
|
188
|
+
1. **Reinstall**: `npx @zenlayer/lune-mcp install` (add `--stdio` for the local transport).
|
|
189
|
+
It writes a connector named `lune-io`; tools show up as `mcp__lune-io__*` in Claude Code.
|
|
190
|
+
2. **Sign in again**: `npx @zenlayer/lune-mcp login` (stdio only). Credentials saved by the
|
|
191
|
+
old package (system keychain entry `tkex-mcp`, `~/.tkex`) are not read. Delete the old
|
|
192
|
+
keychain entry `tkex-mcp` and the `~/.tkex` directory (it may hold a plaintext refresh
|
|
193
|
+
token). To invalidate old credentials right away, change your password.
|
|
194
|
+
3. **Delete the old connector by hand**: `install` does not touch the `tkex` entry in your
|
|
195
|
+
client's config, so it stays behind as a dead connector next to `lune-io`.
|
|
196
|
+
Claude Code: `claude mcp remove tkex -s user` (also try `-s project` / `-s local`).
|
|
197
|
+
4. **Remote connectors**: the address changed to `https://www.lune.io/mcp`. Add it as a new
|
|
198
|
+
connector and authorize it; the old `www.tkex.ai/mcp` one will not work again.
|
|
199
|
+
5. **Environment variables**: rename them in your client config. The old names are ignored.
|
|
200
|
+
|
|
201
|
+
| Old | New |
|
|
202
|
+
|---|---|
|
|
203
|
+
| `TKEX_TOKEN` | `LUNE_MCP_TOKEN` |
|
|
204
|
+
| `TKEX_SUPPLIER` | `LUNE_MCP_SUPPLIER` |
|
|
205
|
+
| `TKEX_ALLOW_FILE_CREDENTIALS` | `LUNE_MCP_ALLOW_FILE_CREDENTIALS` |
|
|
206
|
+
| `TKEX_MCP_LOG_LEVEL` | `LUNE_MCP_LOG_LEVEL` |
|
|
207
|
+
| `TKEX_API_BASE` | `LUNE_MCP_API_BASE` |
|
|
208
|
+
| `TKEX_AS_ISSUER` | `LUNE_MCP_AS_ISSUER` |
|
|
209
|
+
| `TKEX_MCP_URL` | `LUNE_MCP_URL` |
|
|
210
|
+
| `TKEX_WEBSITE_ORIGIN` | `LUNE_MCP_WEBSITE_ORIGIN` |
|
|
211
|
+
| `TKEX_SUPPLIER_ORIGIN` | `LUNE_MCP_SUPPLIER_ORIGIN` |
|
|
212
|
+
|
|
213
|
+
Self-hosted remote deployments also rename `TKEX_ALLOWED_HOSTS`, `TKEX_ALLOWED_ORIGINS` and
|
|
214
|
+
`TKEX_MCP_INSTANCE` to `LUNE_MCP_ALLOWED_HOSTS`, `LUNE_MCP_ALLOWED_ORIGINS` and
|
|
215
|
+
`LUNE_MCP_INSTANCE`.
|
|
216
|
+
|
|
217
|
+
## Tool changes since tkex-mcp 1.0.2
|
|
218
|
+
|
|
219
|
+
`@zenlayer/tkex-mcp` 1.0.3 followed the Lune.io Console's move to **organizations and
|
|
220
|
+
workspaces**, and `@zenlayer/lune-mcp` carries those changes. If you came from 1.0.2 or
|
|
221
|
+
earlier, these break saved prompts and tool allowlists:
|
|
222
|
+
|
|
223
|
+
- **Removed and renamed tools** (no aliases): `set_spend_limit` → `set_budget` (spend limits
|
|
224
|
+
were replaced by workspace and member budgets); `get_auto_topup` → `get_credits`. Update
|
|
225
|
+
tool allowlists or saved prompts that name the old tools.
|
|
226
|
+
- **Every buyer tool is now organization- and workspace-aware**: optional `project_id` /
|
|
227
|
+
`workspace_id` inputs, a `scope` in every result, and `update_key` / `delete_key` require
|
|
228
|
+
`workspace_id`. `get_account` no longer returns the balance (use `get_credits`), and
|
|
229
|
+
`get_usage` reports one workspace for a time range instead of lifetime totals.
|
|
230
|
+
- **Paging inputs use one set of names**: page size is always `max_results`; tools that page
|
|
231
|
+
also take `offset`, set to the previous result's `next_offset` (`null` = no more pages).
|
|
232
|
+
`get_logs`, `supplier_logs` and `list_payouts` renamed `limit` to `max_results`. The old
|
|
233
|
+
name is ignored rather than rejected, so update saved prompts that pass it. `list_keys` and
|
|
234
|
+
`get_billing` are now paged (`max_results` / `offset`; billing statements use
|
|
235
|
+
`statements_max_results` / `statements_offset`). `list_public_models`,
|
|
236
|
+
`list_available_models`, `list_model_catalog`, `list_listings` and `list_upstream_models`
|
|
237
|
+
take `max_results` but no `offset`: narrow them with their filters instead of paging.
|
|
238
|
+
- **New tools**: `list_workspaces`, `get_org_settings`, `get_credits`, `list_budgets`,
|
|
239
|
+
`get_analytics`, `list_members`, and the write tools `create_workspace`,
|
|
240
|
+
`update_workspace`, `delete_workspace`, `set_budget`, `invite_members`, `revoke_invite`,
|
|
241
|
+
`update_member_role`, `remove_member`, `leave_organization`, `update_org_settings`,
|
|
242
|
+
`create_organization`.
|
|
243
|
+
|
|
244
|
+
## Requirements and troubleshooting
|
|
245
|
+
|
|
246
|
+
- The organization-enabled Lune.io backend (`doctor` check ⑩ tells you which one you are
|
|
247
|
+
talking to).
|
|
248
|
+
- Node.js >= 20 (stdio only; the remote transport has no local requirements).
|
|
249
|
+
- If something misbehaves, run `npx @zenlayer/lune-mcp doctor` first — it distinguishes
|
|
250
|
+
network, credential, and client-config problems and tells you what to do next.
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
Proprietary — © Zenlayer Inc. All rights reserved.
|
|
@@ -0,0 +1,357 @@
|
|
|
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
|
+
{
|
|
39
|
+
status: 404,
|
|
40
|
+
match: /^(project|workspace|token|transaction|member|invite|topup|refundable top-up) not found$/,
|
|
41
|
+
code: "not_found",
|
|
42
|
+
details: (m) => ({ resource: m[1] })
|
|
43
|
+
},
|
|
44
|
+
// 退款(user.py _refund_topup)—— C8 不提供退款工具,映射保留给 get_billing 解释 refundable
|
|
45
|
+
{ status: 403, match: "refund window expired", code: "refund_window_expired" },
|
|
46
|
+
{ status: 409, match: "topup is not refundable", code: "topup_not_refundable" },
|
|
47
|
+
{ status: 400, match: "only card top-ups can be refunded", code: "refund_card_only" },
|
|
48
|
+
{ status: 400, match: "no payment to refund", code: "refund_no_payment" },
|
|
49
|
+
{ status: 409, match: "no unconsumed credits to refund", code: "refund_nothing_unconsumed" },
|
|
50
|
+
{ status: 409, match: "balance changed, please retry refund", code: "refund_balance_changed" },
|
|
51
|
+
// auto top-up(user.py update_auto_topup)
|
|
52
|
+
{ status: 400, match: "add a card first (no saved payment method)", code: "no_saved_card" },
|
|
53
|
+
{
|
|
54
|
+
status: 400,
|
|
55
|
+
match: "threshold_usd and amount_usd are required when enabling",
|
|
56
|
+
code: "auto_topup_fields_required"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
status: 400,
|
|
60
|
+
match: /^amount_usd exceeds the \$(\d+(?:\.\d+)?) per-charge limit$/,
|
|
61
|
+
code: "amount_over_charge_limit",
|
|
62
|
+
details: (m) => ({ limit_usd: Number(m[1]) })
|
|
63
|
+
},
|
|
64
|
+
// 杂项
|
|
65
|
+
{ status: 409, match: "project wallet not provisioned", code: "wallet_not_provisioned" },
|
|
66
|
+
{ status: 400, match: "invalid type filter", code: "invalid_type_filter" }
|
|
67
|
+
];
|
|
68
|
+
function mapStringDetail(status, detail) {
|
|
69
|
+
const text = detail.trim();
|
|
70
|
+
for (const rule of STRING_DETAIL_RULES) {
|
|
71
|
+
if (rule.status !== status) continue;
|
|
72
|
+
if (typeof rule.match === "string") {
|
|
73
|
+
if (text === rule.match) return { code: rule.code, message: detail };
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const m = text.match(rule.match);
|
|
77
|
+
if (m) {
|
|
78
|
+
const details = rule.details?.(m);
|
|
79
|
+
return details ? { code: rule.code, message: detail, details } : { code: rule.code, message: detail };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return { code: `http_${status}`, message: detail };
|
|
83
|
+
}
|
|
84
|
+
function parseErrorBody(status, body) {
|
|
85
|
+
const fallbackCode = `http_${status}`;
|
|
86
|
+
let data;
|
|
87
|
+
try {
|
|
88
|
+
data = JSON.parse(body);
|
|
89
|
+
} catch {
|
|
90
|
+
const text = body.trim().slice(0, 300);
|
|
91
|
+
return { code: fallbackCode, message: text || `HTTP ${status}` };
|
|
92
|
+
}
|
|
93
|
+
if (typeof data !== "object" || data === null) {
|
|
94
|
+
const text = String(data).trim();
|
|
95
|
+
return { code: fallbackCode, message: text || `HTTP ${status}` };
|
|
96
|
+
}
|
|
97
|
+
const obj = data;
|
|
98
|
+
const detail = obj.detail;
|
|
99
|
+
if (typeof detail === "object" && detail !== null && !Array.isArray(detail)) {
|
|
100
|
+
const err = detail.error;
|
|
101
|
+
if (typeof err === "object" && err !== null) {
|
|
102
|
+
const e = err;
|
|
103
|
+
const message = typeof e.message === "string" ? e.message : JSON.stringify(err);
|
|
104
|
+
const code = typeof e.code === "string" ? e.code : typeof e.type === "string" ? e.type : fallbackCode;
|
|
105
|
+
const details = {};
|
|
106
|
+
for (const [k, v] of Object.entries(e)) {
|
|
107
|
+
if (!ENVELOPE_CORE_KEYS.has(k)) details[k] = v;
|
|
108
|
+
}
|
|
109
|
+
return Object.keys(details).length > 0 ? { code, message, details } : { code, message };
|
|
110
|
+
}
|
|
111
|
+
return { code: fallbackCode, message: JSON.stringify(detail) };
|
|
112
|
+
}
|
|
113
|
+
if (typeof detail === "string") return mapStringDetail(status, detail);
|
|
114
|
+
if (Array.isArray(detail)) {
|
|
115
|
+
const parts = detail.map((item) => {
|
|
116
|
+
if (typeof item === "object" && item !== null) {
|
|
117
|
+
const it = item;
|
|
118
|
+
const loc = Array.isArray(it.loc) ? it.loc.join(".") : "";
|
|
119
|
+
const msg = typeof it.msg === "string" ? it.msg : JSON.stringify(item);
|
|
120
|
+
return loc ? `${loc}: ${msg}` : msg;
|
|
121
|
+
}
|
|
122
|
+
return String(item);
|
|
123
|
+
});
|
|
124
|
+
return { code: "validation_error", message: parts.join("; ") };
|
|
125
|
+
}
|
|
126
|
+
if (typeof obj.message === "string") return { code: fallbackCode, message: obj.message };
|
|
127
|
+
if (typeof obj.error === "string") return { code: fallbackCode, message: obj.error };
|
|
128
|
+
return { code: fallbackCode, message: body.slice(0, 300) || `HTTP ${status}` };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/core/backend/client.ts
|
|
132
|
+
var PROJECT_HEADER = "x-project-id";
|
|
133
|
+
var WORKSPACE_HEADER = "x-workspace-id";
|
|
134
|
+
var WORKSPACE_FILTER_PATHS = [
|
|
135
|
+
"/v1/user/self/usage",
|
|
136
|
+
"/v1/user/self/usage/summary",
|
|
137
|
+
"/v1/user/self/logs"
|
|
138
|
+
];
|
|
139
|
+
var UNSCOPED_PREFIXES = ["/v1/auth/", "/v1/public/", "/supplier/", "/v1/invites/"];
|
|
140
|
+
var UNSCOPED_EXACT = /* @__PURE__ */ new Set(["/v1/auth", "/v1/public", "/supplier", "/v1/projects", "/v1/invites"]);
|
|
141
|
+
function normalizePath(path) {
|
|
142
|
+
const bare = path.split("?")[0] ?? path;
|
|
143
|
+
return bare.length > 1 ? bare.replace(/\/+$/, "") : bare;
|
|
144
|
+
}
|
|
145
|
+
function assertScope(method, path, scope) {
|
|
146
|
+
if (!scope) return;
|
|
147
|
+
const { projectId, workspaceId } = scope;
|
|
148
|
+
if (projectId === void 0 && workspaceId === void 0) return;
|
|
149
|
+
const p = normalizePath(path);
|
|
150
|
+
if (UNSCOPED_EXACT.has(p) || UNSCOPED_PREFIXES.some((prefix) => p.startsWith(prefix))) {
|
|
151
|
+
throw new ScopeMisuseError(
|
|
152
|
+
`${method} ${p} is not project-scoped: never send X-Project-Id / X-Workspace-Id to it (programming error).`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (projectId !== void 0 && !/^proj_\S+$/.test(projectId)) {
|
|
156
|
+
throw new ScopeMisuseError(
|
|
157
|
+
`scope.projectId must be a full proj_\u2026 id, got '${projectId}' (programming error).`
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
if (workspaceId !== void 0) {
|
|
161
|
+
if (!WORKSPACE_FILTER_PATHS.includes(p)) {
|
|
162
|
+
throw new ScopeMisuseError(
|
|
163
|
+
`X-Workspace-Id is only read by ${WORKSPACE_FILTER_PATHS.join(", ")}; ${method} ${p} would silently ignore it (programming error).`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
if (!/^ws_\S+$/.test(workspaceId)) {
|
|
167
|
+
throw new ScopeMisuseError(
|
|
168
|
+
`scope.workspaceId must be a full ws_\u2026 id, got '${workspaceId}' (programming error).`
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
if (projectId === void 0) {
|
|
172
|
+
throw new ScopeMisuseError(
|
|
173
|
+
"X-Workspace-Id narrows a project-scoped report and must be sent together with X-Project-Id (programming error)."
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
var SCOPE_LAYER_NOT_FOUND = /* @__PURE__ */ new Set(["project", "workspace", "transaction"]);
|
|
179
|
+
function notFoundNote(resource) {
|
|
180
|
+
if (typeof resource !== "string" || !resource) return null;
|
|
181
|
+
if (SCOPE_LAYER_NOT_FOUND.has(resource)) {
|
|
182
|
+
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";
|
|
183
|
+
}
|
|
184
|
+
switch (resource) {
|
|
185
|
+
case "token":
|
|
186
|
+
return "there is no such API key in this workspace \u2014 it was deleted, or it lives in another workspace of this organization";
|
|
187
|
+
case "member":
|
|
188
|
+
return "that user is not an active member of this organization \u2014 pending invitees are addressed by their invite_id, not user_id";
|
|
189
|
+
case "invite":
|
|
190
|
+
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)";
|
|
191
|
+
default:
|
|
192
|
+
return `there is no such ${resource} in this organization`;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
var MAX_USER_AGENT = 255;
|
|
196
|
+
var MAX_REQUEST_ID = 64;
|
|
197
|
+
function clientIdentityHeaders(identity) {
|
|
198
|
+
const headers = {};
|
|
199
|
+
if (!identity) return headers;
|
|
200
|
+
if (identity.forwardedFor) headers["x-forwarded-for"] = identity.forwardedFor;
|
|
201
|
+
if (identity.userAgent) headers["user-agent"] = identity.userAgent.slice(0, MAX_USER_AGENT);
|
|
202
|
+
if (identity.requestId) headers["x-request-id"] = identity.requestId.slice(0, MAX_REQUEST_ID);
|
|
203
|
+
return headers;
|
|
204
|
+
}
|
|
205
|
+
var DEFAULT_TIMEOUT_MS = 6e4;
|
|
206
|
+
function buildQueryString(query) {
|
|
207
|
+
if (!query) return "";
|
|
208
|
+
const sp = new URLSearchParams();
|
|
209
|
+
for (const [key, value] of Object.entries(query)) {
|
|
210
|
+
if (value === null || value === void 0) continue;
|
|
211
|
+
if (Array.isArray(value)) {
|
|
212
|
+
for (const v of value) sp.append(key, String(v));
|
|
213
|
+
} else {
|
|
214
|
+
sp.append(key, String(value));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const s = sp.toString();
|
|
218
|
+
return s ? `?${s}` : "";
|
|
219
|
+
}
|
|
220
|
+
var BackendClient = class {
|
|
221
|
+
baseUrl;
|
|
222
|
+
credentials;
|
|
223
|
+
fetchImpl;
|
|
224
|
+
timeoutMs;
|
|
225
|
+
identityHeaders;
|
|
226
|
+
constructor(options) {
|
|
227
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
228
|
+
this.credentials = options.credentials;
|
|
229
|
+
this.identityHeaders = clientIdentityHeaders(options.clientIdentity);
|
|
230
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
231
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
232
|
+
}
|
|
233
|
+
async get(path, options) {
|
|
234
|
+
return this.request("GET", path, options);
|
|
235
|
+
}
|
|
236
|
+
async post(path, options) {
|
|
237
|
+
return this.request("POST", path, options);
|
|
238
|
+
}
|
|
239
|
+
async put(path, options) {
|
|
240
|
+
return this.request("PUT", path, options);
|
|
241
|
+
}
|
|
242
|
+
async patch(path, options) {
|
|
243
|
+
return this.request("PATCH", path, options);
|
|
244
|
+
}
|
|
245
|
+
async delete(path, options) {
|
|
246
|
+
return this.request("DELETE", path, options);
|
|
247
|
+
}
|
|
248
|
+
async request(method, path, options) {
|
|
249
|
+
assertScope(method, path, options?.scope);
|
|
250
|
+
const auth = options?.auth ?? true;
|
|
251
|
+
let token = null;
|
|
252
|
+
if (auth) {
|
|
253
|
+
token = await this.credentials.getAccessToken();
|
|
254
|
+
if (token === null) {
|
|
255
|
+
throw new ApiError(
|
|
256
|
+
401,
|
|
257
|
+
"no_credentials",
|
|
258
|
+
"Not signed in: no credentials available.",
|
|
259
|
+
this.credentials.reauthHint()
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
let response = await this.send(method, path, options, token);
|
|
264
|
+
if (auth && response.status === 401) {
|
|
265
|
+
const fresh = await this.credentials.forceRefresh();
|
|
266
|
+
if (fresh !== null) {
|
|
267
|
+
response = await this.send(method, path, options, fresh);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return this.finalize(response, path, auth);
|
|
271
|
+
}
|
|
272
|
+
async send(method, path, options, token) {
|
|
273
|
+
const url = `${this.baseUrl}${path}${buildQueryString(options?.query)}`;
|
|
274
|
+
const headers = { ...this.identityHeaders, accept: "application/json" };
|
|
275
|
+
if (token !== null) headers.authorization = `Bearer ${token}`;
|
|
276
|
+
if (options?.scope?.projectId !== void 0) headers[PROJECT_HEADER] = options.scope.projectId;
|
|
277
|
+
if (options?.scope?.workspaceId !== void 0) headers[WORKSPACE_HEADER] = options.scope.workspaceId;
|
|
278
|
+
const init = {
|
|
279
|
+
method,
|
|
280
|
+
headers,
|
|
281
|
+
// 规约 ③:每请求超时(裸 fetch 默认是 undici 的 300s,太长)
|
|
282
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
283
|
+
};
|
|
284
|
+
if (options?.body !== void 0) {
|
|
285
|
+
headers["content-type"] = "application/json";
|
|
286
|
+
init.body = JSON.stringify(options.body);
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
return await this.fetchImpl(url, init);
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
292
|
+
throw new ApiError(0, "timeout", `Request timed out after ${this.timeoutMs}ms: ${method} ${path}`);
|
|
293
|
+
}
|
|
294
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
295
|
+
throw new ApiError(0, "network_error", `Network error: ${method} ${path} (${detail})`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async finalize(response, path, auth) {
|
|
299
|
+
if (response.ok) {
|
|
300
|
+
if (response.status === 204) return void 0;
|
|
301
|
+
return await response.json();
|
|
302
|
+
}
|
|
303
|
+
const bodyText = await response.text().catch(() => "");
|
|
304
|
+
const parsed = parseErrorBody(response.status, bodyText);
|
|
305
|
+
let message = parsed.message;
|
|
306
|
+
const hint = response.status === 401 && auth ? this.credentials.reauthHint() : void 0;
|
|
307
|
+
if (path.includes("/supplier/") || path.startsWith("/supplier")) {
|
|
308
|
+
if (response.status === 403) {
|
|
309
|
+
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.";
|
|
310
|
+
} else if (response.status === 404) {
|
|
311
|
+
message = `${message} (the resource does not exist, or is not owned by your account \u2014 the backend returns 404 for both, without distinction)`;
|
|
312
|
+
}
|
|
313
|
+
} else if (parsed.code === "not_found") {
|
|
314
|
+
const note = notFoundNote(parsed.details?.resource);
|
|
315
|
+
if (note) message = `${message} (${note})`;
|
|
316
|
+
}
|
|
317
|
+
throw new ApiError(response.status, parsed.code, message, hint, parsed.details);
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// src/shared/log.ts
|
|
322
|
+
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
323
|
+
function currentLevel() {
|
|
324
|
+
const raw = process.env.LUNE_MCP_LOG_LEVEL;
|
|
325
|
+
return raw === "debug" || raw === "info" || raw === "warn" || raw === "error" ? raw : "info";
|
|
326
|
+
}
|
|
327
|
+
var instance;
|
|
328
|
+
function write(level, args) {
|
|
329
|
+
if (WEIGHT[level] < WEIGHT[currentLevel()]) return;
|
|
330
|
+
const inst = instance ? ` inst=${instance}` : "";
|
|
331
|
+
console.error(`[lune-mcp] ${(/* @__PURE__ */ new Date()).toISOString()} ${level}${inst}:`, ...args);
|
|
332
|
+
}
|
|
333
|
+
function formatFields(fields) {
|
|
334
|
+
const parts = [];
|
|
335
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
336
|
+
if (value === void 0 || value === null) continue;
|
|
337
|
+
const raw = String(value);
|
|
338
|
+
parts.push(`${key}=${/[\s"=]/.test(raw) ? JSON.stringify(raw) : raw}`);
|
|
339
|
+
}
|
|
340
|
+
return parts.join(" ");
|
|
341
|
+
}
|
|
342
|
+
var log = {
|
|
343
|
+
debug: (...args) => write("debug", args),
|
|
344
|
+
info: (...args) => write("info", args),
|
|
345
|
+
warn: (...args) => write("warn", args),
|
|
346
|
+
error: (...args) => write("error", args),
|
|
347
|
+
/** 结构化事件行:`event=<name> k=v …`(字段顺序 = 传入顺序,便于肉眼扫)。 */
|
|
348
|
+
event: (level, name, fields = {}) => write(level, [formatFields({ event: name, ...fields })])
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
export {
|
|
352
|
+
ApiError,
|
|
353
|
+
ScopeMisuseError,
|
|
354
|
+
isScopeProgrammingError,
|
|
355
|
+
BackendClient,
|
|
356
|
+
log
|
|
357
|
+
};
|