tokenwallet-mcp 1.0.0 → 1.0.1
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 +90 -25
- package/dist/collectors/claude.js +107 -0
- package/dist/collectors/cursor.js +108 -0
- package/dist/collectors/gemini.js +112 -0
- package/dist/collectors/grok.js +42 -0
- package/dist/collectors/index.js +41 -0
- package/dist/collectors/types.js +25 -0
- package/dist/index.js +24 -17
- package/dist/server.js +51 -53
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TokenWallet MCP
|
|
2
2
|
|
|
3
|
-
|
|
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 / Gemini CLI)
|
|
6
12
|
|
|
7
|
-
### Codex CLI
|
|
8
13
|
```bash
|
|
14
|
+
# Codex CLI
|
|
9
15
|
codex mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
10
|
-
```
|
|
11
16
|
|
|
12
|
-
|
|
13
|
-
```bash
|
|
17
|
+
# Claude Code
|
|
14
18
|
claude mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
19
|
+
|
|
20
|
+
# Gemini CLI
|
|
21
|
+
gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
15
22
|
```
|
|
16
23
|
|
|
17
|
-
### Claude Desktop /
|
|
18
|
-
|
|
24
|
+
### Desktop & IDE (Cursor / Antigravity / Claude Desktop / Windsurf / Cline & more)
|
|
25
|
+
|
|
26
|
+
Add the following to your client's MCP configuration file (works with any MCP-compatible IDE or AI client):
|
|
27
|
+
|
|
19
28
|
```json
|
|
20
29
|
{
|
|
21
30
|
"mcpServers": {
|
|
@@ -27,28 +36,84 @@ claude mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
|
27
36
|
}
|
|
28
37
|
```
|
|
29
38
|
|
|
30
|
-
|
|
39
|
+
### VS Code
|
|
40
|
+
|
|
41
|
+
Add to your user or workspace `.vscode/mcp.json`:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"servers": {
|
|
46
|
+
"tokenwallet": {
|
|
47
|
+
"type": "stdio",
|
|
48
|
+
"command": "npx",
|
|
49
|
+
"args": ["-y", "tokenwallet-mcp"]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
31
56
|
|
|
32
|
-
1.
|
|
33
|
-
|
|
34
|
-
|
|
57
|
+
1. After installation, start a conversation in your AI client and say:
|
|
58
|
+
**"Connect to TokenWallet"**
|
|
59
|
+
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.
|
|
35
61
|
|
|
36
|
-
|
|
62
|
+
---
|
|
37
63
|
|
|
38
|
-
|
|
39
|
-
- `sync_codex_quota`:立即读取本机 `~/.codex/sessions` 最新真实额度并上报
|
|
40
|
-
- `report_quota`:向已绑定卡片上报自定义额度指标
|
|
41
|
-
- `check_connection_status`:检查待扫码会话与已绑定卡片
|
|
42
|
-
- `list_connections`:查看已绑定卡片及节点在线状态
|
|
64
|
+
## 简体中文
|
|
43
65
|
|
|
44
|
-
|
|
66
|
+
[TokenWallet(词元钱包)](https://token-wallet.app) 官方 MCP 服务,将你的 AI 客户端连接到词元钱包 App,自动同步额度状态。
|
|
45
67
|
|
|
46
|
-
|
|
47
|
-
- `CODEX_HOME`:自定义 Codex 数据目录,默认 `~/.codex`
|
|
48
|
-
- `TOKENWALLET_MCP_HOME`:本地节点凭证目录,默认 `~/.tokenwallet-mcp`
|
|
68
|
+
### 安装方式
|
|
49
69
|
|
|
50
|
-
|
|
70
|
+
#### 命令行客户端(Codex CLI / Claude Code / Gemini CLI)
|
|
51
71
|
|
|
52
72
|
```bash
|
|
53
|
-
|
|
73
|
+
# Codex CLI
|
|
74
|
+
codex mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
75
|
+
|
|
76
|
+
# Claude Code
|
|
77
|
+
claude mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
78
|
+
|
|
79
|
+
# Gemini CLI
|
|
80
|
+
gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
54
81
|
```
|
|
82
|
+
|
|
83
|
+
#### 桌面端与 IDE(Cursor / Antigravity / Claude Desktop / Windsurf / Cline 等)
|
|
84
|
+
|
|
85
|
+
在对应客户端的 MCP 配置文件中加入(其他任何支持 MCP 协议的 IDE 或 AI 客户端均可按相同方式配置使用):
|
|
86
|
+
|
|
87
|
+
```json
|
|
88
|
+
{
|
|
89
|
+
"mcpServers": {
|
|
90
|
+
"tokenwallet": {
|
|
91
|
+
"command": "npx",
|
|
92
|
+
"args": ["-y", "tokenwallet-mcp"]
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### VS Code
|
|
99
|
+
|
|
100
|
+
在用户或项目 `.vscode/mcp.json` 中加入:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"servers": {
|
|
105
|
+
"tokenwallet": {
|
|
106
|
+
"type": "stdio",
|
|
107
|
+
"command": "npx",
|
|
108
|
+
"args": ["-y", "tokenwallet-mcp"]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 快速开始
|
|
115
|
+
|
|
116
|
+
1. 安装完成后,在 AI 客户端对话中输入:
|
|
117
|
+
**「帮我连接 TokenWallet」**
|
|
118
|
+
2. 打开手机上的 **词元钱包(TokenWallet)** App,点击右上角 **+** → 选择对应平台 → **扫描二维码**(若无法扫码可手动输入 8 位配对码)。
|
|
119
|
+
3. 绑定完成后,额度将自动同步至你的词元钱包 App。
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
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);
|
|
86
|
+
meters.push({
|
|
87
|
+
meterKey: 'extra',
|
|
88
|
+
product: 'claude-code',
|
|
89
|
+
label: '额外额度',
|
|
90
|
+
kind: 'balance',
|
|
91
|
+
window: 'month',
|
|
92
|
+
remaining,
|
|
93
|
+
total: data.extra_usage.monthly_limit,
|
|
94
|
+
unit: 'USD',
|
|
95
|
+
observedAt: now,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (meters.length === 0)
|
|
99
|
+
return null;
|
|
100
|
+
return {
|
|
101
|
+
brand: 'claude',
|
|
102
|
+
plan: creds.plan,
|
|
103
|
+
observedAt: now,
|
|
104
|
+
source: 'claude-code',
|
|
105
|
+
meters,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
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 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
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
export async function collectGeminiQuota() {
|
|
30
|
+
const token = readGeminiAccessToken();
|
|
31
|
+
if (!token)
|
|
32
|
+
return null;
|
|
33
|
+
const res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: {
|
|
36
|
+
Authorization: `Bearer ${token}`,
|
|
37
|
+
'Content-Type': 'application/json',
|
|
38
|
+
Accept: 'application/json',
|
|
39
|
+
},
|
|
40
|
+
body: JSON.stringify({}),
|
|
41
|
+
signal: AbortSignal.timeout(8000),
|
|
42
|
+
}).catch(() => null);
|
|
43
|
+
if (!res || !res.ok)
|
|
44
|
+
return null;
|
|
45
|
+
const data = (await res.json().catch(() => null));
|
|
46
|
+
if (!data?.buckets || data.buckets.length === 0)
|
|
47
|
+
return null;
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
const proBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('pro'));
|
|
50
|
+
const flashBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('flash'));
|
|
51
|
+
const meters = [];
|
|
52
|
+
const pickLowest = (list) => list
|
|
53
|
+
.filter((b) => typeof b.remainingFraction === 'number')
|
|
54
|
+
.sort((a, b) => (a.remainingFraction ?? 1) - (b.remainingFraction ?? 1))[0];
|
|
55
|
+
const pro = pickLowest(proBuckets);
|
|
56
|
+
if (pro && typeof pro.remainingFraction === 'number') {
|
|
57
|
+
meters.push({
|
|
58
|
+
meterKey: 'pro',
|
|
59
|
+
product: 'gemini',
|
|
60
|
+
label: 'Gemini Pro',
|
|
61
|
+
kind: 'percent',
|
|
62
|
+
window: 'day',
|
|
63
|
+
modelGroup: pro.modelId,
|
|
64
|
+
remaining: Math.max(0, Math.min(100, Math.round(pro.remainingFraction * 1000) / 10)),
|
|
65
|
+
total: 100,
|
|
66
|
+
unit: '%',
|
|
67
|
+
resetsAt: toEpochMs(pro.resetTime),
|
|
68
|
+
observedAt: now,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const flash = pickLowest(flashBuckets);
|
|
72
|
+
if (flash && typeof flash.remainingFraction === 'number') {
|
|
73
|
+
meters.push({
|
|
74
|
+
meterKey: 'flash',
|
|
75
|
+
product: 'gemini',
|
|
76
|
+
label: 'Gemini Flash',
|
|
77
|
+
kind: 'percent',
|
|
78
|
+
window: 'day',
|
|
79
|
+
modelGroup: flash.modelId,
|
|
80
|
+
remaining: Math.max(0, Math.min(100, Math.round(flash.remainingFraction * 1000) / 10)),
|
|
81
|
+
total: 100,
|
|
82
|
+
unit: '%',
|
|
83
|
+
resetsAt: toEpochMs(flash.resetTime),
|
|
84
|
+
observedAt: now,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
if (meters.length === 0) {
|
|
88
|
+
const first = pickLowest(data.buckets);
|
|
89
|
+
if (first && typeof first.remainingFraction === 'number') {
|
|
90
|
+
meters.push({
|
|
91
|
+
meterKey: 'default',
|
|
92
|
+
product: 'gemini',
|
|
93
|
+
label: first.modelId || 'Google AI',
|
|
94
|
+
kind: 'percent',
|
|
95
|
+
window: 'day',
|
|
96
|
+
remaining: Math.max(0, Math.min(100, Math.round(first.remainingFraction * 1000) / 10)),
|
|
97
|
+
total: 100,
|
|
98
|
+
unit: '%',
|
|
99
|
+
resetsAt: toEpochMs(first.resetTime),
|
|
100
|
+
observedAt: now,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (meters.length === 0)
|
|
105
|
+
return null;
|
|
106
|
+
return {
|
|
107
|
+
brand: 'gemini',
|
|
108
|
+
observedAt: now,
|
|
109
|
+
source: 'gemini-cli',
|
|
110
|
+
meters,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export async function collectGrokQuota() {
|
|
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 || !res.ok)
|
|
15
|
+
return null;
|
|
16
|
+
const data = (await res.json().catch(() => null));
|
|
17
|
+
if (!data)
|
|
18
|
+
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))
|
|
22
|
+
return null;
|
|
23
|
+
// xAI billing API may return cents or dollars depending on field; normalize cleanly
|
|
24
|
+
const now = Date.now();
|
|
25
|
+
const meters = [
|
|
26
|
+
{
|
|
27
|
+
meterKey: 'balance:USD',
|
|
28
|
+
product: 'xai',
|
|
29
|
+
label: '可用余额',
|
|
30
|
+
kind: 'balance',
|
|
31
|
+
remaining: Math.round(remainingNum * 100) / 100,
|
|
32
|
+
unit: 'USD',
|
|
33
|
+
observedAt: now,
|
|
34
|
+
},
|
|
35
|
+
];
|
|
36
|
+
return {
|
|
37
|
+
brand: 'grok',
|
|
38
|
+
observedAt: now,
|
|
39
|
+
source: 'xai-billing',
|
|
40
|
+
meters,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { readLatestCodexQuota } from '../codex-reader.js';
|
|
2
|
+
import { collectClaudeQuota } from './claude.js';
|
|
3
|
+
import { collectCursorQuota } from './cursor.js';
|
|
4
|
+
import { collectGeminiQuota } from './gemini.js';
|
|
5
|
+
import { collectGrokQuota } from './grok.js';
|
|
6
|
+
export async function collectQuotaForBrand(brand) {
|
|
7
|
+
switch (brand) {
|
|
8
|
+
case 'openai': {
|
|
9
|
+
const codex = readLatestCodexQuota();
|
|
10
|
+
if (!codex)
|
|
11
|
+
return null;
|
|
12
|
+
return {
|
|
13
|
+
brand: 'openai',
|
|
14
|
+
plan: codex.plan,
|
|
15
|
+
observedAt: codex.observedAt,
|
|
16
|
+
source: 'codex',
|
|
17
|
+
meters: codex.meters,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
case 'claude':
|
|
21
|
+
return collectClaudeQuota();
|
|
22
|
+
case 'cursor':
|
|
23
|
+
return collectCursorQuota();
|
|
24
|
+
case 'gemini':
|
|
25
|
+
return collectGeminiQuota();
|
|
26
|
+
case 'grok':
|
|
27
|
+
return collectGrokQuota();
|
|
28
|
+
default:
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
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,25 @@
|
|
|
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
|
+
export function toRemainingPercent(usedPercent) {
|
|
11
|
+
if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent))
|
|
12
|
+
return undefined;
|
|
13
|
+
const remaining = Math.max(0, Math.min(100, 100 - usedPercent));
|
|
14
|
+
return Math.round(remaining * 10) / 10;
|
|
15
|
+
}
|
|
16
|
+
export function toEpochMs(raw) {
|
|
17
|
+
if (typeof raw === 'string' && raw.trim()) {
|
|
18
|
+
const parsed = Date.parse(raw);
|
|
19
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
20
|
+
}
|
|
21
|
+
if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
|
|
22
|
+
return raw < 1_000_000_000_000 ? Math.round(raw * 1000) : Math.round(raw);
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import http from 'node:http';
|
|
|
3
3
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
4
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
5
5
|
import { apiSubmitReport } from './api.js';
|
|
6
|
-
import {
|
|
6
|
+
import { collectQuotaForBrand } from './collectors/index.js';
|
|
7
7
|
import { getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
|
|
8
8
|
import { createTokenWalletMcpServer } from './server.js';
|
|
9
9
|
function parseArgs() {
|
|
@@ -15,27 +15,34 @@ function parseArgs() {
|
|
|
15
15
|
8788;
|
|
16
16
|
return { useHttp, port };
|
|
17
17
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
18
|
+
function startLocalAutoReporter() {
|
|
19
|
+
const lastFingerprintByCard = new Map();
|
|
20
20
|
const tick = async () => {
|
|
21
21
|
try {
|
|
22
|
-
const snap = readLatestCodexQuota();
|
|
23
|
-
if (!snap || snap.observedAt <= lastObservedAt)
|
|
24
|
-
return;
|
|
25
22
|
const cfg = loadConfig();
|
|
26
|
-
|
|
27
|
-
if (openaiConns.length === 0)
|
|
23
|
+
if (cfg.connections.length === 0)
|
|
28
24
|
return;
|
|
29
25
|
const baseUrl = getApiBaseUrl();
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
+
}
|
|
37
45
|
}
|
|
38
|
-
lastObservedAt = snap.observedAt;
|
|
39
46
|
}
|
|
40
47
|
catch {
|
|
41
48
|
// Ignore transient network errors during background sync
|
|
@@ -51,7 +58,7 @@ async function startStdio() {
|
|
|
51
58
|
const server = createTokenWalletMcpServer();
|
|
52
59
|
const transport = new StdioServerTransport();
|
|
53
60
|
await server.connect(transport);
|
|
54
|
-
|
|
61
|
+
startLocalAutoReporter();
|
|
55
62
|
console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
|
|
56
63
|
}
|
|
57
64
|
async function startHttp(port) {
|
package/dist/server.js
CHANGED
|
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
2
2
|
import QRCode from 'qrcode';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { apiCreateMcpSession, apiPingNode, apiPollMcpSession, apiSubmitReport, } from './api.js';
|
|
5
|
-
import {
|
|
5
|
+
import { collectQuotaForBrand } from './collectors/index.js';
|
|
6
6
|
import { getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
|
|
7
7
|
const meterSchema = z.object({
|
|
8
8
|
meterKey: z.string().min(1).describe('Unique meter key, e.g. "5h", "7d", "balance:USD"'),
|
|
@@ -86,29 +86,29 @@ export function createTokenWalletMcpServer() {
|
|
|
86
86
|
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
87
|
inputSchema: {
|
|
88
88
|
brand: z
|
|
89
|
-
.enum(['openai', 'claude', 'gemini', 'openrouter', 'deepseek', 'other'])
|
|
89
|
+
.enum(['openai', 'claude', 'gemini', 'cursor', 'grok', 'openrouter', 'deepseek', 'other'])
|
|
90
90
|
.default('openai')
|
|
91
|
-
.describe('Provider brand (
|
|
91
|
+
.describe('Provider brand (openai, claude, gemini, cursor, grok, openrouter, deepseek, other)'),
|
|
92
92
|
provider: z.string().optional().describe('Custom display name for the provider'),
|
|
93
93
|
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"'),
|
|
94
|
+
source: z.string().optional().describe('Client source identifier, e.g. "chatgpt", "codex", "claude-code", "cursor", "gemini-cli"'),
|
|
95
95
|
plan: z.string().optional().describe('Subscription plan name, e.g. "Plus", "Pro", "AI Pro"'),
|
|
96
96
|
accountHint: z.string().optional().describe('Optional masked account hint, e.g. "u***@gmail.com"'),
|
|
97
97
|
meters: z.array(meterSchema).optional().describe('Optional initial quota meters to populate immediately upon scan'),
|
|
98
98
|
},
|
|
99
99
|
}, async (args) => {
|
|
100
100
|
const baseUrl = getApiBaseUrl();
|
|
101
|
-
const
|
|
102
|
-
?
|
|
101
|
+
const localQuota = !args.meters || args.meters.length === 0
|
|
102
|
+
? await collectQuotaForBrand(args.brand)
|
|
103
103
|
: null;
|
|
104
104
|
const created = await apiCreateMcpSession(baseUrl, {
|
|
105
105
|
brand: args.brand,
|
|
106
106
|
provider: args.provider,
|
|
107
107
|
nodeLabel: args.nodeLabel,
|
|
108
|
-
source: args.source ??
|
|
109
|
-
plan: args.plan ??
|
|
110
|
-
accountHint: args.accountHint,
|
|
111
|
-
meters: args.meters ??
|
|
108
|
+
source: args.source ?? localQuota?.source ?? 'mcp',
|
|
109
|
+
plan: args.plan ?? localQuota?.plan,
|
|
110
|
+
accountHint: args.accountHint ?? localQuota?.accountHint,
|
|
111
|
+
meters: args.meters ?? localQuota?.meters,
|
|
112
112
|
});
|
|
113
113
|
const pending = {
|
|
114
114
|
sessionId: created.sessionId,
|
|
@@ -245,63 +245,61 @@ export function createTokenWalletMcpServer() {
|
|
|
245
245
|
],
|
|
246
246
|
};
|
|
247
247
|
});
|
|
248
|
-
server.registerTool('
|
|
249
|
-
title: 'Sync Real Local
|
|
250
|
-
description: '
|
|
248
|
+
server.registerTool('sync_local_quotas', {
|
|
249
|
+
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.',
|
|
251
251
|
inputSchema: {
|
|
252
|
-
|
|
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'),
|
|
256
|
+
cardId: z.string().optional().describe('Optional specific bound cardId'),
|
|
253
257
|
},
|
|
254
|
-
}, async ({ cardId }) => {
|
|
258
|
+
}, async ({ brand, cardId }) => {
|
|
255
259
|
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
260
|
const cfg = loadConfig();
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
261
|
+
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) {
|
|
273
266
|
return {
|
|
274
267
|
isError: true,
|
|
275
268
|
content: [
|
|
276
269
|
{
|
|
277
270
|
type: 'text',
|
|
278
|
-
text:
|
|
271
|
+
text: '尚未绑定任何 TokenWallet 卡片。请先调用 connect_tokenwallet 生成二维码并在手机 App 中扫码绑定。',
|
|
279
272
|
},
|
|
280
273
|
],
|
|
281
274
|
};
|
|
282
275
|
}
|
|
283
|
-
const
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
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
|
+
}
|
|
298
301
|
return {
|
|
299
|
-
content: [
|
|
300
|
-
{
|
|
301
|
-
type: 'text',
|
|
302
|
-
text: `已同步本机真实 Codex 额度到 ${conn.provider}(cardId=${res.cardId}):${details}`,
|
|
303
|
-
},
|
|
304
|
-
],
|
|
302
|
+
content: [{ type: 'text', text: lines.join('\n') }],
|
|
305
303
|
};
|
|
306
304
|
});
|
|
307
305
|
server.registerTool('list_connections', {
|