tokenwallet-mcp 1.0.1 → 1.0.3
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 +60 -21
- package/dist/collectors/claude.js +5 -4
- package/dist/collectors/gemini.js +55 -26
- package/dist/collectors/index.js +9 -18
- package/dist/collectors/muse-code.js +58 -0
- package/dist/collectors/status-quota.js +61 -0
- package/dist/collectors/types.js +0 -9
- package/dist/collectors/{grok.js → xai.js} +13 -9
- package/dist/config.js +57 -32
- package/dist/index.js +48 -32
- package/dist/server.js +147 -115
- package/dist/statusline.js +15 -0
- package/dist/update.js +69 -0
- package/package.json +3 -2
- package/dist/collectors/cursor.js +0 -108
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 { explicitProvider, 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,57 +16,66 @@ function parseArgs() {
|
|
|
15
16
|
8788;
|
|
16
17
|
return { useHttp, port };
|
|
17
18
|
}
|
|
18
|
-
function startLocalAutoReporter() {
|
|
19
|
+
function startLocalAutoReporter(provider) {
|
|
19
20
|
const lastFingerprintByCard = new Map();
|
|
20
21
|
const tick = async () => {
|
|
21
22
|
try {
|
|
22
|
-
const cfg = loadConfig();
|
|
23
|
+
const cfg = loadConfig(provider);
|
|
23
24
|
if (cfg.connections.length === 0)
|
|
24
25
|
return;
|
|
25
|
-
const baseUrl = getApiBaseUrl();
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
26
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
27
|
+
const [conn] = cfg.connections;
|
|
28
|
+
const snap = await collectQuotaForBrand(provider);
|
|
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(), provider);
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
void
|
|
54
|
-
}
|
|
55
|
-
|
|
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
|
-
const server = createTokenWalletMcpServer();
|
|
64
|
+
const server = createTokenWalletMcpServer(startLocalAutoReporter);
|
|
59
65
|
const transport = new StdioServerTransport();
|
|
60
66
|
await server.connect(transport);
|
|
61
|
-
startLocalAutoReporter();
|
|
62
67
|
console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
|
|
63
68
|
}
|
|
64
69
|
async function startHttp(port) {
|
|
70
|
+
const secret = process.env.TOKENWALLET_HTTP_TOKEN?.trim();
|
|
71
|
+
if (!secret)
|
|
72
|
+
throw new Error('HTTP MCP 需要为此实例设置独立 TOKENWALLET_HTTP_TOKEN,并在客户端使用 Bearer 认证。');
|
|
73
|
+
const digest = (s) => createHash('sha256').update(s).digest();
|
|
74
|
+
const expected = digest('Bearer ' + secret);
|
|
65
75
|
const httpServer = http.createServer(async (req, res) => {
|
|
66
76
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
67
77
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
68
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Mcp-Session-Id');
|
|
78
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, Mcp-Session-Id');
|
|
69
79
|
if (req.method === 'OPTIONS') {
|
|
70
80
|
res.writeHead(204);
|
|
71
81
|
res.end();
|
|
@@ -88,6 +98,11 @@ async function startHttp(port) {
|
|
|
88
98
|
return;
|
|
89
99
|
}
|
|
90
100
|
if (pathname === '/' || pathname === '/mcp') {
|
|
101
|
+
if (!timingSafeEqual(expected, digest(req.headers.authorization ?? ''))) {
|
|
102
|
+
res.writeHead(401, { 'WWW-Authenticate': 'Bearer' });
|
|
103
|
+
res.end();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
91
106
|
try {
|
|
92
107
|
const server = createTokenWalletMcpServer();
|
|
93
108
|
const transport = new StreamableHTTPServerTransport({
|
|
@@ -118,6 +133,7 @@ async function startHttp(port) {
|
|
|
118
133
|
console.log(`[tokenwallet-mcp] TokenWallet API: ${getApiBaseUrl()}`);
|
|
119
134
|
});
|
|
120
135
|
}
|
|
136
|
+
explicitProvider();
|
|
121
137
|
const { useHttp, port } = parseArgs();
|
|
122
138
|
if (useHttp) {
|
|
123
139
|
await startHttp(port);
|
package/dist/server.js
CHANGED
|
@@ -3,12 +3,20 @@ import QRCode from 'qrcode';
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { apiCreateMcpSession, apiPingNode, apiPollMcpSession, apiSubmitReport, } from './api.js';
|
|
5
5
|
import { collectQuotaForBrand } from './collectors/index.js';
|
|
6
|
-
import { getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
|
|
6
|
+
import { explicitProvider, getApiBaseUrl, loadConfig, markConnectionReported, providerForClient, providerIds, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
|
|
7
|
+
import { checkForUpdates, describeUpdate, packageVersion, updatePrompt } from './update.js';
|
|
8
|
+
const sourceHelp = {
|
|
9
|
+
claude: '登录本机 Claude Code,或设置 Claude statusLine 采集器并完成一个回合。',
|
|
10
|
+
gemini: '先在本机终端登录 Gemini CLI(生成 ~/.gemini/oauth_creds.json),或配置 Gemini CLI statusLine 采集器。',
|
|
11
|
+
'muse-code': '请在本机登录 Muse Code 订阅账号(CLI 1.4.13 或更新版本),并运行 muse usage --json 确认能读到套餐额度。',
|
|
12
|
+
xai: '检查 XAI_MANAGEMENT_API_KEY 的账单权限和 XAI_TEAM_ID。',
|
|
13
|
+
other: '自定义卡片由客户端从额度来源读取余量,再调用 report_quota 上报。可在客户端配置定时任务或用量事件来触发。',
|
|
14
|
+
};
|
|
7
15
|
const meterSchema = z.object({
|
|
8
16
|
meterKey: z.string().min(1).describe('Unique meter key, e.g. "5h", "7d", "balance:USD"'),
|
|
9
17
|
product: z.string().optional().describe('Product identifier, e.g. "chatgpt", "codex", "claude-code"'),
|
|
10
18
|
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'),
|
|
19
|
+
kind: z.enum(['percent', 'count', 'balance']).describe('"percent" for 0-100% quotas, "balance" for currency/credits'),
|
|
12
20
|
window: z.enum(['5h', 'day', 'week', 'month', 'rolling']).optional(),
|
|
13
21
|
modelGroup: z.string().optional(),
|
|
14
22
|
remaining: z.number().describe('Remaining amount or percentage (0-100)'),
|
|
@@ -17,8 +25,8 @@ const meterSchema = z.object({
|
|
|
17
25
|
resetsAt: z.number().optional().describe('Reset timestamp in epoch milliseconds'),
|
|
18
26
|
});
|
|
19
27
|
const activePollTimers = new Map();
|
|
20
|
-
async function tryPollPendingSession(session) {
|
|
21
|
-
const baseUrl = getApiBaseUrl();
|
|
28
|
+
async function tryPollPendingSession(session, provider) {
|
|
29
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
22
30
|
try {
|
|
23
31
|
const res = await apiPollMcpSession(baseUrl, session.sessionId, session.pollToken);
|
|
24
32
|
if (res.status === 'authorized' && res.writeToken && res.cardId && res.nodeId) {
|
|
@@ -31,13 +39,13 @@ async function tryPollPendingSession(session) {
|
|
|
31
39
|
fingerprintSalt: res.fingerprintSalt,
|
|
32
40
|
connectedAt: Date.now(),
|
|
33
41
|
};
|
|
34
|
-
upsertBoundConnection(bound);
|
|
35
|
-
removePendingSession(session.sessionId);
|
|
42
|
+
upsertBoundConnection(bound, provider);
|
|
43
|
+
removePendingSession(session.sessionId, provider);
|
|
36
44
|
stopBackgroundPoll(session.sessionId);
|
|
37
45
|
return bound;
|
|
38
46
|
}
|
|
39
47
|
if (res.status === 'expired') {
|
|
40
|
-
removePendingSession(session.sessionId);
|
|
48
|
+
removePendingSession(session.sessionId, provider);
|
|
41
49
|
stopBackgroundPoll(session.sessionId);
|
|
42
50
|
}
|
|
43
51
|
}
|
|
@@ -49,80 +57,127 @@ async function tryPollPendingSession(session) {
|
|
|
49
57
|
function stopBackgroundPoll(sessionId) {
|
|
50
58
|
const timer = activePollTimers.get(sessionId);
|
|
51
59
|
if (timer) {
|
|
52
|
-
|
|
60
|
+
clearTimeout(timer);
|
|
53
61
|
activePollTimers.delete(sessionId);
|
|
54
62
|
}
|
|
55
63
|
}
|
|
56
|
-
function startBackgroundPoll(session) {
|
|
64
|
+
function startBackgroundPoll(session, provider) {
|
|
57
65
|
stopBackgroundPoll(session.sessionId);
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
const schedule = (attempt) => {
|
|
67
|
+
const delay = attempt < 3 ? 3_000 : attempt < 6 ? 6_000 : 15_000;
|
|
68
|
+
const timer = setTimeout(async () => {
|
|
69
|
+
if (Date.now() >= session.expiresAt) {
|
|
70
|
+
removePendingSession(session.sessionId, provider);
|
|
71
|
+
stopBackgroundPoll(session.sessionId);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await tryPollPendingSession(session, provider);
|
|
75
|
+
if (activePollTimers.get(session.sessionId) === timer)
|
|
76
|
+
schedule(attempt + 1);
|
|
77
|
+
}, Math.min(delay, Math.max(0, session.expiresAt - Date.now())));
|
|
78
|
+
timer.unref();
|
|
79
|
+
activePollTimers.set(session.sessionId, timer);
|
|
80
|
+
};
|
|
81
|
+
schedule(0);
|
|
68
82
|
}
|
|
69
|
-
async function syncAllPendingSessions() {
|
|
70
|
-
const cfg = loadConfig();
|
|
83
|
+
async function syncAllPendingSessions(provider) {
|
|
84
|
+
const cfg = loadConfig(provider);
|
|
71
85
|
const newlyBound = [];
|
|
72
86
|
for (const session of cfg.pendingSessions) {
|
|
73
|
-
const bound = await tryPollPendingSession(session);
|
|
87
|
+
const bound = await tryPollPendingSession(session, provider);
|
|
74
88
|
if (bound)
|
|
75
89
|
newlyBound.push(bound);
|
|
76
90
|
}
|
|
77
91
|
return newlyBound;
|
|
78
92
|
}
|
|
79
|
-
export function createTokenWalletMcpServer() {
|
|
93
|
+
export function createTokenWalletMcpServer(onProviderReady) {
|
|
94
|
+
const configured = explicitProvider();
|
|
95
|
+
let selected;
|
|
80
96
|
const server = new McpServer({
|
|
81
97
|
name: 'tokenwallet-mcp',
|
|
82
|
-
version:
|
|
98
|
+
version: packageVersion,
|
|
99
|
+
}, { capabilities: { logging: {} } });
|
|
100
|
+
const providerInput = (configured ? z.literal(configured) : z.enum(providerIds)).optional()
|
|
101
|
+
.describe('Provider for this instance. Required only when the client cannot be identified automatically.');
|
|
102
|
+
const getProvider = (requested) => {
|
|
103
|
+
const provider = selected ?? configured ?? providerForClient(server.server.getClientVersion()?.name) ?? requested;
|
|
104
|
+
if (!provider)
|
|
105
|
+
throw new Error('请在工具参数中指定 provider,或在 MCP 配置中指定 --provider。');
|
|
106
|
+
if (requested && requested !== provider)
|
|
107
|
+
throw new Error(`当前 MCP 已使用 ${provider},请确认 provider。`);
|
|
108
|
+
if (!selected) {
|
|
109
|
+
selected = provider;
|
|
110
|
+
onProviderReady?.(provider);
|
|
111
|
+
}
|
|
112
|
+
return provider;
|
|
113
|
+
};
|
|
114
|
+
server.server.oninitialized = () => {
|
|
115
|
+
if (configured || providerForClient(server.server.getClientVersion()?.name))
|
|
116
|
+
getProvider();
|
|
117
|
+
void checkForUpdates().then((status) => {
|
|
118
|
+
if (status.updateAvailable) {
|
|
119
|
+
return server.sendLoggingMessage({ level: 'notice', logger: 'tokenwallet-mcp', data: describeUpdate(status) });
|
|
120
|
+
}
|
|
121
|
+
}).catch(() => { });
|
|
122
|
+
};
|
|
123
|
+
server.registerTool('check_tokenwallet_updates', {
|
|
124
|
+
title: 'Check for TokenWallet MCP updates',
|
|
125
|
+
description: 'Compare the running version with the latest stable npm release. Use when asked to check, upgrade, or update TokenWallet MCP.',
|
|
126
|
+
inputSchema: {},
|
|
127
|
+
annotations: { readOnlyHint: true },
|
|
128
|
+
}, async () => {
|
|
129
|
+
const status = await checkForUpdates(true);
|
|
130
|
+
return { content: [{ type: 'text', text: describeUpdate(status) }], structuredContent: { ...status } };
|
|
83
131
|
});
|
|
132
|
+
server.registerPrompt('update_tokenwallet', {
|
|
133
|
+
title: 'Update TokenWallet MCP',
|
|
134
|
+
description: 'Upgrade the existing TokenWallet MCP without pinning a version, preserving provider and connection settings.',
|
|
135
|
+
}, () => ({ messages: [{ role: 'user', content: { type: 'text', text: updatePrompt } }] }));
|
|
84
136
|
server.registerTool('connect_tokenwallet', {
|
|
85
137
|
title: 'Connect to TokenWallet App',
|
|
86
138
|
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
139
|
inputSchema: {
|
|
88
|
-
|
|
89
|
-
|
|
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'),
|
|
140
|
+
provider: providerInput,
|
|
141
|
+
displayName: z.string().optional().describe('Optional card display name'),
|
|
93
142
|
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", "
|
|
143
|
+
source: z.string().optional().describe('Client source identifier, e.g. "chatgpt", "codex", "claude-code", "gemini-cli"'),
|
|
95
144
|
plan: z.string().optional().describe('Subscription plan name, e.g. "Plus", "Pro", "AI Pro"'),
|
|
96
145
|
accountHint: z.string().optional().describe('Optional masked account hint, e.g. "u***@gmail.com"'),
|
|
97
146
|
meters: z.array(meterSchema).optional().describe('Optional initial quota meters to populate immediately upon scan'),
|
|
98
147
|
},
|
|
99
148
|
}, async (args) => {
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
149
|
+
const provider = getProvider(args.provider);
|
|
150
|
+
const updateCheck = checkForUpdates();
|
|
151
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
152
|
+
const requiresCollector = provider === 'claude' || provider === 'gemini' || provider === 'muse-code' || provider === 'xai';
|
|
153
|
+
const localQuota = requiresCollector || !args.meters?.length ? await collectQuotaForBrand(provider) : null;
|
|
154
|
+
if (requiresCollector && !localQuota?.meters.length) {
|
|
155
|
+
return { isError: true, content: [{ type: 'text', text: sourceHelp[provider] }] };
|
|
156
|
+
}
|
|
104
157
|
const created = await apiCreateMcpSession(baseUrl, {
|
|
105
|
-
|
|
106
|
-
|
|
158
|
+
provider,
|
|
159
|
+
displayName: args.displayName,
|
|
107
160
|
nodeLabel: args.nodeLabel,
|
|
108
161
|
source: args.source ?? localQuota?.source ?? 'mcp',
|
|
109
162
|
plan: args.plan ?? localQuota?.plan,
|
|
110
163
|
accountHint: args.accountHint ?? localQuota?.accountHint,
|
|
111
|
-
meters:
|
|
164
|
+
meters: localQuota?.meters ?? args.meters,
|
|
112
165
|
});
|
|
166
|
+
if (created.provider !== provider)
|
|
167
|
+
throw new Error('中转服务返回了不同的供应商,请检查服务版本。');
|
|
113
168
|
const pending = {
|
|
114
169
|
sessionId: created.sessionId,
|
|
115
|
-
mcpCode: created.
|
|
170
|
+
mcpCode: created.code,
|
|
116
171
|
pollToken: created.pollToken,
|
|
117
|
-
brand: created.
|
|
118
|
-
provider: created.
|
|
172
|
+
brand: created.provider,
|
|
173
|
+
provider: created.displayName,
|
|
119
174
|
deepLink: created.deepLink,
|
|
120
175
|
webLink: created.webLink,
|
|
121
176
|
expiresAt: created.expiresAt,
|
|
122
177
|
createdAt: Date.now(),
|
|
123
178
|
};
|
|
124
|
-
savePendingSession(pending);
|
|
125
|
-
startBackgroundPoll(pending);
|
|
179
|
+
savePendingSession(pending, provider);
|
|
180
|
+
startBackgroundPoll(pending, provider);
|
|
126
181
|
const qrDataUrl = await QRCode.toDataURL(created.qrPayload, {
|
|
127
182
|
width: 320,
|
|
128
183
|
margin: 2,
|
|
@@ -130,10 +185,12 @@ export function createTokenWalletMcpServer() {
|
|
|
130
185
|
const base64Png = qrDataUrl.replace(/^data:image\/png;base64,/, '');
|
|
131
186
|
const asciiQr = await QRCode.toString(created.qrPayload, { type: 'utf8' });
|
|
132
187
|
const expiresInMin = Math.max(1, Math.round((created.expiresAt - Date.now()) / 60_000));
|
|
188
|
+
const cardLabel = provider === 'other' ? '自定义卡片' : created.displayName;
|
|
189
|
+
const update = await updateCheck;
|
|
133
190
|
const summary = [
|
|
134
|
-
`请打开 TokenWallet App,进入「添加卡片 → ${
|
|
191
|
+
`请打开 TokenWallet App,进入「添加卡片 → ${cardLabel}」,点击「扫描二维码」扫描下方二维码即可完成连接(有效期约 ${expiresInMin} 分钟):`,
|
|
135
192
|
'',
|
|
136
|
-
`连接码:${created.
|
|
193
|
+
`连接码:${created.code}`,
|
|
137
194
|
`手机直达链接:${created.deepLink}`,
|
|
138
195
|
`网页跳转链接:${created.webLink}`,
|
|
139
196
|
'',
|
|
@@ -141,7 +198,11 @@ export function createTokenWalletMcpServer() {
|
|
|
141
198
|
asciiQr.trimEnd(),
|
|
142
199
|
'```',
|
|
143
200
|
'',
|
|
201
|
+
provider === 'other' || (!localQuota && !args.meters?.length)
|
|
202
|
+
? sourceHelp[provider] ?? '等待首次额度上报。'
|
|
203
|
+
: '',
|
|
144
204
|
'扫码后本 MCP 会自动完成配对并保存只写上报凭证;也可以调用 `check_connection_status` 立即确认绑定状态。',
|
|
205
|
+
...(update.updateAvailable ? ['', describeUpdate(update)] : []),
|
|
145
206
|
].join('\n');
|
|
146
207
|
return {
|
|
147
208
|
content: [
|
|
@@ -161,20 +222,22 @@ export function createTokenWalletMcpServer() {
|
|
|
161
222
|
title: 'Check TokenWallet Connection Status',
|
|
162
223
|
description: 'Poll pending QR pairing sessions and report currently connected TokenWallet cards.',
|
|
163
224
|
inputSchema: {
|
|
225
|
+
provider: providerInput,
|
|
164
226
|
sessionId: z.string().optional().describe('Optional specific pending sessionId to poll'),
|
|
165
227
|
},
|
|
166
|
-
}, async ({ sessionId }) => {
|
|
167
|
-
const
|
|
228
|
+
}, async ({ sessionId, provider: requested }) => {
|
|
229
|
+
const provider = getProvider(requested);
|
|
230
|
+
const cfg = loadConfig(provider);
|
|
168
231
|
const targets = sessionId
|
|
169
232
|
? cfg.pendingSessions.filter((s) => s.sessionId === sessionId)
|
|
170
233
|
: cfg.pendingSessions;
|
|
171
234
|
const newlyBound = [];
|
|
172
235
|
for (const s of targets) {
|
|
173
|
-
const bound = await tryPollPendingSession(s);
|
|
236
|
+
const bound = await tryPollPendingSession(s, provider);
|
|
174
237
|
if (bound)
|
|
175
238
|
newlyBound.push(bound);
|
|
176
239
|
}
|
|
177
|
-
const updated = loadConfig();
|
|
240
|
+
const updated = loadConfig(provider);
|
|
178
241
|
const lines = [];
|
|
179
242
|
if (newlyBound.length > 0) {
|
|
180
243
|
lines.push(`新完成绑定 ${newlyBound.length} 张卡片:`);
|
|
@@ -201,30 +264,30 @@ export function createTokenWalletMcpServer() {
|
|
|
201
264
|
title: 'Report Quota to TokenWallet',
|
|
202
265
|
description: 'Push real-time remaining token quota or balance meters to a bound TokenWallet card.',
|
|
203
266
|
inputSchema: {
|
|
204
|
-
cardId: z.string().optional().describe('Target cardId
|
|
205
|
-
|
|
267
|
+
cardId: z.string().optional().describe('Target cardId; may be omitted when exactly one card matches'),
|
|
268
|
+
provider: providerInput,
|
|
206
269
|
plan: z.string().optional().describe('Optional updated plan name, e.g. "Plus", "Pro"'),
|
|
207
270
|
accountHint: z.string().optional().describe('Optional masked account hint'),
|
|
208
271
|
meters: z.array(meterSchema).min(1).describe('One or more quota meters to report'),
|
|
209
272
|
},
|
|
210
273
|
}, async (args) => {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
274
|
+
const provider = getProvider(args.provider);
|
|
275
|
+
await syncAllPendingSessions(provider);
|
|
276
|
+
const cfg = loadConfig(provider);
|
|
277
|
+
const matches = cfg.connections.filter((c) => (!args.cardId || args.cardId === c.cardId) && provider === c.brand);
|
|
278
|
+
const conn = matches.length === 1 ? matches[0] : undefined;
|
|
216
279
|
if (!conn) {
|
|
217
280
|
return {
|
|
218
281
|
isError: true,
|
|
219
282
|
content: [
|
|
220
283
|
{
|
|
221
284
|
type: 'text',
|
|
222
|
-
text: '
|
|
285
|
+
text: '请用 list_connections 查看卡片,并指定正确的 cardId 后重试。',
|
|
223
286
|
},
|
|
224
287
|
],
|
|
225
288
|
};
|
|
226
289
|
}
|
|
227
|
-
const baseUrl = getApiBaseUrl();
|
|
290
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
228
291
|
const now = Date.now();
|
|
229
292
|
const res = await apiSubmitReport(baseUrl, conn.writeToken, {
|
|
230
293
|
plan: args.plan,
|
|
@@ -235,86 +298,55 @@ export function createTokenWalletMcpServer() {
|
|
|
235
298
|
observedAt: now,
|
|
236
299
|
})),
|
|
237
300
|
});
|
|
238
|
-
markConnectionReported(conn.cardId, now);
|
|
301
|
+
markConnectionReported(conn.cardId, now, provider);
|
|
239
302
|
return {
|
|
240
303
|
content: [
|
|
241
304
|
{
|
|
242
305
|
type: 'text',
|
|
243
|
-
text: `已上报 ${conn.provider}(cardId=${res.cardId}
|
|
306
|
+
text: `已上报 ${conn.provider}(cardId=${res.cardId})最新额度,同步完成。`,
|
|
244
307
|
},
|
|
245
308
|
],
|
|
246
309
|
};
|
|
247
310
|
});
|
|
248
311
|
server.registerTool('sync_local_quotas', {
|
|
249
312
|
title: 'Sync Real Local AI Client Quotas',
|
|
250
|
-
description: 'Collect real-time remaining quotas from locally installed AI clients (Codex CLI, Claude Code,
|
|
313
|
+
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
314
|
inputSchema: {
|
|
252
|
-
|
|
253
|
-
.enum(['openai', 'claude', 'cursor', 'gemini', 'grok'])
|
|
254
|
-
.optional()
|
|
255
|
-
.describe('Optional specific brand to sync; omit to sync all bound local providers'),
|
|
315
|
+
provider: providerInput,
|
|
256
316
|
cardId: z.string().optional().describe('Optional specific bound cardId'),
|
|
257
317
|
},
|
|
258
|
-
}, async ({
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
const
|
|
262
|
-
const
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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
|
-
};
|
|
318
|
+
}, async ({ cardId, provider: requested }) => {
|
|
319
|
+
const provider = getProvider(requested);
|
|
320
|
+
await syncAllPendingSessions(provider);
|
|
321
|
+
const cfg = loadConfig(provider);
|
|
322
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
323
|
+
const conn = cfg.connections.find(c => c.brand === provider && (!cardId || c.cardId === cardId));
|
|
324
|
+
if (!conn)
|
|
325
|
+
return { isError: true, content: [{ type: 'text', text: '当前实例没有匹配的绑定。' }] };
|
|
326
|
+
const snapshot = await collectQuotaForBrand(provider);
|
|
327
|
+
if (!snapshot)
|
|
328
|
+
return { isError: true, content: [{ type: 'text', text: sourceHelp[provider] ?? '请检查本机登录状态。' }] };
|
|
329
|
+
await apiSubmitReport(baseUrl, conn.writeToken, {
|
|
330
|
+
plan: snapshot.plan, accountHint: snapshot.accountHint,
|
|
331
|
+
observedAt: snapshot.observedAt, meters: snapshot.meters,
|
|
332
|
+
});
|
|
333
|
+
markConnectionReported(conn.cardId, Date.now(), provider);
|
|
334
|
+
return { content: [{ type: 'text', text: '额度已同步至钱包。' }] };
|
|
304
335
|
});
|
|
305
336
|
server.registerTool('list_connections', {
|
|
306
337
|
title: 'List Connected TokenWallet Cards',
|
|
307
338
|
description: 'List all locally bound TokenWallet cards and verify their node connectivity.',
|
|
308
|
-
inputSchema: {},
|
|
309
|
-
}, async () => {
|
|
310
|
-
|
|
311
|
-
|
|
339
|
+
inputSchema: { provider: providerInput },
|
|
340
|
+
}, async ({ provider: requested }) => {
|
|
341
|
+
const provider = getProvider(requested);
|
|
342
|
+
await syncAllPendingSessions(provider);
|
|
343
|
+
const cfg = loadConfig(provider);
|
|
312
344
|
if (cfg.connections.length === 0) {
|
|
313
345
|
return {
|
|
314
346
|
content: [{ type: 'text', text: '当前没有已绑定的 TokenWallet 卡片。可调用 `connect_tokenwallet` 开始绑定。' }],
|
|
315
347
|
};
|
|
316
348
|
}
|
|
317
|
-
const baseUrl = getApiBaseUrl();
|
|
349
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
318
350
|
const lines = [`API 地址:${baseUrl}`, `已绑定卡片 (${cfg.connections.length}):`];
|
|
319
351
|
for (const conn of cfg.connections) {
|
|
320
352
|
let status = 'online';
|
|
@@ -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/dist/update.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
const require = createRequire(import.meta.url);
|
|
3
|
+
export const packageVersion = require('../package.json').version;
|
|
4
|
+
export const launchCommand = 'npx -y --prefer-online tokenwallet-mcp@latest';
|
|
5
|
+
const registryUrl = 'https://registry.npmjs.org/tokenwallet-mcp/latest';
|
|
6
|
+
const stableVersion = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
7
|
+
const checkIntervalMs = 60_000;
|
|
8
|
+
function isNewer(installed, latest) {
|
|
9
|
+
const current = stableVersion.exec(installed);
|
|
10
|
+
const remote = stableVersion.exec(latest);
|
|
11
|
+
if (!current || !remote)
|
|
12
|
+
return false;
|
|
13
|
+
for (let component = 1; component <= 3; component++) {
|
|
14
|
+
const left = BigInt(current[component]);
|
|
15
|
+
const right = BigInt(remote[component]);
|
|
16
|
+
if (left !== right)
|
|
17
|
+
return right > left;
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
export function createUpdateChecker(installedVersion = packageVersion) {
|
|
22
|
+
let latest;
|
|
23
|
+
let pending;
|
|
24
|
+
return function check(force = false) {
|
|
25
|
+
if (pending)
|
|
26
|
+
return pending;
|
|
27
|
+
if (!force && latest && Date.now() - latest.checkedAt < checkIntervalMs)
|
|
28
|
+
return Promise.resolve(latest.status);
|
|
29
|
+
pending = (async () => {
|
|
30
|
+
let latestVersion = null;
|
|
31
|
+
try {
|
|
32
|
+
const response = await fetch(registryUrl, {
|
|
33
|
+
cache: 'no-store',
|
|
34
|
+
headers: { Accept: 'application/json' },
|
|
35
|
+
redirect: 'error',
|
|
36
|
+
signal: AbortSignal.timeout(2_000),
|
|
37
|
+
});
|
|
38
|
+
if (response.ok) {
|
|
39
|
+
const data = await response.json();
|
|
40
|
+
if (typeof data.version === 'string' && stableVersion.test(data.version))
|
|
41
|
+
latestVersion = data.version;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// Registry availability must not interrupt pairing or quota reporting.
|
|
46
|
+
}
|
|
47
|
+
const status = { installedVersion, latestVersion, updateAvailable: latestVersion ? isNewer(installedVersion, latestVersion) : false };
|
|
48
|
+
latest = { status, checkedAt: Date.now() };
|
|
49
|
+
return status;
|
|
50
|
+
})().finally(() => { pending = undefined; });
|
|
51
|
+
return pending;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export const checkForUpdates = createUpdateChecker();
|
|
55
|
+
export function describeUpdate(status) {
|
|
56
|
+
if (!status.latestVersion)
|
|
57
|
+
return `当前运行 ${status.installedVersion}。暂时无法访问 npm,现有连接可以继续使用。`;
|
|
58
|
+
if (!status.updateAvailable)
|
|
59
|
+
return `当前运行 ${status.installedVersion},npm 最新稳定版是 ${status.latestVersion}。`;
|
|
60
|
+
return `TokenWallet MCP 有新版 ${status.latestVersion}(当前 ${status.installedVersion})。可使用 update_tokenwallet 提示词更新启动配置并重启 MCP。`;
|
|
61
|
+
}
|
|
62
|
+
export const updatePrompt = [
|
|
63
|
+
'请更新我当前 AI 客户端中已有的 TokenWallet MCP 配置。',
|
|
64
|
+
'如果 check_tokenwallet_updates 工具可用,请先核对正在运行的版本和 npm 最新稳定版。',
|
|
65
|
+
`将已有的本地 stdio 启动方式改为 ${launchCommand},让下次启动重新解析 npm 最新稳定版。`,
|
|
66
|
+
'保留现有 MCP 名称、工作目录、环境变量、连接数据和 --provider 参数。更新已有条目,避免添加重复服务器。',
|
|
67
|
+
'旧配置缺少 --provider 时,按已确认的客户端或供应商补上,例如 Codex 使用 openai、Claude Code 使用 claude。',
|
|
68
|
+
'重新加载 MCP 或重启客户端,再验证 MCP 握手报告的版本。如果无法重新加载,只说明需要重启,等待用户完成。',
|
|
69
|
+
].join('\n');
|