tokenwallet-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # tokenwallet-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TokenWallet 官方 MCP Server。安装后通过手机 App 扫码绑定,即可**自动读取本机 AI 客户端(如 Codex CLI)的真实剩余额度与重置时间**并定时同步到 TokenWallet App,无需每次对话手动触发。
4
+
5
+ ## 一行命令安装(推荐)
6
+
7
+ ### Codex CLI
8
+ ```bash
9
+ codex mcp add tokenwallet -- npx -y tokenwallet-mcp
10
+ ```
11
+
12
+ ### Claude Code
13
+ ```bash
14
+ claude mcp add tokenwallet -- npx -y tokenwallet-mcp
15
+ ```
16
+
17
+ ### Claude Desktop / Cursor
18
+ 在 MCP 配置文件中添加:
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "tokenwallet": {
23
+ "command": "npx",
24
+ "args": ["-y", "tokenwallet-mcp"]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ ## 使用方式
31
+
32
+ 1. 安装完成后,在客户端对话中说:**「帮我连接 TokenWallet,生成绑定二维码」**;
33
+ 2. 打开手机 TokenWallet App → 点击 `+` → 选择对应平台 → 点击「扫描二维码」完成绑定(支持免登录直接扫码);
34
+ 3. 绑定后,本机 MCP 会每 60 秒自动检测最新真实额度并静默上报到 `https://api.token-wallet.app/v1`。
35
+
36
+ ## 提供的工具
37
+
38
+ - `connect_tokenwallet`:生成配对二维码与链接(若本机有 Codex 日志会自动附带当前真实 5h / 周额度与精确重置时间)
39
+ - `sync_codex_quota`:立即读取本机 `~/.codex/sessions` 最新真实额度并上报
40
+ - `report_quota`:向已绑定卡片上报自定义额度指标
41
+ - `check_connection_status`:检查待扫码会话与已绑定卡片
42
+ - `list_connections`:查看已绑定卡片及节点在线状态
43
+
44
+ ## 环境变量
45
+
46
+ - `TOKENWALLET_API_URL`:后端 API 地址,默认 `https://api.token-wallet.app/v1`
47
+ - `CODEX_HOME`:自定义 Codex 数据目录,默认 `~/.codex`
48
+ - `TOKENWALLET_MCP_HOME`:本地节点凭证目录,默认 `~/.tokenwallet-mcp`
49
+
50
+ ## 自托管远程模式(Streamable HTTP)
51
+
52
+ ```bash
53
+ npx -y tokenwallet-mcp --http --port 8788
54
+ ```
package/dist/api.js ADDED
@@ -0,0 +1,49 @@
1
+ async function requestJson(baseUrl, pathname, options = {}) {
2
+ const url = `${baseUrl.replace(/\/+$/, '')}${pathname}`;
3
+ const headers = {
4
+ Accept: 'application/json',
5
+ 'Content-Type': 'application/json; charset=utf-8',
6
+ };
7
+ if (options.token) {
8
+ headers.Authorization = `Bearer ${options.token}`;
9
+ }
10
+ const res = await fetch(url, {
11
+ method: options.method ?? 'GET',
12
+ headers,
13
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
14
+ });
15
+ const data = (await res.json().catch(() => null));
16
+ if (!res.ok) {
17
+ const msg = data?.error?.message || `TokenWallet API error (${res.status})`;
18
+ const err = new Error(msg);
19
+ err.code = data?.error?.code;
20
+ err.status = res.status;
21
+ throw err;
22
+ }
23
+ return data;
24
+ }
25
+ export function apiCreateMcpSession(baseUrl, params) {
26
+ return requestJson(baseUrl, '/mcp/sessions', {
27
+ method: 'POST',
28
+ body: params,
29
+ });
30
+ }
31
+ export function apiPollMcpSession(baseUrl, sessionId, pollToken) {
32
+ return requestJson(baseUrl, `/mcp/sessions/${encodeURIComponent(sessionId)}/poll`, { method: 'GET', token: pollToken });
33
+ }
34
+ export function apiSubmitReport(baseUrl, writeToken, params) {
35
+ return requestJson(baseUrl, '/reports', {
36
+ method: 'POST',
37
+ token: writeToken,
38
+ body: {
39
+ ...params,
40
+ observedAt: params.observedAt ?? Date.now(),
41
+ },
42
+ });
43
+ }
44
+ export function apiPingNode(baseUrl, writeToken) {
45
+ return requestJson(baseUrl, '/reports/ping', {
46
+ method: 'GET',
47
+ token: writeToken,
48
+ });
49
+ }
@@ -0,0 +1,146 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ function normalizePlan(planType) {
5
+ if (!planType)
6
+ return undefined;
7
+ switch (planType.toLowerCase()) {
8
+ case 'plus':
9
+ return 'Plus';
10
+ case 'pro':
11
+ return 'Pro';
12
+ case 'team':
13
+ return 'Team';
14
+ case 'enterprise':
15
+ return 'Enterprise';
16
+ default:
17
+ return planType.charAt(0).toUpperCase() + planType.slice(1);
18
+ }
19
+ }
20
+ function collectJsonlFiles(rootDir) {
21
+ const results = [];
22
+ function walk(dir) {
23
+ let entries;
24
+ try {
25
+ entries = fs.readdirSync(dir, { withFileTypes: true });
26
+ }
27
+ catch {
28
+ return;
29
+ }
30
+ for (const entry of entries) {
31
+ const fullPath = path.join(dir, entry.name);
32
+ if (entry.isDirectory()) {
33
+ walk(fullPath);
34
+ }
35
+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
36
+ try {
37
+ const stat = fs.statSync(fullPath);
38
+ results.push({ filePath: fullPath, mtimeMs: stat.mtimeMs });
39
+ }
40
+ catch {
41
+ // Ignore unreadable file
42
+ }
43
+ }
44
+ }
45
+ }
46
+ walk(rootDir);
47
+ results.sort((a, b) => b.mtimeMs - a.mtimeMs);
48
+ return results;
49
+ }
50
+ function toEpochMs(raw) {
51
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0)
52
+ return undefined;
53
+ // Codex stores resets_at in Unix seconds (~1.79e9); convert to ms if < 1e12
54
+ return raw < 1_000_000_000_000 ? Math.round(raw * 1000) : Math.round(raw);
55
+ }
56
+ function toRemainingPercent(usedPercent) {
57
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent))
58
+ return undefined;
59
+ const remaining = Math.max(0, Math.min(100, 100 - usedPercent));
60
+ return Math.round(remaining * 10) / 10;
61
+ }
62
+ function parseLatestRateLimitsFromFile(filePath) {
63
+ let content;
64
+ try {
65
+ content = fs.readFileSync(filePath, 'utf8');
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ const lines = content.split(/\r?\n/);
71
+ for (let i = lines.length - 1; i >= 0; i--) {
72
+ const line = lines[i];
73
+ if (!line || !line.includes('"rate_limits"'))
74
+ continue;
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(line);
78
+ }
79
+ catch {
80
+ continue;
81
+ }
82
+ const rl = parsed.payload?.rate_limits;
83
+ if (!rl || (!rl.primary && !rl.secondary))
84
+ continue;
85
+ const observedAt = (parsed.timestamp ? Date.parse(parsed.timestamp) : NaN) || Date.now();
86
+ const meters = [];
87
+ if (rl.primary) {
88
+ const remaining = toRemainingPercent(rl.primary.used_percent);
89
+ if (remaining !== undefined) {
90
+ const is5h = !rl.primary.window_minutes || rl.primary.window_minutes <= 360;
91
+ meters.push({
92
+ meterKey: is5h ? '5h' : `w${rl.primary.window_minutes}m`,
93
+ product: rl.limit_id || 'codex',
94
+ label: is5h ? '5 小时' : `${Math.round((rl.primary.window_minutes ?? 300) / 60)} 小时`,
95
+ kind: 'percent',
96
+ window: is5h ? '5h' : 'rolling',
97
+ remaining,
98
+ total: 100,
99
+ unit: '%',
100
+ resetsAt: toEpochMs(rl.primary.resets_at),
101
+ observedAt,
102
+ });
103
+ }
104
+ }
105
+ if (rl.secondary) {
106
+ const remaining = toRemainingPercent(rl.secondary.used_percent);
107
+ if (remaining !== undefined) {
108
+ const isWeek = !rl.secondary.window_minutes || rl.secondary.window_minutes >= 7200;
109
+ meters.push({
110
+ meterKey: isWeek ? '7d' : `w${rl.secondary.window_minutes}m`,
111
+ product: rl.limit_id || 'codex',
112
+ label: isWeek ? '每周额度' : `${Math.round((rl.secondary.window_minutes ?? 10080) / 1440)} 天额度`,
113
+ kind: 'percent',
114
+ window: isWeek ? 'week' : 'rolling',
115
+ remaining,
116
+ total: 100,
117
+ unit: '%',
118
+ resetsAt: toEpochMs(rl.secondary.resets_at),
119
+ observedAt,
120
+ });
121
+ }
122
+ }
123
+ if (meters.length > 0) {
124
+ return {
125
+ plan: normalizePlan(rl.plan_type),
126
+ observedAt,
127
+ sourceFile: filePath,
128
+ meters,
129
+ };
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+ export function readLatestCodexQuota() {
135
+ const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
136
+ const sessionsDir = path.join(codexHome, 'sessions');
137
+ if (!fs.existsSync(sessionsDir))
138
+ return null;
139
+ const files = collectJsonlFiles(sessionsDir).slice(0, 8);
140
+ for (const { filePath } of files) {
141
+ const snap = parseLatestRateLimitsFromFile(filePath);
142
+ if (snap)
143
+ return snap;
144
+ }
145
+ return null;
146
+ }
package/dist/config.js ADDED
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ const DEFAULT_API_URL = process.env.TOKENWALLET_API_URL || 'https://api.token-wallet.app/v1';
5
+ const CONFIG_DIR = process.env.TOKENWALLET_MCP_HOME || path.join(os.homedir(), '.tokenwallet-mcp');
6
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
7
+ export function getApiBaseUrl() {
8
+ const cfg = loadConfig();
9
+ return (process.env.TOKENWALLET_API_URL || cfg.apiBaseUrl || DEFAULT_API_URL).replace(/\/+$/, '');
10
+ }
11
+ export function loadConfig() {
12
+ try {
13
+ if (fs.existsSync(CONFIG_FILE)) {
14
+ const parsed = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
15
+ return {
16
+ apiBaseUrl: parsed.apiBaseUrl || DEFAULT_API_URL,
17
+ connections: Array.isArray(parsed.connections) ? parsed.connections : [],
18
+ pendingSessions: Array.isArray(parsed.pendingSessions) ? parsed.pendingSessions : [],
19
+ };
20
+ }
21
+ }
22
+ catch {
23
+ // Fall through to default config
24
+ }
25
+ return {
26
+ apiBaseUrl: DEFAULT_API_URL,
27
+ connections: [],
28
+ pendingSessions: [],
29
+ };
30
+ }
31
+ export function saveConfig(config) {
32
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
33
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
34
+ }
35
+ export function savePendingSession(session) {
36
+ const cfg = loadConfig();
37
+ const now = Date.now();
38
+ const active = cfg.pendingSessions.filter((s) => s.sessionId !== session.sessionId && s.expiresAt > now);
39
+ active.unshift(session);
40
+ cfg.pendingSessions = active.slice(0, 10);
41
+ saveConfig(cfg);
42
+ }
43
+ export function removePendingSession(sessionId) {
44
+ const cfg = loadConfig();
45
+ cfg.pendingSessions = cfg.pendingSessions.filter((s) => s.sessionId !== sessionId);
46
+ saveConfig(cfg);
47
+ }
48
+ export function upsertBoundConnection(conn) {
49
+ const cfg = loadConfig();
50
+ const existingIdx = cfg.connections.findIndex((c) => c.cardId === conn.cardId);
51
+ if (existingIdx >= 0) {
52
+ cfg.connections[existingIdx] = conn;
53
+ }
54
+ else {
55
+ cfg.connections.unshift(conn);
56
+ }
57
+ saveConfig(cfg);
58
+ }
59
+ export function markConnectionReported(cardId, reportedAt = Date.now()) {
60
+ const cfg = loadConfig();
61
+ const target = cfg.connections.find((c) => c.cardId === cardId);
62
+ if (target) {
63
+ target.lastReportedAt = reportedAt;
64
+ saveConfig(cfg);
65
+ }
66
+ }
package/dist/index.js ADDED
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ import http from 'node:http';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
+ import { apiSubmitReport } from './api.js';
6
+ import { readLatestCodexQuota } from './codex-reader.js';
7
+ import { getApiBaseUrl, loadConfig, markConnectionReported } from './config.js';
8
+ import { createTokenWalletMcpServer } from './server.js';
9
+ function parseArgs() {
10
+ const argv = process.argv.slice(2);
11
+ const useHttp = argv.includes('--http') || process.env.MCP_TRANSPORT === 'http';
12
+ const portIdx = argv.indexOf('--port');
13
+ const port = (portIdx >= 0 && Number(argv[portIdx + 1])) ||
14
+ Number(process.env.PORT) ||
15
+ 8788;
16
+ return { useHttp, port };
17
+ }
18
+ function startLocalCodexAutoReporter() {
19
+ let lastObservedAt = 0;
20
+ const tick = async () => {
21
+ try {
22
+ const snap = readLatestCodexQuota();
23
+ if (!snap || snap.observedAt <= lastObservedAt)
24
+ return;
25
+ const cfg = loadConfig();
26
+ const openaiConns = cfg.connections.filter((c) => c.brand === 'openai');
27
+ if (openaiConns.length === 0)
28
+ return;
29
+ const baseUrl = getApiBaseUrl();
30
+ for (const conn of openaiConns) {
31
+ await apiSubmitReport(baseUrl, conn.writeToken, {
32
+ plan: snap.plan,
33
+ observedAt: snap.observedAt,
34
+ meters: snap.meters,
35
+ });
36
+ markConnectionReported(conn.cardId, Date.now());
37
+ }
38
+ lastObservedAt = snap.observedAt;
39
+ }
40
+ catch {
41
+ // Ignore transient network errors during background sync
42
+ }
43
+ };
44
+ void tick();
45
+ const timer = setInterval(() => {
46
+ void tick();
47
+ }, 60_000);
48
+ timer.unref();
49
+ }
50
+ async function startStdio() {
51
+ const server = createTokenWalletMcpServer();
52
+ const transport = new StdioServerTransport();
53
+ await server.connect(transport);
54
+ startLocalCodexAutoReporter();
55
+ console.error(`[tokenwallet-mcp] stdio ready (API: ${getApiBaseUrl()})`);
56
+ }
57
+ async function startHttp(port) {
58
+ const httpServer = http.createServer(async (req, res) => {
59
+ res.setHeader('Access-Control-Allow-Origin', '*');
60
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
61
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Mcp-Session-Id');
62
+ if (req.method === 'OPTIONS') {
63
+ res.writeHead(204);
64
+ res.end();
65
+ return;
66
+ }
67
+ const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
68
+ const pathname = url.pathname.replace(/\/+$/, '') || '/';
69
+ const acceptHeader = String(req.headers.accept || '');
70
+ const isBrowserHealthCheck = req.method === 'GET' &&
71
+ (pathname === '/health' || (pathname === '/' && !acceptHeader.includes('text/event-stream')));
72
+ if (isBrowserHealthCheck) {
73
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
74
+ res.end(JSON.stringify({
75
+ ok: true,
76
+ service: 'tokenwallet-mcp',
77
+ transport: 'streamable-http',
78
+ mcpEndpoint: '/',
79
+ apiBaseUrl: getApiBaseUrl(),
80
+ }));
81
+ return;
82
+ }
83
+ if (pathname === '/' || pathname === '/mcp') {
84
+ try {
85
+ const server = createTokenWalletMcpServer();
86
+ const transport = new StreamableHTTPServerTransport({
87
+ sessionIdGenerator: undefined,
88
+ });
89
+ res.on('close', () => {
90
+ void transport.close();
91
+ void server.close();
92
+ });
93
+ await server.connect(transport);
94
+ await transport.handleRequest(req, res);
95
+ }
96
+ catch (err) {
97
+ console.error('[tokenwallet-mcp] HTTP error:', err);
98
+ if (!res.headersSent) {
99
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
100
+ res.end(JSON.stringify({ error: err instanceof Error ? err.message : 'Internal server error' }));
101
+ }
102
+ }
103
+ return;
104
+ }
105
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
106
+ res.end(JSON.stringify({ error: 'Not Found. Use / or /mcp for Streamable HTTP MCP.' }));
107
+ });
108
+ const host = process.env.HOST || '0.0.0.0';
109
+ httpServer.listen(port, host, () => {
110
+ console.log(`[tokenwallet-mcp] Streamable HTTP listening on http://${host}:${port}/mcp`);
111
+ console.log(`[tokenwallet-mcp] TokenWallet API: ${getApiBaseUrl()}`);
112
+ });
113
+ }
114
+ const { useHttp, port } = parseArgs();
115
+ if (useHttp) {
116
+ await startHttp(port);
117
+ }
118
+ else {
119
+ await startStdio();
120
+ }
package/dist/server.js ADDED
@@ -0,0 +1,336 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import QRCode from 'qrcode';
3
+ import { z } from 'zod';
4
+ import { apiCreateMcpSession, apiPingNode, apiPollMcpSession, apiSubmitReport, } from './api.js';
5
+ import { readLatestCodexQuota } from './codex-reader.js';
6
+ import { getApiBaseUrl, loadConfig, markConnectionReported, removePendingSession, savePendingSession, upsertBoundConnection, } from './config.js';
7
+ const meterSchema = z.object({
8
+ meterKey: z.string().min(1).describe('Unique meter key, e.g. "5h", "7d", "balance:USD"'),
9
+ product: z.string().optional().describe('Product identifier, e.g. "chatgpt", "codex", "claude-code"'),
10
+ 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'),
12
+ window: z.enum(['5h', 'day', 'week', 'month', 'rolling']).optional(),
13
+ modelGroup: z.string().optional(),
14
+ remaining: z.number().describe('Remaining amount or percentage (0-100)'),
15
+ total: z.number().optional().describe('Total quota if applicable (e.g. 100 for percent)'),
16
+ unit: z.string().optional().describe('Unit such as "%", "USD", "CNY", "credits"'),
17
+ resetsAt: z.number().optional().describe('Reset timestamp in epoch milliseconds'),
18
+ });
19
+ const activePollTimers = new Map();
20
+ async function tryPollPendingSession(session) {
21
+ const baseUrl = getApiBaseUrl();
22
+ try {
23
+ const res = await apiPollMcpSession(baseUrl, session.sessionId, session.pollToken);
24
+ if (res.status === 'authorized' && res.writeToken && res.cardId && res.nodeId) {
25
+ const bound = {
26
+ cardId: res.cardId,
27
+ nodeId: res.nodeId,
28
+ brand: session.brand,
29
+ provider: session.provider,
30
+ writeToken: res.writeToken,
31
+ fingerprintSalt: res.fingerprintSalt,
32
+ connectedAt: Date.now(),
33
+ };
34
+ upsertBoundConnection(bound);
35
+ removePendingSession(session.sessionId);
36
+ stopBackgroundPoll(session.sessionId);
37
+ return bound;
38
+ }
39
+ if (res.status === 'expired') {
40
+ removePendingSession(session.sessionId);
41
+ stopBackgroundPoll(session.sessionId);
42
+ }
43
+ }
44
+ catch {
45
+ // Ignore transient network errors during background polling
46
+ }
47
+ return null;
48
+ }
49
+ function stopBackgroundPoll(sessionId) {
50
+ const timer = activePollTimers.get(sessionId);
51
+ if (timer) {
52
+ clearInterval(timer);
53
+ activePollTimers.delete(sessionId);
54
+ }
55
+ }
56
+ function startBackgroundPoll(session) {
57
+ stopBackgroundPoll(session.sessionId);
58
+ const timer = setInterval(() => {
59
+ if (Date.now() > session.expiresAt) {
60
+ removePendingSession(session.sessionId);
61
+ stopBackgroundPoll(session.sessionId);
62
+ return;
63
+ }
64
+ void tryPollPendingSession(session);
65
+ }, 3000);
66
+ timer.unref();
67
+ activePollTimers.set(session.sessionId, timer);
68
+ }
69
+ async function syncAllPendingSessions() {
70
+ const cfg = loadConfig();
71
+ const newlyBound = [];
72
+ for (const session of cfg.pendingSessions) {
73
+ const bound = await tryPollPendingSession(session);
74
+ if (bound)
75
+ newlyBound.push(bound);
76
+ }
77
+ return newlyBound;
78
+ }
79
+ export function createTokenWalletMcpServer() {
80
+ const server = new McpServer({
81
+ name: 'tokenwallet-mcp',
82
+ version: '1.0.0',
83
+ });
84
+ server.registerTool('connect_tokenwallet', {
85
+ title: 'Connect to TokenWallet App',
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
+ inputSchema: {
88
+ brand: z
89
+ .enum(['openai', 'claude', 'gemini', 'openrouter', 'deepseek', 'other'])
90
+ .default('openai')
91
+ .describe('Provider brand (use "openai" for ChatGPT, "claude" for Claude, "gemini" for Google AI, "other" for custom)'),
92
+ provider: z.string().optional().describe('Custom display name for the provider'),
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"'),
95
+ plan: z.string().optional().describe('Subscription plan name, e.g. "Plus", "Pro", "AI Pro"'),
96
+ accountHint: z.string().optional().describe('Optional masked account hint, e.g. "u***@gmail.com"'),
97
+ meters: z.array(meterSchema).optional().describe('Optional initial quota meters to populate immediately upon scan'),
98
+ },
99
+ }, async (args) => {
100
+ const baseUrl = getApiBaseUrl();
101
+ const localCodex = args.brand === 'openai' && (!args.meters || args.meters.length === 0)
102
+ ? readLatestCodexQuota()
103
+ : null;
104
+ const created = await apiCreateMcpSession(baseUrl, {
105
+ brand: args.brand,
106
+ provider: args.provider,
107
+ nodeLabel: args.nodeLabel,
108
+ source: args.source ?? (localCodex ? 'codex' : 'mcp'),
109
+ plan: args.plan ?? localCodex?.plan,
110
+ accountHint: args.accountHint,
111
+ meters: args.meters ?? localCodex?.meters,
112
+ });
113
+ const pending = {
114
+ sessionId: created.sessionId,
115
+ mcpCode: created.mcpCode,
116
+ pollToken: created.pollToken,
117
+ brand: created.brand,
118
+ provider: created.provider,
119
+ deepLink: created.deepLink,
120
+ webLink: created.webLink,
121
+ expiresAt: created.expiresAt,
122
+ createdAt: Date.now(),
123
+ };
124
+ savePendingSession(pending);
125
+ startBackgroundPoll(pending);
126
+ const qrDataUrl = await QRCode.toDataURL(created.qrPayload, {
127
+ width: 320,
128
+ margin: 2,
129
+ });
130
+ const base64Png = qrDataUrl.replace(/^data:image\/png;base64,/, '');
131
+ const asciiQr = await QRCode.toString(created.qrPayload, { type: 'utf8' });
132
+ const expiresInMin = Math.max(1, Math.round((created.expiresAt - Date.now()) / 60_000));
133
+ const summary = [
134
+ `请打开 TokenWallet App,进入「添加卡片 → ${created.provider}」,点击「扫描二维码」扫描下方二维码即可完成连接(有效期约 ${expiresInMin} 分钟):`,
135
+ '',
136
+ `连接码:${created.mcpCode}`,
137
+ `手机直达链接:${created.deepLink}`,
138
+ `网页跳转链接:${created.webLink}`,
139
+ '',
140
+ '```',
141
+ asciiQr.trimEnd(),
142
+ '```',
143
+ '',
144
+ '扫码后本 MCP 会自动完成配对并保存只写上报凭证;也可以调用 `check_connection_status` 立即确认绑定状态。',
145
+ ].join('\n');
146
+ return {
147
+ content: [
148
+ {
149
+ type: 'image',
150
+ data: base64Png,
151
+ mimeType: 'image/png',
152
+ },
153
+ {
154
+ type: 'text',
155
+ text: summary,
156
+ },
157
+ ],
158
+ };
159
+ });
160
+ server.registerTool('check_connection_status', {
161
+ title: 'Check TokenWallet Connection Status',
162
+ description: 'Poll pending QR pairing sessions and report currently connected TokenWallet cards.',
163
+ inputSchema: {
164
+ sessionId: z.string().optional().describe('Optional specific pending sessionId to poll'),
165
+ },
166
+ }, async ({ sessionId }) => {
167
+ const cfg = loadConfig();
168
+ const targets = sessionId
169
+ ? cfg.pendingSessions.filter((s) => s.sessionId === sessionId)
170
+ : cfg.pendingSessions;
171
+ const newlyBound = [];
172
+ for (const s of targets) {
173
+ const bound = await tryPollPendingSession(s);
174
+ if (bound)
175
+ newlyBound.push(bound);
176
+ }
177
+ const updated = loadConfig();
178
+ const lines = [];
179
+ if (newlyBound.length > 0) {
180
+ lines.push(`新完成绑定 ${newlyBound.length} 张卡片:`);
181
+ for (const c of newlyBound) {
182
+ lines.push(`- ${c.provider} (${c.brand}) · cardId=${c.cardId}`);
183
+ }
184
+ }
185
+ else if (updated.pendingSessions.length > 0) {
186
+ lines.push(`仍有 ${updated.pendingSessions.length} 个等待扫码的会话(最新连接码:${updated.pendingSessions[0].mcpCode})。`);
187
+ }
188
+ else {
189
+ lines.push('当前没有等待中的扫码会话。');
190
+ }
191
+ lines.push('');
192
+ lines.push(`已绑定卡片总数:${updated.connections.length}`);
193
+ for (const c of updated.connections) {
194
+ lines.push(`- ${c.provider} (${c.brand}) · cardId=${c.cardId}`);
195
+ }
196
+ return {
197
+ content: [{ type: 'text', text: lines.join('\n') }],
198
+ };
199
+ });
200
+ server.registerTool('report_quota', {
201
+ title: 'Report Quota to TokenWallet',
202
+ description: 'Push real-time remaining token quota or balance meters to a bound TokenWallet card.',
203
+ inputSchema: {
204
+ cardId: z.string().optional().describe('Target cardId (optional; defaults to matching brand or latest bound card)'),
205
+ brand: z.string().optional().describe('Brand filter when cardId is omitted, e.g. "openai", "claude"'),
206
+ plan: z.string().optional().describe('Optional updated plan name, e.g. "Plus", "Pro"'),
207
+ accountHint: z.string().optional().describe('Optional masked account hint'),
208
+ meters: z.array(meterSchema).min(1).describe('One or more quota meters to report'),
209
+ },
210
+ }, async (args) => {
211
+ await syncAllPendingSessions();
212
+ const cfg = loadConfig();
213
+ const conn = (args.cardId && cfg.connections.find((c) => c.cardId === args.cardId)) ||
214
+ (args.brand && cfg.connections.find((c) => c.brand === args.brand)) ||
215
+ cfg.connections[0];
216
+ if (!conn) {
217
+ return {
218
+ isError: true,
219
+ content: [
220
+ {
221
+ type: 'text',
222
+ text: '尚未绑定任何 TokenWallet 卡片。请先调用 `connect_tokenwallet` 生成二维码并在手机 App 中扫码绑定。',
223
+ },
224
+ ],
225
+ };
226
+ }
227
+ const baseUrl = getApiBaseUrl();
228
+ const now = Date.now();
229
+ const res = await apiSubmitReport(baseUrl, conn.writeToken, {
230
+ plan: args.plan,
231
+ accountHint: args.accountHint,
232
+ observedAt: now,
233
+ meters: args.meters.map((m) => ({
234
+ ...m,
235
+ observedAt: now,
236
+ })),
237
+ });
238
+ markConnectionReported(conn.cardId, now);
239
+ return {
240
+ content: [
241
+ {
242
+ type: 'text',
243
+ text: `已上报 ${conn.provider}(cardId=${res.cardId})最新额度,更新字段:${res.updatedMeters.join(', ') || '无'},服务端版本 rev=${res.revision}。`,
244
+ },
245
+ ],
246
+ };
247
+ });
248
+ server.registerTool('sync_codex_quota', {
249
+ title: 'Sync Real Local Codex CLI Quota',
250
+ description: 'Read the latest real 5-hour and weekly rate_limits (with exact reset timestamps) from local ~/.codex/sessions logs and push them to the bound ChatGPT/OpenAI card in TokenWallet.',
251
+ inputSchema: {
252
+ cardId: z.string().optional().describe('Optional target cardId (defaults to bound openai card)'),
253
+ },
254
+ }, async ({ cardId }) => {
255
+ 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
+ const cfg = loadConfig();
269
+ const conn = (cardId && cfg.connections.find((c) => c.cardId === cardId)) ||
270
+ cfg.connections.find((c) => c.brand === 'openai') ||
271
+ cfg.connections[0];
272
+ if (!conn) {
273
+ return {
274
+ isError: true,
275
+ content: [
276
+ {
277
+ type: 'text',
278
+ text: `已读取本机真实 Codex 额度(${snapshot.meters.map((m) => `${m.label}: ${m.remaining}%`).join(',')}),但尚未绑定 TokenWallet 卡片。请先调用 connect_tokenwallet 扫码绑定。`,
279
+ },
280
+ ],
281
+ };
282
+ }
283
+ const baseUrl = getApiBaseUrl();
284
+ const res = await apiSubmitReport(baseUrl, conn.writeToken, {
285
+ plan: snapshot.plan,
286
+ observedAt: snapshot.observedAt,
287
+ meters: snapshot.meters,
288
+ });
289
+ markConnectionReported(conn.cardId, Date.now());
290
+ const details = snapshot.meters
291
+ .map((m) => {
292
+ const resetStr = m.resetsAt
293
+ ? `(重置:${new Date(m.resetsAt).toLocaleString('zh-CN', { hour12: false })})`
294
+ : '';
295
+ return `${m.label} ${m.remaining}%${resetStr}`;
296
+ })
297
+ .join(';');
298
+ return {
299
+ content: [
300
+ {
301
+ type: 'text',
302
+ text: `已同步本机真实 Codex 额度到 ${conn.provider}(cardId=${res.cardId}):${details}`,
303
+ },
304
+ ],
305
+ };
306
+ });
307
+ server.registerTool('list_connections', {
308
+ title: 'List Connected TokenWallet Cards',
309
+ description: 'List all locally bound TokenWallet cards and verify their node connectivity.',
310
+ inputSchema: {},
311
+ }, async () => {
312
+ await syncAllPendingSessions();
313
+ const cfg = loadConfig();
314
+ if (cfg.connections.length === 0) {
315
+ return {
316
+ content: [{ type: 'text', text: '当前没有已绑定的 TokenWallet 卡片。可调用 `connect_tokenwallet` 开始绑定。' }],
317
+ };
318
+ }
319
+ const baseUrl = getApiBaseUrl();
320
+ const lines = [`API 地址:${baseUrl}`, `已绑定卡片 (${cfg.connections.length}):`];
321
+ for (const conn of cfg.connections) {
322
+ let status = 'online';
323
+ try {
324
+ await apiPingNode(baseUrl, conn.writeToken);
325
+ }
326
+ catch (err) {
327
+ status = `error: ${err instanceof Error ? err.message : 'unreachable'}`;
328
+ }
329
+ lines.push(`- ${conn.provider} (${conn.brand}) · cardId=${conn.cardId} · 状态=${status}`);
330
+ }
331
+ return {
332
+ content: [{ type: 'text', text: lines.join('\n') }],
333
+ };
334
+ });
335
+ return server;
336
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "tokenwallet-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "TokenWallet MCP Server for QR pairing and automatic real-time AI token quota syncing",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "bin": {
9
+ "tokenwallet-mcp": "dist/index.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
18
+ "keywords": [
19
+ "mcp",
20
+ "model-context-protocol",
21
+ "tokenwallet",
22
+ "codex",
23
+ "chatgpt",
24
+ "claude",
25
+ "ai-quota"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/token-wallet-app/mcp.git"
30
+ },
31
+ "homepage": "https://token-wallet.app",
32
+ "scripts": {
33
+ "dev": "tsx src/index.ts",
34
+ "dev:http": "tsx src/index.ts --http",
35
+ "build": "tsc",
36
+ "prepublishOnly": "npm run build",
37
+ "start": "node dist/index.js",
38
+ "start:http": "node dist/index.js --http",
39
+ "typecheck": "tsc --noEmit"
40
+ },
41
+ "dependencies": {
42
+ "@modelcontextprotocol/sdk": "^1.25.2",
43
+ "qrcode": "^1.5.4",
44
+ "zod": "^3.25.76"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.15.0",
48
+ "@types/qrcode": "^1.5.5",
49
+ "tsx": "^4.19.4",
50
+ "typescript": "^5.8.3"
51
+ }
52
+ }