tokenwallet-mcp 1.0.1 → 1.0.2

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
@@ -8,29 +8,26 @@ Official MCP server for [TokenWallet](https://token-wallet.app) — connect your
8
8
 
9
9
  ## Installation
10
10
 
11
- ### CLI (Codex CLI / Claude Code / Gemini CLI)
11
+ ### CLI (Codex CLI / Claude Code)
12
12
 
13
13
  ```bash
14
14
  # Codex CLI
15
- codex mcp add tokenwallet -- npx -y tokenwallet-mcp
15
+ codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
16
16
 
17
17
  # Claude Code
18
- claude mcp add tokenwallet -- npx -y tokenwallet-mcp
19
-
20
- # Gemini CLI
21
- gemini mcp add tokenwallet npx -y tokenwallet-mcp
18
+ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
22
19
  ```
23
20
 
24
- ### Desktop & IDE (Cursor / Antigravity / Claude Desktop / Windsurf / Cline & more)
21
+ ### Desktop & IDE (Claude Desktop / Windsurf / Cline & more)
25
22
 
26
- Add the following to your client's MCP configuration file (works with any MCP-compatible IDE or AI client):
23
+ Add the following to your client's MCP configuration file and replace `<provider>` with the provider ID, such as `claude`.
27
24
 
28
25
  ```json
29
26
  {
30
27
  "mcpServers": {
31
28
  "tokenwallet": {
32
29
  "command": "npx",
33
- "args": ["-y", "tokenwallet-mcp"]
30
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
34
31
  }
35
32
  }
36
33
  }
@@ -46,7 +43,7 @@ Add to your user or workspace `.vscode/mcp.json`:
46
43
  "tokenwallet": {
47
44
  "type": "stdio",
48
45
  "command": "npx",
49
- "args": ["-y", "tokenwallet-mcp"]
46
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
50
47
  }
51
48
  }
52
49
  }
@@ -57,7 +54,7 @@ Add to your user or workspace `.vscode/mcp.json`:
57
54
  1. After installation, start a conversation in your AI client and say:
58
55
  **"Connect to TokenWallet"**
59
56
  2. Open the **TokenWallet** app on your phone, tap **+** → select the platform → **Scan QR Code** (or enter the 8-character pairing code manually).
60
- 3. Once connected, your quota updates will sync to the TokenWallet app automatically.
57
+ 3. After pairing, view your quota in TokenWallet.
61
58
 
62
59
  ---
63
60
 
@@ -67,20 +64,17 @@ Add to your user or workspace `.vscode/mcp.json`:
67
64
 
68
65
  ### 安装方式
69
66
 
70
- #### 命令行客户端(Codex CLI / Claude Code / Gemini CLI)
67
+ #### 命令行客户端(Codex CLI / Claude Code)
71
68
 
72
69
  ```bash
73
70
  # Codex CLI
74
- codex mcp add tokenwallet -- npx -y tokenwallet-mcp
71
+ codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
75
72
 
76
73
  # Claude Code
77
- claude mcp add tokenwallet -- npx -y tokenwallet-mcp
78
-
79
- # Gemini CLI
80
- gemini mcp add tokenwallet npx -y tokenwallet-mcp
74
+ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
81
75
  ```
82
76
 
83
- #### 桌面端与 IDE(Cursor / Antigravity / Claude Desktop / Windsurf / Cline 等)
77
+ #### 桌面端与 IDE(Claude Desktop / Windsurf / Cline 等)
84
78
 
85
79
  在对应客户端的 MCP 配置文件中加入(其他任何支持 MCP 协议的 IDE 或 AI 客户端均可按相同方式配置使用):
86
80
 
@@ -89,7 +83,7 @@ gemini mcp add tokenwallet npx -y tokenwallet-mcp
89
83
  "mcpServers": {
90
84
  "tokenwallet": {
91
85
  "command": "npx",
92
- "args": ["-y", "tokenwallet-mcp"]
86
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
93
87
  }
94
88
  }
95
89
  }
@@ -105,15 +99,50 @@ gemini mcp add tokenwallet npx -y tokenwallet-mcp
105
99
  "tokenwallet": {
106
100
  "type": "stdio",
107
101
  "command": "npx",
108
- "args": ["-y", "tokenwallet-mcp"]
102
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
109
103
  }
110
104
  }
111
105
  }
112
106
  ```
113
107
 
108
+ 将配置中的 `<provider>` 替换为对应的供应商 ID,例如 `claude`。
109
+
114
110
  ### 快速开始
115
111
 
116
112
  1. 安装完成后,在 AI 客户端对话中输入:
117
113
  **「帮我连接 TokenWallet」**
118
114
  2. 打开手机上的 **词元钱包(TokenWallet)** App,点击右上角 **+** → 选择对应平台 → **扫描二维码**(若无法扫码可手动输入 8 位配对码)。
119
- 3. 绑定完成后,额度将自动同步至你的词元钱包 App。
115
+ 3. 配对完成后,在词元钱包中查看额度。
116
+
117
+ ### 发布 npm 新版本
118
+
119
+ #### 首次配置
120
+
121
+ 在 [npm 包设置](https://www.npmjs.com/package/tokenwallet-mcp/access) 的 **Trusted Publisher** 中选择 **GitHub Actions**,填写下表并保存。 [npm 配置文档](https://docs.npmjs.com/trusted-publishers/#for-github-actions)
122
+
123
+ | 字段 | 值 |
124
+ | --- | --- |
125
+ | Organization or user | `token-wallet-app` |
126
+ | Repository | `mcp` |
127
+ | Workflow filename | `publish.yml` |
128
+ | Environment | 留空 |
129
+ | Allowed actions | 勾选 `npm publish` |
130
+
131
+ #### 每次发版
132
+
133
+ 确认工作区里的发布内容已经提交。在 MCP 仓库根目录执行以下命令。这个例子将 `1.0.1` 升到 `1.0.2`。
134
+
135
+ ```bash
136
+ git switch main
137
+ git pull --ff-only origin main
138
+ npm version patch
139
+ git push --atomic origin main v1.0.2
140
+ ```
141
+
142
+ `npm version patch` 会更新 `package.json` 和 `package-lock.json`,并创建版本提交和标签。以后发版时,把最后一条命令里的 `v1.0.2` 换成 `npm version` 输出的标签。
143
+
144
+ 标签推送后,在 GitHub 的 **Actions → Publish to npm** 查看结果。流水线会核对标签、运行类型检查和测试,再构建并发布。成功后执行以下命令,确认输出为刚发布的版本号:
145
+
146
+ ```bash
147
+ npm view tokenwallet-mcp@latest version
148
+ ```
@@ -80,9 +80,10 @@ export async function collectClaudeQuota() {
80
80
  }
81
81
  if (data.extra_usage?.is_enabled &&
82
82
  typeof data.extra_usage.monthly_limit === 'number' &&
83
- data.extra_usage.monthly_limit > 0) {
84
- const used = Number(data.extra_usage.used_credits ?? 0);
85
- const remaining = Math.max(0, Math.round((data.extra_usage.monthly_limit - used) * 100) / 100);
83
+ data.extra_usage.monthly_limit > 0 &&
84
+ typeof data.extra_usage.used_credits === 'number') {
85
+ const used = data.extra_usage.used_credits;
86
+ const remaining = Math.max(0, (data.extra_usage.monthly_limit - used) / 100);
86
87
  meters.push({
87
88
  meterKey: 'extra',
88
89
  product: 'claude-code',
@@ -90,7 +91,7 @@ export async function collectClaudeQuota() {
90
91
  kind: 'balance',
91
92
  window: 'month',
92
93
  remaining,
93
- total: data.extra_usage.monthly_limit,
94
+ total: data.extra_usage.monthly_limit / 100,
94
95
  unit: 'USD',
95
96
  observedAt: now,
96
97
  });
@@ -7,39 +7,67 @@ function readGeminiAccessToken() {
7
7
  if (envToken)
8
8
  return envToken;
9
9
  const geminiHome = process.env.GEMINI_CLI_HOME || path.join(os.homedir(), '.gemini');
10
- const credCandidates = [
11
- path.join(geminiHome, 'oauth_creds.json'),
12
- path.join(geminiHome, 'antigravity', 'oauth_creds.json'),
13
- ];
14
- for (const file of credCandidates) {
15
- if (!fs.existsSync(file))
16
- continue;
17
- try {
18
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
19
- if (parsed.access_token?.trim()) {
20
- return parsed.access_token.trim();
21
- }
22
- }
23
- catch {
24
- // Try next candidate
25
- }
10
+ const credFile = path.join(geminiHome, 'oauth_creds.json');
11
+ if (!fs.existsSync(credFile))
12
+ return null;
13
+ try {
14
+ const parsed = JSON.parse(fs.readFileSync(credFile, 'utf8'));
15
+ return parsed.access_token?.trim() || null;
16
+ }
17
+ catch {
18
+ return null;
26
19
  }
27
- return null;
20
+ }
21
+ async function resolveCodeAssistContext(headers) {
22
+ const res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist', {
23
+ method: 'POST',
24
+ headers,
25
+ body: JSON.stringify({
26
+ metadata: {
27
+ ideType: 'GEMINI_CLI',
28
+ pluginType: 'GEMINI',
29
+ },
30
+ }),
31
+ signal: AbortSignal.timeout(6000),
32
+ }).catch(() => null);
33
+ if (!res || !res.ok)
34
+ return {};
35
+ const payload = (await res.json().catch(() => null));
36
+ if (!payload)
37
+ return {};
38
+ const rawProj = payload.cloudaicompanionProject;
39
+ const project = typeof rawProj === 'string'
40
+ ? rawProj.trim() || undefined
41
+ : typeof rawProj?.id === 'string'
42
+ ? rawProj.id.trim() || undefined
43
+ : undefined;
44
+ const tierName = (payload.paidTier?.name || payload.currentTier?.name || '').trim() || undefined;
45
+ return { project, plan: tierName };
28
46
  }
29
47
  export async function collectGeminiQuota() {
30
48
  const token = readGeminiAccessToken();
31
49
  if (!token)
32
50
  return null;
33
- const res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
51
+ const headers = {
52
+ Authorization: `Bearer ${token}`,
53
+ 'Content-Type': 'application/json',
54
+ Accept: 'application/json',
55
+ };
56
+ const { project, plan } = await resolveCodeAssistContext(headers);
57
+ let res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
34
58
  method: 'POST',
35
- headers: {
36
- Authorization: `Bearer ${token}`,
37
- 'Content-Type': 'application/json',
38
- Accept: 'application/json',
39
- },
40
- body: JSON.stringify({}),
59
+ headers,
60
+ body: JSON.stringify(project ? { project } : {}),
41
61
  signal: AbortSignal.timeout(8000),
42
62
  }).catch(() => null);
63
+ if ((!res || !res.ok) && project) {
64
+ res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
65
+ method: 'POST',
66
+ headers,
67
+ body: JSON.stringify({}),
68
+ signal: AbortSignal.timeout(8000),
69
+ }).catch(() => null);
70
+ }
43
71
  if (!res || !res.ok)
44
72
  return null;
45
73
  const data = (await res.json().catch(() => null));
@@ -50,7 +78,7 @@ export async function collectGeminiQuota() {
50
78
  const flashBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('flash'));
51
79
  const meters = [];
52
80
  const pickLowest = (list) => list
53
- .filter((b) => typeof b.remainingFraction === 'number')
81
+ .filter((b) => typeof b.remainingFraction === 'number' && Number.isFinite(b.remainingFraction))
54
82
  .sort((a, b) => (a.remainingFraction ?? 1) - (b.remainingFraction ?? 1))[0];
55
83
  const pro = pickLowest(proBuckets);
56
84
  if (pro && typeof pro.remainingFraction === 'number') {
@@ -90,7 +118,7 @@ export async function collectGeminiQuota() {
90
118
  meters.push({
91
119
  meterKey: 'default',
92
120
  product: 'gemini',
93
- label: first.modelId || 'Google AI',
121
+ label: first.modelId || 'Gemini',
94
122
  kind: 'percent',
95
123
  window: 'day',
96
124
  remaining: Math.max(0, Math.min(100, Math.round(first.remainingFraction * 1000) / 10)),
@@ -105,6 +133,7 @@ export async function collectGeminiQuota() {
105
133
  return null;
106
134
  return {
107
135
  brand: 'gemini',
136
+ plan,
108
137
  observedAt: now,
109
138
  source: 'gemini-cli',
110
139
  meters,
@@ -1,8 +1,9 @@
1
1
  import { readLatestCodexQuota } from '../codex-reader.js';
2
2
  import { collectClaudeQuota } from './claude.js';
3
- import { collectCursorQuota } from './cursor.js';
4
3
  import { collectGeminiQuota } from './gemini.js';
5
- import { collectGrokQuota } from './grok.js';
4
+ import { collectMuseCodeQuota } from './muse-code.js';
5
+ import { collectXaiQuota } from './xai.js';
6
+ import { readStatusQuota } from './status-quota.js';
6
7
  export async function collectQuotaForBrand(brand) {
7
8
  switch (brand) {
8
9
  case 'openai': {
@@ -18,24 +19,14 @@ export async function collectQuotaForBrand(brand) {
18
19
  };
19
20
  }
20
21
  case 'claude':
21
- return collectClaudeQuota();
22
- case 'cursor':
23
- return collectCursorQuota();
22
+ return readStatusQuota('claude') ?? collectClaudeQuota();
24
23
  case 'gemini':
25
- return collectGeminiQuota();
26
- case 'grok':
27
- return collectGrokQuota();
24
+ return readStatusQuota('gemini') ?? collectGeminiQuota();
25
+ case 'muse-code':
26
+ return collectMuseCodeQuota();
27
+ case 'xai':
28
+ return collectXaiQuota();
28
29
  default:
29
30
  return null;
30
31
  }
31
32
  }
32
- export async function collectAllLocalQuotas() {
33
- const results = await Promise.all([
34
- collectQuotaForBrand('openai'),
35
- collectQuotaForBrand('claude'),
36
- collectQuotaForBrand('cursor'),
37
- collectQuotaForBrand('gemini'),
38
- collectQuotaForBrand('grok'),
39
- ]);
40
- return results.filter((snap) => snap !== null);
41
- }
@@ -0,0 +1,58 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { z } from 'zod';
4
+ import { toRemainingPercent } from './types.js';
5
+ const runFile = promisify(execFile);
6
+ const allowanceWindow = z.object({
7
+ usedPercent: z.number().min(0).max(100),
8
+ resetsAtMs: z.number().int().positive().nullish(),
9
+ });
10
+ const usageResponse = z.object({
11
+ allowance: z.object({
12
+ tier: z.string().trim().nullish(),
13
+ window: allowanceWindow.nullish(),
14
+ weekly: allowanceWindow.nullish(),
15
+ asOfMs: z.number().int().positive().nullish(),
16
+ }).nullish(),
17
+ });
18
+ export async function collectMuseCodeQuota() {
19
+ try {
20
+ const windows = process.platform === 'win32';
21
+ // The Windows installer puts a muse.cmd launcher on PATH.
22
+ const command = windows ? process.env.ComSpec || 'cmd.exe' : 'muse';
23
+ const args = windows ? ['/d', '/c', 'muse', 'usage', '--json'] : ['usage', '--json'];
24
+ const { stdout } = await runFile(command, args, {
25
+ encoding: 'utf8',
26
+ timeout: 15_000,
27
+ maxBuffer: 128 * 1024,
28
+ windowsHide: true,
29
+ });
30
+ const response = usageResponse.safeParse(JSON.parse(stdout));
31
+ if (!response.success || !response.data.allowance)
32
+ return null;
33
+ const { tier, window, weekly, asOfMs } = response.data.allowance;
34
+ const observedAt = asOfMs ?? Date.now();
35
+ const meters = [];
36
+ const periods = [
37
+ { reading: window, meterKey: '5h', period: '5h', label: '5 小时' },
38
+ { reading: weekly, meterKey: '7d', period: 'week', label: '每周额度' },
39
+ ];
40
+ for (const { reading, meterKey, period, label } of periods) {
41
+ if (!reading)
42
+ continue;
43
+ const remaining = toRemainingPercent(reading.usedPercent);
44
+ if (remaining === undefined)
45
+ continue;
46
+ meters.push({
47
+ meterKey, product: 'muse-code', label, kind: 'percent', window: period,
48
+ remaining, total: 100, unit: '%', resetsAt: reading.resetsAtMs ?? undefined, observedAt,
49
+ });
50
+ }
51
+ if (!meters.length)
52
+ return null;
53
+ return { brand: 'muse-code', source: 'muse-code', plan: tier || undefined, meters, observedAt };
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CONFIG_DIR } from '../config.js';
4
+ import { toEpochMs } from './types.js';
5
+ export function captureStatusQuota(brand, data) {
6
+ const observedAt = Date.now();
7
+ const meters = [];
8
+ if (brand === 'gemini' && (!data.product || data.product === 'gemini')) {
9
+ for (const [id, bucket] of Object.entries(data.quota ?? {})) {
10
+ if (!bucket || bucket.disabled)
11
+ continue;
12
+ const fraction = bucket.remaining_fraction;
13
+ const amount = bucket.remaining_amount;
14
+ const percent = typeof fraction === 'number' && fraction >= 0 && fraction <= 1;
15
+ if (!percent && !(typeof amount === 'number' && Number.isFinite(amount) && amount >= 0))
16
+ continue;
17
+ meters.push({
18
+ meterKey: id, product: brand, label: id, kind: percent ? 'percent' : 'count',
19
+ remaining: percent ? Math.round(fraction * 1000) / 10 : amount,
20
+ total: percent ? 100 : undefined, unit: percent ? '%' : undefined,
21
+ resetsAt: toEpochMs(bucket.reset_time), observedAt,
22
+ });
23
+ }
24
+ }
25
+ else if (brand === 'claude') {
26
+ for (const [id, window] of [['five_hour', '5h'], ['seven_day', 'week']]) {
27
+ const bucket = data.rate_limits?.[id];
28
+ const used = bucket?.used_percentage;
29
+ if (typeof used !== 'number' || !(used >= 0 && used <= 100))
30
+ continue;
31
+ meters.push({
32
+ meterKey: window === 'week' ? '7d' : '5h', product: 'claude-code',
33
+ label: window === 'week' ? '每周额度' : '5 小时', kind: 'percent', window,
34
+ remaining: Math.round((100 - used) * 10) / 10, total: 100, unit: '%',
35
+ resetsAt: toEpochMs(bucket?.resets_at), observedAt,
36
+ });
37
+ }
38
+ }
39
+ if (!meters.length)
40
+ return null;
41
+ const snapshot = { brand, source: brand + '-statusline', meters, observedAt };
42
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
43
+ const file = path.join(CONFIG_DIR, brand + '-quota.json');
44
+ const tmp = file + '.' + process.pid;
45
+ fs.writeFileSync(tmp, JSON.stringify(snapshot), { mode: 0o600 });
46
+ fs.renameSync(tmp, file);
47
+ return snapshot;
48
+ }
49
+ export function readStatusQuota(brand) {
50
+ try {
51
+ const snapshot = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, brand + '-quota.json'), 'utf8'));
52
+ if (snapshot.brand !== brand || !Array.isArray(snapshot.meters) || !snapshot.meters.length)
53
+ return null;
54
+ const now = Date.now();
55
+ const meters = snapshot.meters.filter(m => m.resetsAt === undefined || m.resetsAt > now);
56
+ return meters.length ? { ...snapshot, meters } : null;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
@@ -1,12 +1,3 @@
1
- export function maskEmail(email) {
2
- if (!email || !email.includes('@'))
3
- return undefined;
4
- const [user, domain] = email.trim().split('@');
5
- if (!user || !domain)
6
- return undefined;
7
- const prefix = user.length <= 2 ? user[0] : user.slice(0, 2);
8
- return `${prefix}***@${domain}`;
9
- }
10
1
  export function toRemainingPercent(usedPercent) {
11
2
  if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent))
12
3
  return undefined;
@@ -1,4 +1,4 @@
1
- export async function collectGrokQuota() {
1
+ export async function collectXaiQuota() {
2
2
  const mgmtKey = process.env.XAI_MANAGEMENT_API_KEY?.trim();
3
3
  const teamId = process.env.XAI_TEAM_ID?.trim();
4
4
  if (!mgmtKey || !teamId)
@@ -11,16 +11,20 @@ export async function collectGrokQuota() {
11
11
  },
12
12
  signal: AbortSignal.timeout(8000),
13
13
  }).catch(() => null);
14
- if (!res || !res.ok)
15
- return null;
14
+ if (!res)
15
+ throw new Error('无法连接 xAI Management API,请检查本机网络。');
16
+ if (!res.ok)
17
+ throw new Error('xAI 账单查询失败(HTTP ' + res.status + '),请检查团队 ID 和管理密钥的账单读取权限。');
16
18
  const data = (await res.json().catch(() => null));
17
19
  if (!data)
18
20
  return null;
19
- const rawRemaining = data.remaining?.val ?? data.remaining_balance ?? data.balance ?? data.total?.val;
20
- const remainingNum = typeof rawRemaining === 'string' ? Number(rawRemaining) : rawRemaining;
21
- if (typeof remainingNum !== 'number' || !Number.isFinite(remainingNum))
21
+ const raw = data.total?.val;
22
+ if (typeof raw !== 'number' && !(typeof raw === 'string' && /^-?\d+$/.test(raw)))
23
+ return null;
24
+ const cents = Number(raw);
25
+ if (!Number.isSafeInteger(cents))
22
26
  return null;
23
- // xAI billing API may return cents or dollars depending on field; normalize cleanly
27
+ // Prepaid credits are negative entries on the USD-cent ledger.
24
28
  const now = Date.now();
25
29
  const meters = [
26
30
  {
@@ -28,13 +32,13 @@ export async function collectGrokQuota() {
28
32
  product: 'xai',
29
33
  label: '可用余额',
30
34
  kind: 'balance',
31
- remaining: Math.round(remainingNum * 100) / 100,
35
+ remaining: Math.max(0, -cents / 100),
32
36
  unit: 'USD',
33
37
  observedAt: now,
34
38
  },
35
39
  ];
36
40
  return {
37
- brand: 'grok',
41
+ brand: 'xai',
38
42
  observedAt: now,
39
43
  source: 'xai-billing',
40
44
  meters,
package/dist/config.js CHANGED
@@ -2,20 +2,30 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  const DEFAULT_API_URL = process.env.TOKENWALLET_API_URL || 'https://api.token-wallet.app/v1';
5
- const CONFIG_DIR = process.env.TOKENWALLET_MCP_HOME || path.join(os.homedir(), '.tokenwallet-mcp');
6
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
5
+ export const CONFIG_DIR = process.env.TOKENWALLET_MCP_HOME || path.join(os.homedir(), '.tokenwallet-mcp');
6
+ const providerIds = ['openai', 'claude', 'gemini', 'muse-code', 'xai', 'deepseek', 'openrouter', 'other'];
7
+ export function configuredProvider() {
8
+ const index = process.argv.indexOf('--provider');
9
+ const value = index < 0 ? process.env.TOKENWALLET_PROVIDER : process.argv[index + 1];
10
+ const provider = providerIds.find(id => id === value);
11
+ if (!provider)
12
+ throw new Error('请在本客户端的 MCP 启动参数中指定 --provider,或设置 TOKENWALLET_PROVIDER。支持:' + providerIds.join(', '));
13
+ return provider;
14
+ }
7
15
  export function getApiBaseUrl() {
8
16
  const cfg = loadConfig();
9
17
  return (process.env.TOKENWALLET_API_URL || cfg.apiBaseUrl || DEFAULT_API_URL).replace(/\/+$/, '');
10
18
  }
11
19
  export function loadConfig() {
20
+ const provider = configuredProvider();
21
+ const file = path.join(CONFIG_DIR, provider, 'config.json');
12
22
  try {
13
- if (fs.existsSync(CONFIG_FILE)) {
14
- const parsed = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
23
+ if (fs.existsSync(file)) {
24
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
15
25
  return {
16
26
  apiBaseUrl: parsed.apiBaseUrl || DEFAULT_API_URL,
17
- connections: Array.isArray(parsed.connections) ? parsed.connections : [],
18
- pendingSessions: Array.isArray(parsed.pendingSessions) ? parsed.pendingSessions : [],
27
+ connections: Array.isArray(parsed.connections) ? parsed.connections.filter(c => c.brand === provider).slice(0, 1) : [],
28
+ pendingSessions: Array.isArray(parsed.pendingSessions) ? parsed.pendingSessions.filter(s => s.brand === provider) : [],
19
29
  };
20
30
  }
21
31
  }
@@ -29,8 +39,9 @@ export function loadConfig() {
29
39
  };
30
40
  }
31
41
  export function saveConfig(config) {
32
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
33
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
42
+ const directory = path.join(CONFIG_DIR, configuredProvider());
43
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
44
+ fs.writeFileSync(path.join(directory, 'config.json'), JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
34
45
  }
35
46
  export function savePendingSession(session) {
36
47
  const cfg = loadConfig();
@@ -47,13 +58,7 @@ export function removePendingSession(sessionId) {
47
58
  }
48
59
  export function upsertBoundConnection(conn) {
49
60
  const cfg = loadConfig();
50
- const existingIdx = cfg.connections.findIndex((c) => c.cardId === conn.cardId);
51
- if (existingIdx >= 0) {
52
- cfg.connections[existingIdx] = conn;
53
- }
54
- else {
55
- cfg.connections.unshift(conn);
56
- }
61
+ cfg.connections = [conn];
57
62
  saveConfig(cfg);
58
63
  }
59
64
  export function markConnectionReported(cardId, reportedAt = Date.now()) {
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { timingSafeEqual, createHash } from 'node:crypto';
2
3
  import http from 'node:http';
3
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
5
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
6
  import { apiSubmitReport } from './api.js';
6
7
  import { collectQuotaForBrand } from './collectors/index.js';
7
- import { getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
8
+ import { configuredProvider, getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
8
9
  import { createTokenWalletMcpServer } from './server.js';
9
10
  function parseArgs() {
10
11
  const argv = process.argv.slice(2);
@@ -23,36 +24,41 @@ function startLocalAutoReporter() {
23
24
  if (cfg.connections.length === 0)
24
25
  return;
25
26
  const baseUrl = getApiBaseUrl();
26
- const uniqueBrands = Array.from(new Set(cfg.connections.map((c) => c.brand)));
27
- for (const brand of uniqueBrands) {
28
- const snap = await collectQuotaForBrand(brand);
29
- if (!snap || snap.meters.length === 0)
30
- continue;
31
- const sig = JSON.stringify(snap.meters.map((m) => [m.meterKey, m.remaining, m.resetsAt ?? null]));
32
- const matchingConns = cfg.connections.filter((c) => c.brand === brand);
33
- for (const conn of matchingConns) {
34
- if (lastFingerprintByCard.get(conn.cardId) === sig)
35
- continue;
36
- await apiSubmitReport(baseUrl, conn.writeToken, {
37
- plan: snap.plan,
38
- accountHint: snap.accountHint,
39
- observedAt: snap.observedAt,
40
- meters: snap.meters,
41
- });
42
- markConnectionReported(conn.cardId, Date.now());
43
- lastFingerprintByCard.set(conn.cardId, sig);
44
- }
45
- }
27
+ const [conn] = cfg.connections;
28
+ const snap = await collectQuotaForBrand(configuredProvider());
29
+ if (!snap?.meters.length)
30
+ return;
31
+ const sig = JSON.stringify([
32
+ snap.plan, snap.accountHint,
33
+ [...snap.meters].sort((a, b) => a.meterKey.localeCompare(b.meterKey)).map((m) => [
34
+ m.meterKey, m.product, m.label, m.kind, m.window, m.modelGroup,
35
+ m.remaining, m.total, m.unit, m.resetsAt,
36
+ ]),
37
+ ]);
38
+ const connection = JSON.stringify([baseUrl, conn.nodeId, conn.cardId]);
39
+ if (lastFingerprintByCard.get(connection) === sig)
40
+ return;
41
+ const result = await apiSubmitReport(baseUrl, conn.writeToken, {
42
+ plan: snap.plan,
43
+ accountHint: snap.accountHint,
44
+ observedAt: snap.observedAt,
45
+ meters: snap.meters,
46
+ }).catch(() => null);
47
+ if (!result)
48
+ return;
49
+ markConnectionReported(conn.cardId, Date.now());
50
+ lastFingerprintByCard.clear();
51
+ lastFingerprintByCard.set(connection, sig);
46
52
  }
47
53
  catch {
48
54
  // Ignore transient network errors during background sync
49
55
  }
50
56
  };
51
- void tick();
52
- const timer = setInterval(() => {
53
- void tick();
54
- }, 60_000);
55
- timer.unref();
57
+ const run = async () => {
58
+ await tick();
59
+ setTimeout(() => void run(), 60_000 + Math.floor(Math.random() * 3_000)).unref();
60
+ };
61
+ void run();
56
62
  }
57
63
  async function startStdio() {
58
64
  const server = createTokenWalletMcpServer();
@@ -62,10 +68,15 @@ async function startStdio() {
62
68
  console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
63
69
  }
64
70
  async function startHttp(port) {
71
+ const secret = process.env.TOKENWALLET_HTTP_TOKEN?.trim();
72
+ if (!secret)
73
+ throw new Error('HTTP MCP 需要为此实例设置独立 TOKENWALLET_HTTP_TOKEN,并在客户端使用 Bearer 认证。');
74
+ const digest = (s) => createHash('sha256').update(s).digest();
75
+ const expected = digest('Bearer ' + secret);
65
76
  const httpServer = http.createServer(async (req, res) => {
66
77
  res.setHeader('Access-Control-Allow-Origin', '*');
67
78
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
68
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Mcp-Session-Id');
79
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, Mcp-Session-Id');
69
80
  if (req.method === 'OPTIONS') {
70
81
  res.writeHead(204);
71
82
  res.end();
@@ -88,6 +99,11 @@ async function startHttp(port) {
88
99
  return;
89
100
  }
90
101
  if (pathname === '/' || pathname === '/mcp') {
102
+ if (!timingSafeEqual(expected, digest(req.headers.authorization ?? ''))) {
103
+ res.writeHead(401, { 'WWW-Authenticate': 'Bearer' });
104
+ res.end();
105
+ return;
106
+ }
91
107
  try {
92
108
  const server = createTokenWalletMcpServer();
93
109
  const transport = new StreamableHTTPServerTransport({
@@ -118,6 +134,7 @@ async function startHttp(port) {
118
134
  console.log(`[tokenwallet-mcp] TokenWallet API: ${getApiBaseUrl()}`);
119
135
  });
120
136
  }
137
+ configuredProvider();
121
138
  const { useHttp, port } = parseArgs();
122
139
  if (useHttp) {
123
140
  await startHttp(port);
package/dist/server.js CHANGED
@@ -1,14 +1,25 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
3
  import QRCode from 'qrcode';
3
4
  import { z } from 'zod';
5
+ const require = createRequire(import.meta.url);
6
+ const pkg = require('../package.json');
7
+ const SERVER_VERSION = pkg.version || '1.0.1';
4
8
  import { apiCreateMcpSession, apiPingNode, apiPollMcpSession, apiSubmitReport, } from './api.js';
5
9
  import { collectQuotaForBrand } from './collectors/index.js';
6
- import { getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
10
+ import { configuredProvider, getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
11
+ const sourceHelp = {
12
+ claude: '登录本机 Claude Code,或设置 Claude statusLine 采集器并完成一个回合。',
13
+ gemini: '先在本机终端登录 Gemini CLI(生成 ~/.gemini/oauth_creds.json),或配置 Gemini CLI statusLine 采集器。',
14
+ 'muse-code': '请在本机登录 Muse Code 订阅账号(CLI 1.4.13 或更新版本),并运行 muse usage --json 确认能读到套餐额度。',
15
+ xai: '检查 XAI_MANAGEMENT_API_KEY 的账单权限和 XAI_TEAM_ID。',
16
+ other: '自定义卡片由客户端从额度来源读取余量,再调用 report_quota 上报。可在客户端配置定时任务或用量事件来触发。',
17
+ };
7
18
  const meterSchema = z.object({
8
19
  meterKey: z.string().min(1).describe('Unique meter key, e.g. "5h", "7d", "balance:USD"'),
9
20
  product: z.string().optional().describe('Product identifier, e.g. "chatgpt", "codex", "claude-code"'),
10
21
  label: z.string().min(1).describe('Human-readable label, e.g. "5 小时", "每周额度", "可用余额"'),
11
- kind: z.enum(['percent', 'balance']).describe('"percent" for 0-100% quotas, "balance" for currency/credits'),
22
+ kind: z.enum(['percent', 'count', 'balance']).describe('"percent" for 0-100% quotas, "balance" for currency/credits'),
12
23
  window: z.enum(['5h', 'day', 'week', 'month', 'rolling']).optional(),
13
24
  modelGroup: z.string().optional(),
14
25
  remaining: z.number().describe('Remaining amount or percentage (0-100)'),
@@ -49,22 +60,28 @@ async function tryPollPendingSession(session) {
49
60
  function stopBackgroundPoll(sessionId) {
50
61
  const timer = activePollTimers.get(sessionId);
51
62
  if (timer) {
52
- clearInterval(timer);
63
+ clearTimeout(timer);
53
64
  activePollTimers.delete(sessionId);
54
65
  }
55
66
  }
56
67
  function startBackgroundPoll(session) {
57
68
  stopBackgroundPoll(session.sessionId);
58
- const timer = setInterval(() => {
59
- if (Date.now() > session.expiresAt) {
60
- removePendingSession(session.sessionId);
61
- stopBackgroundPoll(session.sessionId);
62
- return;
63
- }
64
- void tryPollPendingSession(session);
65
- }, 3000);
66
- timer.unref();
67
- activePollTimers.set(session.sessionId, timer);
69
+ const schedule = (attempt) => {
70
+ const delay = attempt < 3 ? 3_000 : attempt < 6 ? 6_000 : 15_000;
71
+ const timer = setTimeout(async () => {
72
+ if (Date.now() >= session.expiresAt) {
73
+ removePendingSession(session.sessionId);
74
+ stopBackgroundPoll(session.sessionId);
75
+ return;
76
+ }
77
+ await tryPollPendingSession(session);
78
+ if (activePollTimers.get(session.sessionId) === timer)
79
+ schedule(attempt + 1);
80
+ }, Math.min(delay, Math.max(0, session.expiresAt - Date.now())));
81
+ timer.unref();
82
+ activePollTimers.set(session.sessionId, timer);
83
+ };
84
+ schedule(0);
68
85
  }
69
86
  async function syncAllPendingSessions() {
70
87
  const cfg = loadConfig();
@@ -77,45 +94,47 @@ async function syncAllPendingSessions() {
77
94
  return newlyBound;
78
95
  }
79
96
  export function createTokenWalletMcpServer() {
97
+ const provider = configuredProvider();
80
98
  const server = new McpServer({
81
99
  name: 'tokenwallet-mcp',
82
- version: '1.0.0',
100
+ version: SERVER_VERSION,
83
101
  });
84
102
  server.registerTool('connect_tokenwallet', {
85
103
  title: 'Connect to TokenWallet App',
86
104
  description: 'Generate a QR code and pairing link so the user can scan with the TokenWallet mobile app to bind this AI client and sync token quotas.',
87
105
  inputSchema: {
88
- brand: z
89
- .enum(['openai', 'claude', 'gemini', 'cursor', 'grok', 'openrouter', 'deepseek', 'other'])
90
- .default('openai')
91
- .describe('Provider brand (openai, claude, gemini, cursor, grok, openrouter, deepseek, other)'),
92
- provider: z.string().optional().describe('Custom display name for the provider'),
106
+ provider: z.literal(provider).optional().describe('Provider configured for this installation'),
107
+ displayName: z.string().optional().describe('Optional card display name'),
93
108
  nodeLabel: z.string().optional().describe('Friendly name for this client/machine, e.g. "MacBook ChatGPT"'),
94
- source: z.string().optional().describe('Client source identifier, e.g. "chatgpt", "codex", "claude-code", "cursor", "gemini-cli"'),
109
+ source: z.string().optional().describe('Client source identifier, e.g. "chatgpt", "codex", "claude-code", "gemini-cli"'),
95
110
  plan: z.string().optional().describe('Subscription plan name, e.g. "Plus", "Pro", "AI Pro"'),
96
111
  accountHint: z.string().optional().describe('Optional masked account hint, e.g. "u***@gmail.com"'),
97
112
  meters: z.array(meterSchema).optional().describe('Optional initial quota meters to populate immediately upon scan'),
98
113
  },
99
114
  }, async (args) => {
100
115
  const baseUrl = getApiBaseUrl();
101
- const localQuota = !args.meters || args.meters.length === 0
102
- ? await collectQuotaForBrand(args.brand)
103
- : null;
116
+ const requiresCollector = provider === 'claude' || provider === 'gemini' || provider === 'muse-code' || provider === 'xai';
117
+ const localQuota = requiresCollector || !args.meters?.length ? await collectQuotaForBrand(provider) : null;
118
+ if (requiresCollector && !localQuota?.meters.length) {
119
+ return { isError: true, content: [{ type: 'text', text: sourceHelp[provider] }] };
120
+ }
104
121
  const created = await apiCreateMcpSession(baseUrl, {
105
- brand: args.brand,
106
- provider: args.provider,
122
+ provider,
123
+ displayName: args.displayName,
107
124
  nodeLabel: args.nodeLabel,
108
125
  source: args.source ?? localQuota?.source ?? 'mcp',
109
126
  plan: args.plan ?? localQuota?.plan,
110
127
  accountHint: args.accountHint ?? localQuota?.accountHint,
111
- meters: args.meters ?? localQuota?.meters,
128
+ meters: localQuota?.meters ?? args.meters,
112
129
  });
130
+ if (created.provider !== provider)
131
+ throw new Error('中转服务返回了不同的供应商,请检查服务版本。');
113
132
  const pending = {
114
133
  sessionId: created.sessionId,
115
- mcpCode: created.mcpCode,
134
+ mcpCode: created.code,
116
135
  pollToken: created.pollToken,
117
- brand: created.brand,
118
- provider: created.provider,
136
+ brand: created.provider,
137
+ provider: created.displayName,
119
138
  deepLink: created.deepLink,
120
139
  webLink: created.webLink,
121
140
  expiresAt: created.expiresAt,
@@ -130,10 +149,11 @@ export function createTokenWalletMcpServer() {
130
149
  const base64Png = qrDataUrl.replace(/^data:image\/png;base64,/, '');
131
150
  const asciiQr = await QRCode.toString(created.qrPayload, { type: 'utf8' });
132
151
  const expiresInMin = Math.max(1, Math.round((created.expiresAt - Date.now()) / 60_000));
152
+ const cardLabel = provider === 'other' ? '自定义卡片' : created.displayName;
133
153
  const summary = [
134
- `请打开 TokenWallet App,进入「添加卡片 → ${created.provider}」,点击「扫描二维码」扫描下方二维码即可完成连接(有效期约 ${expiresInMin} 分钟):`,
154
+ `请打开 TokenWallet App,进入「添加卡片 → ${cardLabel}」,点击「扫描二维码」扫描下方二维码即可完成连接(有效期约 ${expiresInMin} 分钟):`,
135
155
  '',
136
- `连接码:${created.mcpCode}`,
156
+ `连接码:${created.code}`,
137
157
  `手机直达链接:${created.deepLink}`,
138
158
  `网页跳转链接:${created.webLink}`,
139
159
  '',
@@ -141,6 +161,9 @@ export function createTokenWalletMcpServer() {
141
161
  asciiQr.trimEnd(),
142
162
  '```',
143
163
  '',
164
+ provider === 'other' || (!localQuota && !args.meters?.length)
165
+ ? sourceHelp[provider] ?? '等待首次额度上报。'
166
+ : '',
144
167
  '扫码后本 MCP 会自动完成配对并保存只写上报凭证;也可以调用 `check_connection_status` 立即确认绑定状态。',
145
168
  ].join('\n');
146
169
  return {
@@ -201,8 +224,8 @@ export function createTokenWalletMcpServer() {
201
224
  title: 'Report Quota to TokenWallet',
202
225
  description: 'Push real-time remaining token quota or balance meters to a bound TokenWallet card.',
203
226
  inputSchema: {
204
- cardId: z.string().optional().describe('Target cardId (optional; defaults to matching brand or latest bound card)'),
205
- brand: z.string().optional().describe('Brand filter when cardId is omitted, e.g. "openai", "claude"'),
227
+ cardId: z.string().optional().describe('Target cardId; may be omitted when exactly one card matches'),
228
+ provider: z.literal(provider).optional(),
206
229
  plan: z.string().optional().describe('Optional updated plan name, e.g. "Plus", "Pro"'),
207
230
  accountHint: z.string().optional().describe('Optional masked account hint'),
208
231
  meters: z.array(meterSchema).min(1).describe('One or more quota meters to report'),
@@ -210,16 +233,15 @@ export function createTokenWalletMcpServer() {
210
233
  }, async (args) => {
211
234
  await syncAllPendingSessions();
212
235
  const cfg = loadConfig();
213
- const conn = (args.cardId && cfg.connections.find((c) => c.cardId === args.cardId)) ||
214
- (args.brand && cfg.connections.find((c) => c.brand === args.brand)) ||
215
- cfg.connections[0];
236
+ const matches = cfg.connections.filter((c) => (!args.cardId || args.cardId === c.cardId) && provider === c.brand);
237
+ const conn = matches.length === 1 ? matches[0] : undefined;
216
238
  if (!conn) {
217
239
  return {
218
240
  isError: true,
219
241
  content: [
220
242
  {
221
243
  type: 'text',
222
- text: '尚未绑定任何 TokenWallet 卡片。请先调用 `connect_tokenwallet` 生成二维码并在手机 App 中扫码绑定。',
244
+ text: '请用 list_connections 查看卡片,并指定正确的 cardId 后重试。',
223
245
  },
224
246
  ],
225
247
  };
@@ -240,67 +262,34 @@ export function createTokenWalletMcpServer() {
240
262
  content: [
241
263
  {
242
264
  type: 'text',
243
- text: `已上报 ${conn.provider}(cardId=${res.cardId})最新额度,更新字段:${res.updatedMeters.join(', ') || '无'},服务端版本 rev=${res.revision}。`,
265
+ text: `已上报 ${conn.provider}(cardId=${res.cardId})最新额度,同步完成。`,
244
266
  },
245
267
  ],
246
268
  };
247
269
  });
248
270
  server.registerTool('sync_local_quotas', {
249
271
  title: 'Sync Real Local AI Client Quotas',
250
- description: 'Collect real-time remaining quotas from locally installed AI clients (Codex CLI, Claude Code, Cursor, Gemini CLI, Grok/xAI) and push updates to bound TokenWallet cards.',
272
+ description: 'Collect real-time remaining quotas from locally installed AI clients (Codex CLI, Claude Code, Gemini CLI, Muse Code, xAI) and push updates to bound TokenWallet cards.',
251
273
  inputSchema: {
252
- brand: z
253
- .enum(['openai', 'claude', 'cursor', 'gemini', 'grok'])
254
- .optional()
255
- .describe('Optional specific brand to sync; omit to sync all bound local providers'),
274
+ provider: z.literal(provider).optional(),
256
275
  cardId: z.string().optional().describe('Optional specific bound cardId'),
257
276
  },
258
- }, async ({ brand, cardId }) => {
277
+ }, async ({ cardId }) => {
259
278
  await syncAllPendingSessions();
260
279
  const cfg = loadConfig();
261
280
  const baseUrl = getApiBaseUrl();
262
- const targetBrands = brand
263
- ? [brand]
264
- : Array.from(new Set(cfg.connections.map((c) => c.brand)));
265
- if (targetBrands.length === 0) {
266
- return {
267
- isError: true,
268
- content: [
269
- {
270
- type: 'text',
271
- text: '尚未绑定任何 TokenWallet 卡片。请先调用 connect_tokenwallet 生成二维码并在手机 App 中扫码绑定。',
272
- },
273
- ],
274
- };
275
- }
276
- const lines = [];
277
- for (const b of targetBrands) {
278
- const snapshot = await collectQuotaForBrand(b);
279
- if (!snapshot) {
280
- lines.push(`- ${b}: 未检测到本机可用额度数据源`);
281
- continue;
282
- }
283
- const conn = (cardId && cfg.connections.find((c) => c.cardId === cardId)) ||
284
- cfg.connections.find((c) => c.brand === b);
285
- if (!conn) {
286
- lines.push(`- ${b}: 已采集到真实额度(${snapshot.meters.map((m) => `${m.label} ${m.remaining}${m.unit ?? ''}`).join(',')}),但尚未绑定卡片`);
287
- continue;
288
- }
289
- const res = await apiSubmitReport(baseUrl, conn.writeToken, {
290
- plan: snapshot.plan,
291
- accountHint: snapshot.accountHint,
292
- observedAt: snapshot.observedAt,
293
- meters: snapshot.meters,
294
- });
295
- markConnectionReported(conn.cardId, Date.now());
296
- const summary = snapshot.meters
297
- .map((m) => `${m.label} ${m.remaining}${m.unit ?? ''}`)
298
- .join(',');
299
- lines.push(`- ${conn.provider} (cardId=${res.cardId}): 已同步 ${summary}`);
300
- }
301
- return {
302
- content: [{ type: 'text', text: lines.join('\n') }],
303
- };
281
+ const conn = cfg.connections.find(c => c.brand === provider && (!cardId || c.cardId === cardId));
282
+ if (!conn)
283
+ return { isError: true, content: [{ type: 'text', text: '当前实例没有匹配的绑定。' }] };
284
+ const snapshot = await collectQuotaForBrand(provider);
285
+ if (!snapshot)
286
+ return { isError: true, content: [{ type: 'text', text: sourceHelp[provider] ?? '请检查本机登录状态。' }] };
287
+ await apiSubmitReport(baseUrl, conn.writeToken, {
288
+ plan: snapshot.plan, accountHint: snapshot.accountHint,
289
+ observedAt: snapshot.observedAt, meters: snapshot.meters,
290
+ });
291
+ markConnectionReported(conn.cardId, Date.now());
292
+ return { content: [{ type: 'text', text: '额度已同步至钱包。' }] };
304
293
  });
305
294
  server.registerTool('list_connections', {
306
295
  title: 'List Connected TokenWallet Cards',
@@ -0,0 +1,15 @@
1
+ import { captureStatusQuota } from './collectors/status-quota.js';
2
+ const brand = process.argv[2];
3
+ if (brand !== 'gemini' && brand !== 'claude') {
4
+ console.error('Usage: node statusline.js gemini|claude');
5
+ process.exitCode = 1;
6
+ }
7
+ else {
8
+ process.stdin.setEncoding('utf8');
9
+ let input = '';
10
+ for await (const chunk of process.stdin)
11
+ input += chunk;
12
+ const snapshot = captureStatusQuota(brand, JSON.parse(input));
13
+ if (snapshot)
14
+ console.log(snapshot.meters.map(m => m.label + ' ' + m.remaining + (m.unit ?? '')).join(' · '));
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenwallet-mcp",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "TokenWallet MCP Server for QR pairing and automatic real-time AI token quota syncing",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "repository": {
28
28
  "type": "git",
29
- "url": "https://github.com/token-wallet-app/mcp.git"
29
+ "url": "git+https://github.com/token-wallet-app/mcp.git"
30
30
  },
31
31
  "homepage": "https://token-wallet.app",
32
32
  "scripts": {
@@ -36,6 +36,7 @@
36
36
  "prepublishOnly": "npm run build",
37
37
  "start": "node dist/index.js",
38
38
  "start:http": "node dist/index.js --http",
39
+ "test": "tsx --test test/providers.test.ts",
39
40
  "typecheck": "tsc --noEmit"
40
41
  },
41
42
  "dependencies": {
@@ -1,108 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { maskEmail, toEpochMs } from './types.js';
5
- function getCursorStateDbPath() {
6
- if (process.env.CURSOR_STATE_DB)
7
- return process.env.CURSOR_STATE_DB;
8
- if (process.platform === 'win32') {
9
- const appData = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
10
- return path.join(appData, 'Cursor', 'User', 'globalStorage', 'state.vscdb');
11
- }
12
- if (process.platform === 'darwin') {
13
- return path.join(os.homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
14
- }
15
- return path.join(os.homedir(), '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
16
- }
17
- async function readCursorLocalAuth() {
18
- const envToken = process.env.CURSOR_ACCESS_TOKEN?.trim();
19
- if (envToken)
20
- return { token: envToken };
21
- const dbPath = getCursorStateDbPath();
22
- if (!fs.existsSync(dbPath))
23
- return null;
24
- try {
25
- const sqlite = await import('node:sqlite');
26
- const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
27
- try {
28
- const tokenRow = db
29
- .prepare("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'")
30
- .get();
31
- const emailRow = db
32
- .prepare("SELECT value FROM ItemTable WHERE key = 'cursorAuth/cachedEmail'")
33
- .get();
34
- const token = tokenRow?.value?.trim();
35
- if (!token)
36
- return null;
37
- return { token, email: emailRow?.value?.trim() };
38
- }
39
- finally {
40
- db.close();
41
- }
42
- }
43
- catch {
44
- return null;
45
- }
46
- }
47
- export async function collectCursorQuota() {
48
- const auth = await readCursorLocalAuth();
49
- if (!auth)
50
- return null;
51
- const endpoints = [
52
- 'https://api2.cursor.sh/auth/usage-summary',
53
- 'https://cursor.com/api/usage-summary',
54
- ];
55
- let data = null;
56
- for (const url of endpoints) {
57
- const res = await fetch(url, {
58
- method: 'GET',
59
- headers: {
60
- Authorization: `Bearer ${auth.token}`,
61
- Accept: 'application/json',
62
- 'User-Agent': 'tokenwallet-mcp/1.0',
63
- },
64
- signal: AbortSignal.timeout(8000),
65
- }).catch(() => null);
66
- if (res && res.ok) {
67
- data = (await res.json().catch(() => null));
68
- if (data?.individualUsage)
69
- break;
70
- }
71
- }
72
- if (!data?.individualUsage)
73
- return null;
74
- const now = Date.now();
75
- const resetsAt = toEpochMs(data.billingCycleEnd);
76
- const meters = [];
77
- const planUsage = data.individualUsage.plan;
78
- if (planUsage && typeof planUsage.limit === 'number' && planUsage.limit > 0) {
79
- const remainingRaw = typeof planUsage.remaining === 'number'
80
- ? planUsage.remaining
81
- : Math.max(0, planUsage.limit - Number(planUsage.used ?? 0));
82
- const pct = Math.max(0, Math.min(100, Math.round((remainingRaw / planUsage.limit) * 1000) / 10));
83
- meters.push({
84
- meterKey: 'month',
85
- product: 'cursor',
86
- label: '本月额度',
87
- kind: 'percent',
88
- window: 'month',
89
- remaining: pct,
90
- total: 100,
91
- unit: '%',
92
- resetsAt,
93
- observedAt: now,
94
- });
95
- }
96
- if (meters.length === 0)
97
- return null;
98
- const membership = data.membershipType?.trim();
99
- const plan = membership ? membership.charAt(0).toUpperCase() + membership.slice(1) : undefined;
100
- return {
101
- brand: 'cursor',
102
- plan,
103
- accountHint: maskEmail(auth.email),
104
- observedAt: now,
105
- source: 'cursor',
106
- meters,
107
- };
108
- }