tokenwallet-mcp 1.0.0 → 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
@@ -1,54 +1,148 @@
1
- # tokenwallet-mcp
1
+ # TokenWallet MCP
2
2
 
3
- TokenWallet 官方 MCP Server。安装后通过手机 App 扫码绑定,即可**自动读取本机 AI 客户端(如 Codex CLI)的真实剩余额度与重置时间**并定时同步到 TokenWallet App,无需每次对话手动触发。
3
+ Official MCP server for [TokenWallet](https://token-wallet.app) — connect your AI clients to the TokenWallet app and keep your token quotas in sync automatically.
4
4
 
5
- ## 一行命令安装(推荐)
5
+ [简体中文](#简体中文)
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ ### CLI (Codex CLI / Claude Code)
6
12
 
7
- ### Codex CLI
8
13
  ```bash
9
- codex mcp add tokenwallet -- npx -y tokenwallet-mcp
14
+ # Codex CLI
15
+ codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
16
+
17
+ # Claude Code
18
+ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
19
+ ```
20
+
21
+ ### Desktop & IDE (Claude Desktop / Windsurf / Cline & more)
22
+
23
+ Add the following to your client's MCP configuration file and replace `<provider>` with the provider ID, such as `claude`.
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "tokenwallet": {
29
+ "command": "npx",
30
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ ### VS Code
37
+
38
+ Add to your user or workspace `.vscode/mcp.json`:
39
+
40
+ ```json
41
+ {
42
+ "servers": {
43
+ "tokenwallet": {
44
+ "type": "stdio",
45
+ "command": "npx",
46
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
47
+ }
48
+ }
49
+ }
10
50
  ```
11
51
 
12
- ### Claude Code
52
+ ## Quick Start
53
+
54
+ 1. After installation, start a conversation in your AI client and say:
55
+ **"Connect to TokenWallet"**
56
+ 2. Open the **TokenWallet** app on your phone, tap **+** → select the platform → **Scan QR Code** (or enter the 8-character pairing code manually).
57
+ 3. After pairing, view your quota in TokenWallet.
58
+
59
+ ---
60
+
61
+ ## 简体中文
62
+
63
+ [TokenWallet(词元钱包)](https://token-wallet.app) 官方 MCP 服务,将你的 AI 客户端连接到词元钱包 App,自动同步额度状态。
64
+
65
+ ### 安装方式
66
+
67
+ #### 命令行客户端(Codex CLI / Claude Code)
68
+
13
69
  ```bash
14
- claude mcp add tokenwallet -- npx -y tokenwallet-mcp
70
+ # Codex CLI
71
+ codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
72
+
73
+ # Claude Code
74
+ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
15
75
  ```
16
76
 
17
- ### Claude Desktop / Cursor
18
- 在 MCP 配置文件中添加:
77
+ #### 桌面端与 IDE(Claude Desktop / Windsurf / Cline 等)
78
+
79
+ 在对应客户端的 MCP 配置文件中加入(其他任何支持 MCP 协议的 IDE 或 AI 客户端均可按相同方式配置使用):
80
+
19
81
  ```json
20
82
  {
21
83
  "mcpServers": {
22
84
  "tokenwallet": {
23
85
  "command": "npx",
24
- "args": ["-y", "tokenwallet-mcp"]
86
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
25
87
  }
26
88
  }
27
89
  }
28
90
  ```
29
91
 
30
- ## 使用方式
92
+ #### VS Code
31
93
 
32
- 1. 安装完成后,在客户端对话中说:**「帮我连接 TokenWallet,生成绑定二维码」**;
33
- 2. 打开手机 TokenWallet App → 点击 `+` → 选择对应平台 → 点击「扫描二维码」完成绑定(支持免登录直接扫码);
34
- 3. 绑定后,本机 MCP 会每 60 秒自动检测最新真实额度并静默上报到 `https://api.token-wallet.app/v1`。
94
+ 在用户或项目 `.vscode/mcp.json` 中加入:
35
95
 
36
- ## 提供的工具
96
+ ```json
97
+ {
98
+ "servers": {
99
+ "tokenwallet": {
100
+ "type": "stdio",
101
+ "command": "npx",
102
+ "args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ 将配置中的 `<provider>` 替换为对应的供应商 ID,例如 `claude`。
109
+
110
+ ### 快速开始
111
+
112
+ 1. 安装完成后,在 AI 客户端对话中输入:
113
+ **「帮我连接 TokenWallet」**
114
+ 2. 打开手机上的 **词元钱包(TokenWallet)** App,点击右上角 **+** → 选择对应平台 → **扫描二维码**(若无法扫码可手动输入 8 位配对码)。
115
+ 3. 配对完成后,在词元钱包中查看额度。
116
+
117
+ ### 发布 npm 新版本
37
118
 
38
- - `connect_tokenwallet`:生成配对二维码与链接(若本机有 Codex 日志会自动附带当前真实 5h / 周额度与精确重置时间)
39
- - `sync_codex_quota`:立即读取本机 `~/.codex/sessions` 最新真实额度并上报
40
- - `report_quota`:向已绑定卡片上报自定义额度指标
41
- - `check_connection_status`:检查待扫码会话与已绑定卡片
42
- - `list_connections`:查看已绑定卡片及节点在线状态
119
+ #### 首次配置
43
120
 
44
- ## 环境变量
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
+ ```
45
141
 
46
- - `TOKENWALLET_API_URL`:后端 API 地址,默认 `https://api.token-wallet.app/v1`
47
- - `CODEX_HOME`:自定义 Codex 数据目录,默认 `~/.codex`
48
- - `TOKENWALLET_MCP_HOME`:本地节点凭证目录,默认 `~/.tokenwallet-mcp`
142
+ `npm version patch` 会更新 `package.json` 和 `package-lock.json`,并创建版本提交和标签。以后发版时,把最后一条命令里的 `v1.0.2` 换成 `npm version` 输出的标签。
49
143
 
50
- ## 自托管远程模式(Streamable HTTP)
144
+ 标签推送后,在 GitHub 的 **Actions → Publish to npm** 查看结果。流水线会核对标签、运行类型检查和测试,再构建并发布。成功后执行以下命令,确认输出为刚发布的版本号:
51
145
 
52
146
  ```bash
53
- npx -y tokenwallet-mcp --http --port 8788
147
+ npm view tokenwallet-mcp@latest version
54
148
  ```
@@ -0,0 +1,108 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { toEpochMs, toRemainingPercent } from './types.js';
5
+ function readClaudeCredentials() {
6
+ const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
7
+ if (envToken)
8
+ return { token: envToken };
9
+ const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
10
+ const credFile = path.join(configDir, '.credentials.json');
11
+ if (!fs.existsSync(credFile))
12
+ return null;
13
+ try {
14
+ const parsed = JSON.parse(fs.readFileSync(credFile, 'utf8'));
15
+ const token = parsed.claudeAiOauth?.accessToken?.trim();
16
+ if (!token)
17
+ return null;
18
+ const sub = parsed.claudeAiOauth?.subscriptionType;
19
+ const plan = sub ? sub.charAt(0).toUpperCase() + sub.slice(1) : undefined;
20
+ return { token, plan };
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ export async function collectClaudeQuota() {
27
+ const creds = readClaudeCredentials();
28
+ if (!creds)
29
+ return null;
30
+ const res = await fetch('https://api.anthropic.com/api/oauth/usage', {
31
+ method: 'GET',
32
+ headers: {
33
+ Authorization: `Bearer ${creds.token}`,
34
+ 'anthropic-beta': 'oauth-2025-04-20',
35
+ Accept: 'application/json',
36
+ 'User-Agent': 'tokenwallet-mcp/1.0',
37
+ },
38
+ signal: AbortSignal.timeout(8000),
39
+ }).catch(() => null);
40
+ if (!res || !res.ok)
41
+ return null;
42
+ const data = (await res.json().catch(() => null));
43
+ if (!data)
44
+ return null;
45
+ const now = Date.now();
46
+ const meters = [];
47
+ if (data.five_hour && typeof data.five_hour.utilization === 'number') {
48
+ const remaining = toRemainingPercent(data.five_hour.utilization);
49
+ if (remaining !== undefined) {
50
+ meters.push({
51
+ meterKey: '5h',
52
+ product: 'claude-code',
53
+ label: '5 小时',
54
+ kind: 'percent',
55
+ window: '5h',
56
+ remaining,
57
+ total: 100,
58
+ unit: '%',
59
+ resetsAt: toEpochMs(data.five_hour.resets_at),
60
+ observedAt: now,
61
+ });
62
+ }
63
+ }
64
+ if (data.seven_day && typeof data.seven_day.utilization === 'number') {
65
+ const remaining = toRemainingPercent(data.seven_day.utilization);
66
+ if (remaining !== undefined) {
67
+ meters.push({
68
+ meterKey: '7d',
69
+ product: 'claude-code',
70
+ label: '每周额度',
71
+ kind: 'percent',
72
+ window: 'week',
73
+ remaining,
74
+ total: 100,
75
+ unit: '%',
76
+ resetsAt: toEpochMs(data.seven_day.resets_at),
77
+ observedAt: now,
78
+ });
79
+ }
80
+ }
81
+ if (data.extra_usage?.is_enabled &&
82
+ typeof data.extra_usage.monthly_limit === 'number' &&
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);
87
+ meters.push({
88
+ meterKey: 'extra',
89
+ product: 'claude-code',
90
+ label: '额外额度',
91
+ kind: 'balance',
92
+ window: 'month',
93
+ remaining,
94
+ total: data.extra_usage.monthly_limit / 100,
95
+ unit: 'USD',
96
+ observedAt: now,
97
+ });
98
+ }
99
+ if (meters.length === 0)
100
+ return null;
101
+ return {
102
+ brand: 'claude',
103
+ plan: creds.plan,
104
+ observedAt: now,
105
+ source: 'claude-code',
106
+ meters,
107
+ };
108
+ }
@@ -0,0 +1,141 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { toEpochMs } from './types.js';
5
+ function readGeminiAccessToken() {
6
+ const envToken = process.env.GEMINI_OAUTH_TOKEN?.trim();
7
+ if (envToken)
8
+ return envToken;
9
+ const geminiHome = process.env.GEMINI_CLI_HOME || path.join(os.homedir(), '.gemini');
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;
19
+ }
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 };
46
+ }
47
+ export async function collectGeminiQuota() {
48
+ const token = readGeminiAccessToken();
49
+ if (!token)
50
+ return null;
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', {
58
+ method: 'POST',
59
+ headers,
60
+ body: JSON.stringify(project ? { project } : {}),
61
+ signal: AbortSignal.timeout(8000),
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
+ }
71
+ if (!res || !res.ok)
72
+ return null;
73
+ const data = (await res.json().catch(() => null));
74
+ if (!data?.buckets || data.buckets.length === 0)
75
+ return null;
76
+ const now = Date.now();
77
+ const proBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('pro'));
78
+ const flashBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('flash'));
79
+ const meters = [];
80
+ const pickLowest = (list) => list
81
+ .filter((b) => typeof b.remainingFraction === 'number' && Number.isFinite(b.remainingFraction))
82
+ .sort((a, b) => (a.remainingFraction ?? 1) - (b.remainingFraction ?? 1))[0];
83
+ const pro = pickLowest(proBuckets);
84
+ if (pro && typeof pro.remainingFraction === 'number') {
85
+ meters.push({
86
+ meterKey: 'pro',
87
+ product: 'gemini',
88
+ label: 'Gemini Pro',
89
+ kind: 'percent',
90
+ window: 'day',
91
+ modelGroup: pro.modelId,
92
+ remaining: Math.max(0, Math.min(100, Math.round(pro.remainingFraction * 1000) / 10)),
93
+ total: 100,
94
+ unit: '%',
95
+ resetsAt: toEpochMs(pro.resetTime),
96
+ observedAt: now,
97
+ });
98
+ }
99
+ const flash = pickLowest(flashBuckets);
100
+ if (flash && typeof flash.remainingFraction === 'number') {
101
+ meters.push({
102
+ meterKey: 'flash',
103
+ product: 'gemini',
104
+ label: 'Gemini Flash',
105
+ kind: 'percent',
106
+ window: 'day',
107
+ modelGroup: flash.modelId,
108
+ remaining: Math.max(0, Math.min(100, Math.round(flash.remainingFraction * 1000) / 10)),
109
+ total: 100,
110
+ unit: '%',
111
+ resetsAt: toEpochMs(flash.resetTime),
112
+ observedAt: now,
113
+ });
114
+ }
115
+ if (meters.length === 0) {
116
+ const first = pickLowest(data.buckets);
117
+ if (first && typeof first.remainingFraction === 'number') {
118
+ meters.push({
119
+ meterKey: 'default',
120
+ product: 'gemini',
121
+ label: first.modelId || 'Gemini',
122
+ kind: 'percent',
123
+ window: 'day',
124
+ remaining: Math.max(0, Math.min(100, Math.round(first.remainingFraction * 1000) / 10)),
125
+ total: 100,
126
+ unit: '%',
127
+ resetsAt: toEpochMs(first.resetTime),
128
+ observedAt: now,
129
+ });
130
+ }
131
+ }
132
+ if (meters.length === 0)
133
+ return null;
134
+ return {
135
+ brand: 'gemini',
136
+ plan,
137
+ observedAt: now,
138
+ source: 'gemini-cli',
139
+ meters,
140
+ };
141
+ }
@@ -0,0 +1,32 @@
1
+ import { readLatestCodexQuota } from '../codex-reader.js';
2
+ import { collectClaudeQuota } from './claude.js';
3
+ import { collectGeminiQuota } from './gemini.js';
4
+ import { collectMuseCodeQuota } from './muse-code.js';
5
+ import { collectXaiQuota } from './xai.js';
6
+ import { readStatusQuota } from './status-quota.js';
7
+ export async function collectQuotaForBrand(brand) {
8
+ switch (brand) {
9
+ case 'openai': {
10
+ const codex = readLatestCodexQuota();
11
+ if (!codex)
12
+ return null;
13
+ return {
14
+ brand: 'openai',
15
+ plan: codex.plan,
16
+ observedAt: codex.observedAt,
17
+ source: 'codex',
18
+ meters: codex.meters,
19
+ };
20
+ }
21
+ case 'claude':
22
+ return readStatusQuota('claude') ?? collectClaudeQuota();
23
+ case 'gemini':
24
+ return readStatusQuota('gemini') ?? collectGeminiQuota();
25
+ case 'muse-code':
26
+ return collectMuseCodeQuota();
27
+ case 'xai':
28
+ return collectXaiQuota();
29
+ default:
30
+ return null;
31
+ }
32
+ }
@@ -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
+ }
@@ -0,0 +1,16 @@
1
+ export function toRemainingPercent(usedPercent) {
2
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent))
3
+ return undefined;
4
+ const remaining = Math.max(0, Math.min(100, 100 - usedPercent));
5
+ return Math.round(remaining * 10) / 10;
6
+ }
7
+ export function toEpochMs(raw) {
8
+ if (typeof raw === 'string' && raw.trim()) {
9
+ const parsed = Date.parse(raw);
10
+ return Number.isFinite(parsed) ? parsed : undefined;
11
+ }
12
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
13
+ return raw < 1_000_000_000_000 ? Math.round(raw * 1000) : Math.round(raw);
14
+ }
15
+ return undefined;
16
+ }
@@ -0,0 +1,46 @@
1
+ export async function collectXaiQuota() {
2
+ const mgmtKey = process.env.XAI_MANAGEMENT_API_KEY?.trim();
3
+ const teamId = process.env.XAI_TEAM_ID?.trim();
4
+ if (!mgmtKey || !teamId)
5
+ return null;
6
+ const res = await fetch(`https://management-api.x.ai/v1/billing/teams/${encodeURIComponent(teamId)}/prepaid/balance`, {
7
+ method: 'GET',
8
+ headers: {
9
+ Authorization: `Bearer ${mgmtKey}`,
10
+ Accept: 'application/json',
11
+ },
12
+ signal: AbortSignal.timeout(8000),
13
+ }).catch(() => null);
14
+ if (!res)
15
+ throw new Error('无法连接 xAI Management API,请检查本机网络。');
16
+ if (!res.ok)
17
+ throw new Error('xAI 账单查询失败(HTTP ' + res.status + '),请检查团队 ID 和管理密钥的账单读取权限。');
18
+ const data = (await res.json().catch(() => null));
19
+ if (!data)
20
+ return null;
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))
26
+ return null;
27
+ // Prepaid credits are negative entries on the USD-cent ledger.
28
+ const now = Date.now();
29
+ const meters = [
30
+ {
31
+ meterKey: 'balance:USD',
32
+ product: 'xai',
33
+ label: '可用余额',
34
+ kind: 'balance',
35
+ remaining: Math.max(0, -cents / 100),
36
+ unit: 'USD',
37
+ observedAt: now,
38
+ },
39
+ ];
40
+ return {
41
+ brand: 'xai',
42
+ observedAt: now,
43
+ source: 'xai-billing',
44
+ meters,
45
+ };
46
+ }
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
- import { readLatestCodexQuota } from './codex-reader.js';
7
- import { getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
7
+ import { collectQuotaForBrand } from './collectors/index.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);
@@ -15,50 +16,67 @@ function parseArgs() {
15
16
  8788;
16
17
  return { useHttp, port };
17
18
  }
18
- function startLocalCodexAutoReporter() {
19
- let lastObservedAt = 0;
19
+ function startLocalAutoReporter() {
20
+ const lastFingerprintByCard = new Map();
20
21
  const tick = async () => {
21
22
  try {
22
- const snap = readLatestCodexQuota();
23
- if (!snap || snap.observedAt <= lastObservedAt)
24
- return;
25
23
  const cfg = loadConfig();
26
- const openaiConns = cfg.connections.filter((c) => c.brand === 'openai');
27
- if (openaiConns.length === 0)
24
+ if (cfg.connections.length === 0)
28
25
  return;
29
26
  const baseUrl = getApiBaseUrl();
30
- for (const conn of openaiConns) {
31
- await apiSubmitReport(baseUrl, conn.writeToken, {
32
- plan: snap.plan,
33
- observedAt: snap.observedAt,
34
- meters: snap.meters,
35
- });
36
- markConnectionReported(conn.cardId, Date.now());
37
- }
38
- lastObservedAt = snap.observedAt;
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);
39
52
  }
40
53
  catch {
41
54
  // Ignore transient network errors during background sync
42
55
  }
43
56
  };
44
- void tick();
45
- const timer = setInterval(() => {
46
- void tick();
47
- }, 60_000);
48
- 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();
49
62
  }
50
63
  async function startStdio() {
51
64
  const server = createTokenWalletMcpServer();
52
65
  const transport = new StdioServerTransport();
53
66
  await server.connect(transport);
54
- startLocalCodexAutoReporter();
67
+ startLocalAutoReporter();
55
68
  console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
56
69
  }
57
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);
58
76
  const httpServer = http.createServer(async (req, res) => {
59
77
  res.setHeader('Access-Control-Allow-Origin', '*');
60
78
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
61
- 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');
62
80
  if (req.method === 'OPTIONS') {
63
81
  res.writeHead(204);
64
82
  res.end();
@@ -81,6 +99,11 @@ async function startHttp(port) {
81
99
  return;
82
100
  }
83
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
+ }
84
107
  try {
85
108
  const server = createTokenWalletMcpServer();
86
109
  const transport = new StreamableHTTPServerTransport({
@@ -111,6 +134,7 @@ async function startHttp(port) {
111
134
  console.log(`[tokenwallet-mcp] TokenWallet API: ${getApiBaseUrl()}`);
112
135
  });
113
136
  }
137
+ configuredProvider();
114
138
  const { useHttp, port } = parseArgs();
115
139
  if (useHttp) {
116
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
- import { readLatestCodexQuota } from './codex-reader.js';
6
- import { getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
9
+ import { collectQuotaForBrand } from './collectors/index.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', 'openrouter', 'deepseek', 'other'])
90
- .default('openai')
91
- .describe('Provider brand (use "openai" for ChatGPT, "claude" for Claude, "gemini" for Google AI, "other" for custom)'),
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"'),
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 localCodex = args.brand === 'openai' && (!args.meters || args.meters.length === 0)
102
- ? readLatestCodexQuota()
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
- source: args.source ?? (localCodex ? 'codex' : 'mcp'),
109
- plan: args.plan ?? localCodex?.plan,
110
- accountHint: args.accountHint,
111
- meters: args.meters ?? localCodex?.meters,
125
+ source: args.source ?? localQuota?.source ?? 'mcp',
126
+ plan: args.plan ?? localQuota?.plan,
127
+ accountHint: args.accountHint ?? localQuota?.accountHint,
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,69 +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
- server.registerTool('sync_codex_quota', {
249
- title: 'Sync Real Local Codex CLI Quota',
250
- description: 'Read the latest real 5-hour and weekly rate_limits (with exact reset timestamps) from local ~/.codex/sessions logs and push them to the bound ChatGPT/OpenAI card in TokenWallet.',
270
+ server.registerTool('sync_local_quotas', {
271
+ title: 'Sync Real Local AI Client Quotas',
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
- cardId: z.string().optional().describe('Optional target cardId (defaults to bound openai card)'),
274
+ provider: z.literal(provider).optional(),
275
+ cardId: z.string().optional().describe('Optional specific bound cardId'),
253
276
  },
254
277
  }, async ({ cardId }) => {
255
278
  await syncAllPendingSessions();
256
- const snapshot = readLatestCodexQuota();
257
- if (!snapshot) {
258
- return {
259
- isError: true,
260
- content: [
261
- {
262
- type: 'text',
263
- text: '未在本机 ~/.codex/sessions 中找到有效的 Codex rate_limits 记录。请确认本 MCP 以本地 stdio 模式运行,且本机已使用过 Codex CLI。',
264
- },
265
- ],
266
- };
267
- }
268
279
  const cfg = loadConfig();
269
- const conn = (cardId && cfg.connections.find((c) => c.cardId === cardId)) ||
270
- cfg.connections.find((c) => c.brand === 'openai') ||
271
- cfg.connections[0];
272
- if (!conn) {
273
- return {
274
- isError: true,
275
- content: [
276
- {
277
- type: 'text',
278
- text: `已读取本机真实 Codex 额度(${snapshot.meters.map((m) => `${m.label}: ${m.remaining}%`).join(',')}),但尚未绑定 TokenWallet 卡片。请先调用 connect_tokenwallet 扫码绑定。`,
279
- },
280
- ],
281
- };
282
- }
283
280
  const baseUrl = getApiBaseUrl();
284
- const res = await apiSubmitReport(baseUrl, conn.writeToken, {
285
- plan: snapshot.plan,
286
- observedAt: snapshot.observedAt,
287
- meters: snapshot.meters,
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,
288
290
  });
289
291
  markConnectionReported(conn.cardId, Date.now());
290
- const details = snapshot.meters
291
- .map((m) => {
292
- const resetStr = m.resetsAt
293
- ? `(重置:${new Date(m.resetsAt).toLocaleString('zh-CN', { hour12: false })})`
294
- : '';
295
- return `${m.label} ${m.remaining}%${resetStr}`;
296
- })
297
- .join(';');
298
- return {
299
- content: [
300
- {
301
- type: 'text',
302
- text: `已同步本机真实 Codex 额度到 ${conn.provider}(cardId=${res.cardId}):${details}`,
303
- },
304
- ],
305
- };
292
+ return { content: [{ type: 'text', text: '额度已同步至钱包。' }] };
306
293
  });
307
294
  server.registerTool('list_connections', {
308
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.0",
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": {