tokenwallet-mcp 1.0.2 → 1.0.4
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 +20 -10
- package/dist/config.js +42 -22
- package/dist/index.js +8 -9
- package/dist/server.js +121 -55
- package/dist/update.js +69 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,10 +12,10 @@ Official MCP server for [TokenWallet](https://token-wallet.app) — connect your
|
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
# Codex CLI
|
|
15
|
-
codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
|
|
15
|
+
codex mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider openai
|
|
16
16
|
|
|
17
17
|
# Claude Code
|
|
18
|
-
claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
|
|
18
|
+
claude mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider claude
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
### Desktop & IDE (Claude Desktop / Windsurf / Cline & more)
|
|
@@ -27,7 +27,7 @@ Add the following to your client's MCP configuration file and replace `<provider
|
|
|
27
27
|
"mcpServers": {
|
|
28
28
|
"tokenwallet": {
|
|
29
29
|
"command": "npx",
|
|
30
|
-
"args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
|
|
30
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
}
|
|
@@ -43,7 +43,7 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
43
43
|
"tokenwallet": {
|
|
44
44
|
"type": "stdio",
|
|
45
45
|
"command": "npx",
|
|
46
|
-
"args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
|
|
46
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
}
|
|
@@ -52,10 +52,14 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
52
52
|
## Quick Start
|
|
53
53
|
|
|
54
54
|
1. After installation, start a conversation in your AI client and say:
|
|
55
|
-
**"Connect to TokenWallet"
|
|
55
|
+
**"Connect to TokenWallet"**. The reply includes a scannable QR code, a clickable pairing page, and an 8-character pairing code. If your client cannot display images, open the pairing page to see the QR code beneath the code. Clients with MCP prompt support can also use `connect_tokenwallet`.
|
|
56
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
57
|
3. After pairing, view your quota in TokenWallet.
|
|
58
58
|
|
|
59
|
+
### Updates
|
|
60
|
+
|
|
61
|
+
The launch command resolves npm's latest stable version whenever the client starts the MCP server. To update an older setup, tell your agent **“Update my existing TokenWallet MCP and use the latest stable release without pinning a version.”** Clients that support MCP prompts can also use `update_tokenwallet`. The `check_tokenwallet_updates` tool reports the version of the running process and the latest npm release.
|
|
62
|
+
|
|
59
63
|
---
|
|
60
64
|
|
|
61
65
|
## 简体中文
|
|
@@ -68,10 +72,10 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
68
72
|
|
|
69
73
|
```bash
|
|
70
74
|
# Codex CLI
|
|
71
|
-
codex mcp add tokenwallet -- npx -y tokenwallet-mcp --provider openai
|
|
75
|
+
codex mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider openai
|
|
72
76
|
|
|
73
77
|
# Claude Code
|
|
74
|
-
claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
|
|
78
|
+
claude mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider claude
|
|
75
79
|
```
|
|
76
80
|
|
|
77
81
|
#### 桌面端与 IDE(Claude Desktop / Windsurf / Cline 等)
|
|
@@ -83,7 +87,7 @@ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
|
|
|
83
87
|
"mcpServers": {
|
|
84
88
|
"tokenwallet": {
|
|
85
89
|
"command": "npx",
|
|
86
|
-
"args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
|
|
90
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
87
91
|
}
|
|
88
92
|
}
|
|
89
93
|
}
|
|
@@ -99,7 +103,7 @@ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
|
|
|
99
103
|
"tokenwallet": {
|
|
100
104
|
"type": "stdio",
|
|
101
105
|
"command": "npx",
|
|
102
|
-
"args": ["-y", "tokenwallet-mcp", "--provider", "<provider>"]
|
|
106
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
103
107
|
}
|
|
104
108
|
}
|
|
105
109
|
}
|
|
@@ -110,10 +114,16 @@ claude mcp add tokenwallet -- npx -y tokenwallet-mcp --provider claude
|
|
|
110
114
|
### 快速开始
|
|
111
115
|
|
|
112
116
|
1. 安装完成后,在 AI 客户端对话中输入:
|
|
113
|
-
**「帮我连接 TokenWallet
|
|
117
|
+
**「帮我连接 TokenWallet」**。回复会显示二维码、可点击的配对链接和 8 位配对码。客户端如果无法显示图片,打开配对链接即可在配对码下方看到二维码。支持 MCP 提示词的客户端也可以使用 `connect_tokenwallet`。
|
|
114
118
|
2. 打开手机上的 **词元钱包(TokenWallet)** App,点击右上角 **+** → 选择对应平台 → **扫描二维码**(若无法扫码可手动输入 8 位配对码)。
|
|
115
119
|
3. 配对完成后,在词元钱包中查看额度。
|
|
116
120
|
|
|
121
|
+
### 更新 MCP
|
|
122
|
+
|
|
123
|
+
配置中的 `@latest` 是 npm 的发布标签。客户端每次启动 MCP 时都会在线解析最新稳定版,无需在配置里改版本号。已经在运行的 MCP 会检查更新,并在有新版时提示重新加载。
|
|
124
|
+
|
|
125
|
+
已有安装可以直接告诉原来的 AI 助手:**「帮我升级现有的 TokenWallet MCP,以后每次连接用 npm 最新版,保留现有供应商和连接配置。」** 支持 MCP 提示词的客户端也可以选用 `update_tokenwallet`,或让助手调用 `check_tokenwallet_updates` 查看当前运行版本和 npm 最新版。
|
|
126
|
+
|
|
117
127
|
### 发布 npm 新版本
|
|
118
128
|
|
|
119
129
|
#### 首次配置
|
package/dist/config.js
CHANGED
|
@@ -3,22 +3,42 @@ 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
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
|
|
6
|
+
export const providerIds = ['openai', 'claude', 'gemini', 'muse-code', 'xai', 'deepseek', 'openrouter', 'other'];
|
|
7
|
+
export function explicitProvider() {
|
|
8
8
|
const index = process.argv.indexOf('--provider');
|
|
9
9
|
const value = index < 0 ? process.env.TOKENWALLET_PROVIDER : process.argv[index + 1];
|
|
10
|
+
if (index < 0 && !value)
|
|
11
|
+
return undefined;
|
|
10
12
|
const provider = providerIds.find(id => id === value);
|
|
11
13
|
if (!provider)
|
|
12
14
|
throw new Error('请在本客户端的 MCP 启动参数中指定 --provider,或设置 TOKENWALLET_PROVIDER。支持:' + providerIds.join(', '));
|
|
13
15
|
return provider;
|
|
14
16
|
}
|
|
15
|
-
export function
|
|
16
|
-
const
|
|
17
|
-
|
|
17
|
+
export function configuredProvider() {
|
|
18
|
+
const provider = explicitProvider();
|
|
19
|
+
if (!provider)
|
|
20
|
+
throw new Error('请为 TokenWallet MCP 指定 --provider。支持:' + providerIds.join(', '));
|
|
21
|
+
return provider;
|
|
22
|
+
}
|
|
23
|
+
export function providerForClient(clientName) {
|
|
24
|
+
const parts = clientName?.toLowerCase().split(/[^a-z0-9]+/) ?? [];
|
|
25
|
+
if (parts.includes('codex'))
|
|
26
|
+
return 'openai';
|
|
27
|
+
if (parts.includes('claude'))
|
|
28
|
+
return 'claude';
|
|
29
|
+
if (parts.includes('gemini'))
|
|
30
|
+
return 'gemini';
|
|
31
|
+
if (parts.includes('muse') && parts.includes('code'))
|
|
32
|
+
return 'muse-code';
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
export function getApiBaseUrl(provider = explicitProvider()) {
|
|
36
|
+
const url = process.env.TOKENWALLET_API_URL || (provider ? loadConfig(provider).apiBaseUrl : DEFAULT_API_URL);
|
|
37
|
+
return url.replace(/\/+$/, '');
|
|
18
38
|
}
|
|
19
|
-
export function loadConfig() {
|
|
20
|
-
const
|
|
21
|
-
const file = path.join(CONFIG_DIR,
|
|
39
|
+
export function loadConfig(provider = configuredProvider()) {
|
|
40
|
+
const scoped = path.join(CONFIG_DIR, provider, 'config.json');
|
|
41
|
+
const file = fs.existsSync(scoped) ? scoped : path.join(CONFIG_DIR, 'config.json');
|
|
22
42
|
try {
|
|
23
43
|
if (fs.existsSync(file)) {
|
|
24
44
|
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
@@ -38,34 +58,34 @@ export function loadConfig() {
|
|
|
38
58
|
pendingSessions: [],
|
|
39
59
|
};
|
|
40
60
|
}
|
|
41
|
-
export function saveConfig(config) {
|
|
42
|
-
const directory = path.join(CONFIG_DIR,
|
|
61
|
+
export function saveConfig(config, provider = configuredProvider()) {
|
|
62
|
+
const directory = path.join(CONFIG_DIR, provider);
|
|
43
63
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
44
64
|
fs.writeFileSync(path.join(directory, 'config.json'), JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
45
65
|
}
|
|
46
|
-
export function savePendingSession(session) {
|
|
47
|
-
const cfg = loadConfig();
|
|
66
|
+
export function savePendingSession(session, provider = configuredProvider()) {
|
|
67
|
+
const cfg = loadConfig(provider);
|
|
48
68
|
const now = Date.now();
|
|
49
69
|
const active = cfg.pendingSessions.filter((s) => s.sessionId !== session.sessionId && s.expiresAt > now);
|
|
50
70
|
active.unshift(session);
|
|
51
71
|
cfg.pendingSessions = active.slice(0, 10);
|
|
52
|
-
saveConfig(cfg);
|
|
72
|
+
saveConfig(cfg, provider);
|
|
53
73
|
}
|
|
54
|
-
export function removePendingSession(sessionId) {
|
|
55
|
-
const cfg = loadConfig();
|
|
74
|
+
export function removePendingSession(sessionId, provider = configuredProvider()) {
|
|
75
|
+
const cfg = loadConfig(provider);
|
|
56
76
|
cfg.pendingSessions = cfg.pendingSessions.filter((s) => s.sessionId !== sessionId);
|
|
57
|
-
saveConfig(cfg);
|
|
77
|
+
saveConfig(cfg, provider);
|
|
58
78
|
}
|
|
59
|
-
export function upsertBoundConnection(conn) {
|
|
60
|
-
const cfg = loadConfig();
|
|
79
|
+
export function upsertBoundConnection(conn, provider = configuredProvider()) {
|
|
80
|
+
const cfg = loadConfig(provider);
|
|
61
81
|
cfg.connections = [conn];
|
|
62
|
-
saveConfig(cfg);
|
|
82
|
+
saveConfig(cfg, provider);
|
|
63
83
|
}
|
|
64
|
-
export function markConnectionReported(cardId, reportedAt = Date.now()) {
|
|
65
|
-
const cfg = loadConfig();
|
|
84
|
+
export function markConnectionReported(cardId, reportedAt = Date.now(), provider = configuredProvider()) {
|
|
85
|
+
const cfg = loadConfig(provider);
|
|
66
86
|
const target = cfg.connections.find((c) => c.cardId === cardId);
|
|
67
87
|
if (target) {
|
|
68
88
|
target.lastReportedAt = reportedAt;
|
|
69
|
-
saveConfig(cfg);
|
|
89
|
+
saveConfig(cfg, provider);
|
|
70
90
|
}
|
|
71
91
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
|
5
5
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
6
6
|
import { apiSubmitReport } from './api.js';
|
|
7
7
|
import { collectQuotaForBrand } from './collectors/index.js';
|
|
8
|
-
import {
|
|
8
|
+
import { explicitProvider, getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
|
|
9
9
|
import { createTokenWalletMcpServer } from './server.js';
|
|
10
10
|
function parseArgs() {
|
|
11
11
|
const argv = process.argv.slice(2);
|
|
@@ -16,16 +16,16 @@ function parseArgs() {
|
|
|
16
16
|
8788;
|
|
17
17
|
return { useHttp, port };
|
|
18
18
|
}
|
|
19
|
-
function startLocalAutoReporter() {
|
|
19
|
+
function startLocalAutoReporter(provider) {
|
|
20
20
|
const lastFingerprintByCard = new Map();
|
|
21
21
|
const tick = async () => {
|
|
22
22
|
try {
|
|
23
|
-
const cfg = loadConfig();
|
|
23
|
+
const cfg = loadConfig(provider);
|
|
24
24
|
if (cfg.connections.length === 0)
|
|
25
25
|
return;
|
|
26
|
-
const baseUrl = getApiBaseUrl();
|
|
26
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
27
27
|
const [conn] = cfg.connections;
|
|
28
|
-
const snap = await collectQuotaForBrand(
|
|
28
|
+
const snap = await collectQuotaForBrand(provider);
|
|
29
29
|
if (!snap?.meters.length)
|
|
30
30
|
return;
|
|
31
31
|
const sig = JSON.stringify([
|
|
@@ -46,7 +46,7 @@ function startLocalAutoReporter() {
|
|
|
46
46
|
}).catch(() => null);
|
|
47
47
|
if (!result)
|
|
48
48
|
return;
|
|
49
|
-
markConnectionReported(conn.cardId, Date.now());
|
|
49
|
+
markConnectionReported(conn.cardId, Date.now(), provider);
|
|
50
50
|
lastFingerprintByCard.clear();
|
|
51
51
|
lastFingerprintByCard.set(connection, sig);
|
|
52
52
|
}
|
|
@@ -61,10 +61,9 @@ function startLocalAutoReporter() {
|
|
|
61
61
|
void run();
|
|
62
62
|
}
|
|
63
63
|
async function startStdio() {
|
|
64
|
-
const server = createTokenWalletMcpServer();
|
|
64
|
+
const server = createTokenWalletMcpServer(startLocalAutoReporter);
|
|
65
65
|
const transport = new StdioServerTransport();
|
|
66
66
|
await server.connect(transport);
|
|
67
|
-
startLocalAutoReporter();
|
|
68
67
|
console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
|
|
69
68
|
}
|
|
70
69
|
async function startHttp(port) {
|
|
@@ -134,7 +133,7 @@ async function startHttp(port) {
|
|
|
134
133
|
console.log(`[tokenwallet-mcp] TokenWallet API: ${getApiBaseUrl()}`);
|
|
135
134
|
});
|
|
136
135
|
}
|
|
137
|
-
|
|
136
|
+
explicitProvider();
|
|
138
137
|
const { useHttp, port } = parseArgs();
|
|
139
138
|
if (useHttp) {
|
|
140
139
|
await startHttp(port);
|
package/dist/server.js
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import { createRequire } from 'node:module';
|
|
2
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
2
|
import QRCode from 'qrcode';
|
|
4
3
|
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';
|
|
8
4
|
import { apiCreateMcpSession, apiPingNode, apiPollMcpSession, apiSubmitReport, } from './api.js';
|
|
9
5
|
import { collectQuotaForBrand } from './collectors/index.js';
|
|
10
|
-
import {
|
|
6
|
+
import { explicitProvider, getApiBaseUrl, loadConfig, markConnectionReported, providerForClient, providerIds, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
|
|
7
|
+
import { checkForUpdates, describeUpdate, packageVersion, updatePrompt } from './update.js';
|
|
11
8
|
const sourceHelp = {
|
|
12
9
|
claude: '登录本机 Claude Code,或设置 Claude statusLine 采集器并完成一个回合。',
|
|
13
10
|
gemini: '先在本机终端登录 Gemini CLI(生成 ~/.gemini/oauth_creds.json),或配置 Gemini CLI statusLine 采集器。',
|
|
@@ -15,6 +12,11 @@ const sourceHelp = {
|
|
|
15
12
|
xai: '检查 XAI_MANAGEMENT_API_KEY 的账单权限和 XAI_TEAM_ID。',
|
|
16
13
|
other: '自定义卡片由客户端从额度来源读取余量,再调用 report_quota 上报。可在客户端配置定时任务或用量事件来触发。',
|
|
17
14
|
};
|
|
15
|
+
const pairingInstructions = [
|
|
16
|
+
'When the user asks to connect or pair TokenWallet, including “帮我连接TokenWallet” or “连接词元钱包”, call connect_tokenwallet immediately using the configured provider. Ask for the provider only if it cannot be resolved.',
|
|
17
|
+
'After a successful call, show all three in the same reply: a visible scannable QR image, the clickable HTTPS pairing page, and the 8-character pairing code. Display the returned PNG or use the provided Markdown image URL. If the client cannot render images, keep the pairing page link and code visible and tell the user that the page shows the QR code directly below the code.',
|
|
18
|
+
'Ask the user to scan the QR code in TokenWallet or enter the code manually. Use only the actual values returned by the tool. If the tool returns an error, show its recovery steps.',
|
|
19
|
+
].join(' ');
|
|
18
20
|
const meterSchema = z.object({
|
|
19
21
|
meterKey: z.string().min(1).describe('Unique meter key, e.g. "5h", "7d", "balance:USD"'),
|
|
20
22
|
product: z.string().optional().describe('Product identifier, e.g. "chatgpt", "codex", "claude-code"'),
|
|
@@ -28,8 +30,8 @@ const meterSchema = z.object({
|
|
|
28
30
|
resetsAt: z.number().optional().describe('Reset timestamp in epoch milliseconds'),
|
|
29
31
|
});
|
|
30
32
|
const activePollTimers = new Map();
|
|
31
|
-
async function tryPollPendingSession(session) {
|
|
32
|
-
const baseUrl = getApiBaseUrl();
|
|
33
|
+
async function tryPollPendingSession(session, provider) {
|
|
34
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
33
35
|
try {
|
|
34
36
|
const res = await apiPollMcpSession(baseUrl, session.sessionId, session.pollToken);
|
|
35
37
|
if (res.status === 'authorized' && res.writeToken && res.cardId && res.nodeId) {
|
|
@@ -42,13 +44,13 @@ async function tryPollPendingSession(session) {
|
|
|
42
44
|
fingerprintSalt: res.fingerprintSalt,
|
|
43
45
|
connectedAt: Date.now(),
|
|
44
46
|
};
|
|
45
|
-
upsertBoundConnection(bound);
|
|
46
|
-
removePendingSession(session.sessionId);
|
|
47
|
+
upsertBoundConnection(bound, provider);
|
|
48
|
+
removePendingSession(session.sessionId, provider);
|
|
47
49
|
stopBackgroundPoll(session.sessionId);
|
|
48
50
|
return bound;
|
|
49
51
|
}
|
|
50
52
|
if (res.status === 'expired') {
|
|
51
|
-
removePendingSession(session.sessionId);
|
|
53
|
+
removePendingSession(session.sessionId, provider);
|
|
52
54
|
stopBackgroundPoll(session.sessionId);
|
|
53
55
|
}
|
|
54
56
|
}
|
|
@@ -64,17 +66,17 @@ function stopBackgroundPoll(sessionId) {
|
|
|
64
66
|
activePollTimers.delete(sessionId);
|
|
65
67
|
}
|
|
66
68
|
}
|
|
67
|
-
function startBackgroundPoll(session) {
|
|
69
|
+
function startBackgroundPoll(session, provider) {
|
|
68
70
|
stopBackgroundPoll(session.sessionId);
|
|
69
71
|
const schedule = (attempt) => {
|
|
70
72
|
const delay = attempt < 3 ? 3_000 : attempt < 6 ? 6_000 : 15_000;
|
|
71
73
|
const timer = setTimeout(async () => {
|
|
72
74
|
if (Date.now() >= session.expiresAt) {
|
|
73
|
-
removePendingSession(session.sessionId);
|
|
75
|
+
removePendingSession(session.sessionId, provider);
|
|
74
76
|
stopBackgroundPoll(session.sessionId);
|
|
75
77
|
return;
|
|
76
78
|
}
|
|
77
|
-
await tryPollPendingSession(session);
|
|
79
|
+
await tryPollPendingSession(session, provider);
|
|
78
80
|
if (activePollTimers.get(session.sessionId) === timer)
|
|
79
81
|
schedule(attempt + 1);
|
|
80
82
|
}, Math.min(delay, Math.max(0, session.expiresAt - Date.now())));
|
|
@@ -83,27 +85,77 @@ function startBackgroundPoll(session) {
|
|
|
83
85
|
};
|
|
84
86
|
schedule(0);
|
|
85
87
|
}
|
|
86
|
-
async function syncAllPendingSessions() {
|
|
87
|
-
const cfg = loadConfig();
|
|
88
|
+
async function syncAllPendingSessions(provider) {
|
|
89
|
+
const cfg = loadConfig(provider);
|
|
88
90
|
const newlyBound = [];
|
|
89
91
|
for (const session of cfg.pendingSessions) {
|
|
90
|
-
const bound = await tryPollPendingSession(session);
|
|
92
|
+
const bound = await tryPollPendingSession(session, provider);
|
|
91
93
|
if (bound)
|
|
92
94
|
newlyBound.push(bound);
|
|
93
95
|
}
|
|
94
96
|
return newlyBound;
|
|
95
97
|
}
|
|
96
|
-
export function createTokenWalletMcpServer() {
|
|
97
|
-
const
|
|
98
|
+
export function createTokenWalletMcpServer(onProviderReady) {
|
|
99
|
+
const configured = explicitProvider();
|
|
100
|
+
let selected;
|
|
98
101
|
const server = new McpServer({
|
|
99
102
|
name: 'tokenwallet-mcp',
|
|
100
|
-
version:
|
|
103
|
+
version: packageVersion,
|
|
104
|
+
}, { capabilities: { logging: {} }, instructions: pairingInstructions });
|
|
105
|
+
const providerInput = (configured ? z.literal(configured) : z.enum(providerIds)).optional()
|
|
106
|
+
.describe('Provider for this instance. Required only when the client cannot be identified automatically.');
|
|
107
|
+
const getProvider = (requested) => {
|
|
108
|
+
const provider = selected ?? configured ?? providerForClient(server.server.getClientVersion()?.name) ?? requested;
|
|
109
|
+
if (!provider)
|
|
110
|
+
throw new Error('请在工具参数中指定 provider,或在 MCP 配置中指定 --provider。');
|
|
111
|
+
if (requested && requested !== provider)
|
|
112
|
+
throw new Error(`当前 MCP 已使用 ${provider},请确认 provider。`);
|
|
113
|
+
if (!selected) {
|
|
114
|
+
selected = provider;
|
|
115
|
+
onProviderReady?.(provider);
|
|
116
|
+
}
|
|
117
|
+
return provider;
|
|
118
|
+
};
|
|
119
|
+
server.server.oninitialized = () => {
|
|
120
|
+
if (configured || providerForClient(server.server.getClientVersion()?.name))
|
|
121
|
+
getProvider();
|
|
122
|
+
void checkForUpdates().then((status) => {
|
|
123
|
+
if (status.updateAvailable) {
|
|
124
|
+
return server.sendLoggingMessage({ level: 'notice', logger: 'tokenwallet-mcp', data: describeUpdate(status) });
|
|
125
|
+
}
|
|
126
|
+
}).catch(() => { });
|
|
127
|
+
};
|
|
128
|
+
server.registerTool('check_tokenwallet_updates', {
|
|
129
|
+
title: 'Check for TokenWallet MCP updates',
|
|
130
|
+
description: 'Compare the running version with the latest stable npm release. Use when asked to check, upgrade, or update TokenWallet MCP.',
|
|
131
|
+
inputSchema: {},
|
|
132
|
+
annotations: { readOnlyHint: true },
|
|
133
|
+
}, async () => {
|
|
134
|
+
const status = await checkForUpdates(true);
|
|
135
|
+
return { content: [{ type: 'text', text: describeUpdate(status) }], structuredContent: { ...status } };
|
|
101
136
|
});
|
|
137
|
+
server.registerPrompt('update_tokenwallet', {
|
|
138
|
+
title: 'Update TokenWallet MCP',
|
|
139
|
+
description: 'Upgrade the existing TokenWallet MCP without pinning a version, preserving provider and connection settings.',
|
|
140
|
+
}, () => ({ messages: [{ role: 'user', content: { type: 'text', text: updatePrompt } }] }));
|
|
141
|
+
server.registerPrompt('connect_tokenwallet', {
|
|
142
|
+
title: 'Connect TokenWallet / 连接词元钱包',
|
|
143
|
+
description: 'Create a pairing session and show its QR code, clickable pairing page, and 8-character code.',
|
|
144
|
+
}, () => ({
|
|
145
|
+
messages: [{ role: 'user', content: { type: 'text', text: pairingInstructions } }],
|
|
146
|
+
}));
|
|
102
147
|
server.registerTool('connect_tokenwallet', {
|
|
103
148
|
title: 'Connect to TokenWallet App',
|
|
104
|
-
description:
|
|
149
|
+
description: pairingInstructions,
|
|
150
|
+
outputSchema: {
|
|
151
|
+
pairingCode: z.string(),
|
|
152
|
+
pairingUrl: z.string().url(),
|
|
153
|
+
qrImageUrl: z.string().url(),
|
|
154
|
+
deepLink: z.string().url(),
|
|
155
|
+
expiresAt: z.number(),
|
|
156
|
+
},
|
|
105
157
|
inputSchema: {
|
|
106
|
-
provider:
|
|
158
|
+
provider: providerInput,
|
|
107
159
|
displayName: z.string().optional().describe('Optional card display name'),
|
|
108
160
|
nodeLabel: z.string().optional().describe('Friendly name for this client/machine, e.g. "MacBook ChatGPT"'),
|
|
109
161
|
source: z.string().optional().describe('Client source identifier, e.g. "chatgpt", "codex", "claude-code", "gemini-cli"'),
|
|
@@ -112,7 +164,9 @@ export function createTokenWalletMcpServer() {
|
|
|
112
164
|
meters: z.array(meterSchema).optional().describe('Optional initial quota meters to populate immediately upon scan'),
|
|
113
165
|
},
|
|
114
166
|
}, async (args) => {
|
|
115
|
-
const
|
|
167
|
+
const provider = getProvider(args.provider);
|
|
168
|
+
const updateCheck = checkForUpdates();
|
|
169
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
116
170
|
const requiresCollector = provider === 'claude' || provider === 'gemini' || provider === 'muse-code' || provider === 'xai';
|
|
117
171
|
const localQuota = requiresCollector || !args.meters?.length ? await collectQuotaForBrand(provider) : null;
|
|
118
172
|
if (requiresCollector && !localQuota?.meters.length) {
|
|
@@ -140,33 +194,40 @@ export function createTokenWalletMcpServer() {
|
|
|
140
194
|
expiresAt: created.expiresAt,
|
|
141
195
|
createdAt: Date.now(),
|
|
142
196
|
};
|
|
143
|
-
savePendingSession(pending);
|
|
144
|
-
startBackgroundPoll(pending);
|
|
197
|
+
savePendingSession(pending, provider);
|
|
198
|
+
startBackgroundPoll(pending, provider);
|
|
145
199
|
const qrDataUrl = await QRCode.toDataURL(created.qrPayload, {
|
|
146
200
|
width: 320,
|
|
147
|
-
margin:
|
|
201
|
+
margin: 4,
|
|
148
202
|
});
|
|
149
203
|
const base64Png = qrDataUrl.replace(/^data:image\/png;base64,/, '');
|
|
150
|
-
const
|
|
204
|
+
const qrImage = new URL('/connect/qr', created.webLink);
|
|
205
|
+
qrImage.search = new URLSearchParams({ provider: created.provider, code: created.code }).toString();
|
|
206
|
+
const qrImageUrl = qrImage.href;
|
|
151
207
|
const expiresInMin = Math.max(1, Math.round((created.expiresAt - Date.now()) / 60_000));
|
|
152
208
|
const cardLabel = provider === 'other' ? '自定义卡片' : created.displayName;
|
|
209
|
+
const update = await updateCheck;
|
|
153
210
|
const summary = [
|
|
154
|
-
|
|
155
|
-
'',
|
|
156
|
-
`连接码:${created.code}`,
|
|
157
|
-
`手机直达链接:${created.deepLink}`,
|
|
158
|
-
`网页跳转链接:${created.webLink}`,
|
|
211
|
+
`请在 TokenWallet App 中打开「添加卡片 → ${cardLabel} → 扫描二维码」,或手动输入配对码。有效期约 ${expiresInMin} 分钟。`,
|
|
159
212
|
'',
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
213
|
+
``,
|
|
214
|
+
`[打开 TokenWallet 配对页面](${created.webLink})`,
|
|
215
|
+
`配对码:${created.code}`,
|
|
163
216
|
'',
|
|
164
217
|
provider === 'other' || (!localQuota && !args.meters?.length)
|
|
165
218
|
? sourceHelp[provider] ?? '等待首次额度上报。'
|
|
166
219
|
: '',
|
|
167
|
-
'
|
|
220
|
+
'配对页面在配对码下方也会显示二维码。扫码或输入配对码后,可调用 `check_connection_status` 确认连接。',
|
|
221
|
+
...(update.updateAvailable ? ['', describeUpdate(update)] : []),
|
|
168
222
|
].join('\n');
|
|
169
223
|
return {
|
|
224
|
+
structuredContent: {
|
|
225
|
+
pairingCode: created.code,
|
|
226
|
+
pairingUrl: created.webLink,
|
|
227
|
+
qrImageUrl,
|
|
228
|
+
deepLink: created.deepLink,
|
|
229
|
+
expiresAt: created.expiresAt,
|
|
230
|
+
},
|
|
170
231
|
content: [
|
|
171
232
|
{
|
|
172
233
|
type: 'image',
|
|
@@ -184,20 +245,22 @@ export function createTokenWalletMcpServer() {
|
|
|
184
245
|
title: 'Check TokenWallet Connection Status',
|
|
185
246
|
description: 'Poll pending QR pairing sessions and report currently connected TokenWallet cards.',
|
|
186
247
|
inputSchema: {
|
|
248
|
+
provider: providerInput,
|
|
187
249
|
sessionId: z.string().optional().describe('Optional specific pending sessionId to poll'),
|
|
188
250
|
},
|
|
189
|
-
}, async ({ sessionId }) => {
|
|
190
|
-
const
|
|
251
|
+
}, async ({ sessionId, provider: requested }) => {
|
|
252
|
+
const provider = getProvider(requested);
|
|
253
|
+
const cfg = loadConfig(provider);
|
|
191
254
|
const targets = sessionId
|
|
192
255
|
? cfg.pendingSessions.filter((s) => s.sessionId === sessionId)
|
|
193
256
|
: cfg.pendingSessions;
|
|
194
257
|
const newlyBound = [];
|
|
195
258
|
for (const s of targets) {
|
|
196
|
-
const bound = await tryPollPendingSession(s);
|
|
259
|
+
const bound = await tryPollPendingSession(s, provider);
|
|
197
260
|
if (bound)
|
|
198
261
|
newlyBound.push(bound);
|
|
199
262
|
}
|
|
200
|
-
const updated = loadConfig();
|
|
263
|
+
const updated = loadConfig(provider);
|
|
201
264
|
const lines = [];
|
|
202
265
|
if (newlyBound.length > 0) {
|
|
203
266
|
lines.push(`新完成绑定 ${newlyBound.length} 张卡片:`);
|
|
@@ -225,14 +288,15 @@ export function createTokenWalletMcpServer() {
|
|
|
225
288
|
description: 'Push real-time remaining token quota or balance meters to a bound TokenWallet card.',
|
|
226
289
|
inputSchema: {
|
|
227
290
|
cardId: z.string().optional().describe('Target cardId; may be omitted when exactly one card matches'),
|
|
228
|
-
provider:
|
|
291
|
+
provider: providerInput,
|
|
229
292
|
plan: z.string().optional().describe('Optional updated plan name, e.g. "Plus", "Pro"'),
|
|
230
293
|
accountHint: z.string().optional().describe('Optional masked account hint'),
|
|
231
294
|
meters: z.array(meterSchema).min(1).describe('One or more quota meters to report'),
|
|
232
295
|
},
|
|
233
296
|
}, async (args) => {
|
|
234
|
-
|
|
235
|
-
|
|
297
|
+
const provider = getProvider(args.provider);
|
|
298
|
+
await syncAllPendingSessions(provider);
|
|
299
|
+
const cfg = loadConfig(provider);
|
|
236
300
|
const matches = cfg.connections.filter((c) => (!args.cardId || args.cardId === c.cardId) && provider === c.brand);
|
|
237
301
|
const conn = matches.length === 1 ? matches[0] : undefined;
|
|
238
302
|
if (!conn) {
|
|
@@ -246,7 +310,7 @@ export function createTokenWalletMcpServer() {
|
|
|
246
310
|
],
|
|
247
311
|
};
|
|
248
312
|
}
|
|
249
|
-
const baseUrl = getApiBaseUrl();
|
|
313
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
250
314
|
const now = Date.now();
|
|
251
315
|
const res = await apiSubmitReport(baseUrl, conn.writeToken, {
|
|
252
316
|
plan: args.plan,
|
|
@@ -257,7 +321,7 @@ export function createTokenWalletMcpServer() {
|
|
|
257
321
|
observedAt: now,
|
|
258
322
|
})),
|
|
259
323
|
});
|
|
260
|
-
markConnectionReported(conn.cardId, now);
|
|
324
|
+
markConnectionReported(conn.cardId, now, provider);
|
|
261
325
|
return {
|
|
262
326
|
content: [
|
|
263
327
|
{
|
|
@@ -271,13 +335,14 @@ export function createTokenWalletMcpServer() {
|
|
|
271
335
|
title: 'Sync Real Local AI Client Quotas',
|
|
272
336
|
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.',
|
|
273
337
|
inputSchema: {
|
|
274
|
-
provider:
|
|
338
|
+
provider: providerInput,
|
|
275
339
|
cardId: z.string().optional().describe('Optional specific bound cardId'),
|
|
276
340
|
},
|
|
277
|
-
}, async ({ cardId }) => {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const
|
|
341
|
+
}, async ({ cardId, provider: requested }) => {
|
|
342
|
+
const provider = getProvider(requested);
|
|
343
|
+
await syncAllPendingSessions(provider);
|
|
344
|
+
const cfg = loadConfig(provider);
|
|
345
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
281
346
|
const conn = cfg.connections.find(c => c.brand === provider && (!cardId || c.cardId === cardId));
|
|
282
347
|
if (!conn)
|
|
283
348
|
return { isError: true, content: [{ type: 'text', text: '当前实例没有匹配的绑定。' }] };
|
|
@@ -288,22 +353,23 @@ export function createTokenWalletMcpServer() {
|
|
|
288
353
|
plan: snapshot.plan, accountHint: snapshot.accountHint,
|
|
289
354
|
observedAt: snapshot.observedAt, meters: snapshot.meters,
|
|
290
355
|
});
|
|
291
|
-
markConnectionReported(conn.cardId, Date.now());
|
|
356
|
+
markConnectionReported(conn.cardId, Date.now(), provider);
|
|
292
357
|
return { content: [{ type: 'text', text: '额度已同步至钱包。' }] };
|
|
293
358
|
});
|
|
294
359
|
server.registerTool('list_connections', {
|
|
295
360
|
title: 'List Connected TokenWallet Cards',
|
|
296
361
|
description: 'List all locally bound TokenWallet cards and verify their node connectivity.',
|
|
297
|
-
inputSchema: {},
|
|
298
|
-
}, async () => {
|
|
299
|
-
|
|
300
|
-
|
|
362
|
+
inputSchema: { provider: providerInput },
|
|
363
|
+
}, async ({ provider: requested }) => {
|
|
364
|
+
const provider = getProvider(requested);
|
|
365
|
+
await syncAllPendingSessions(provider);
|
|
366
|
+
const cfg = loadConfig(provider);
|
|
301
367
|
if (cfg.connections.length === 0) {
|
|
302
368
|
return {
|
|
303
369
|
content: [{ type: 'text', text: '当前没有已绑定的 TokenWallet 卡片。可调用 `connect_tokenwallet` 开始绑定。' }],
|
|
304
370
|
};
|
|
305
371
|
}
|
|
306
|
-
const baseUrl = getApiBaseUrl();
|
|
372
|
+
const baseUrl = getApiBaseUrl(provider);
|
|
307
373
|
const lines = [`API 地址:${baseUrl}`, `已绑定卡片 (${cfg.connections.length}):`];
|
|
308
374
|
for (const conn of cfg.connections) {
|
|
309
375
|
let status = 'online';
|
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');
|