vpsyou-cn2 0.0.0-stage → 0.1.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,50 @@
1
- # Temporary Holding Version
1
+ # VPSYOU 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
+ Read CN2 latency and packet loss from the VPSYOU probe in Guangdong. This repository contains the connection guide and a from-source read-only client for the hosted MCP server. It does not contain the VPSYOU server implementation.
4
+
5
+ | Field | Value |
6
+ | --- | --- |
7
+ | Endpoint | `https://vpsyou.com/mcp` |
8
+ | Transport | Streamable HTTP |
9
+ | Authorization | OAuth. Approve read-only `cn2:read`. |
10
+ | Tool | `get_cn2_latency` (`live`, `24h`, `7d`) |
11
+ | Registry | `com.vpsyou/mcp` |
12
+
13
+ The service measures ICMP from that one probe to listed test endpoints. It does not provision or manage VPS instances, and it is not a global monitoring network.
14
+
15
+ Official product guides:
16
+
17
+ - English: <https://vpsyou.com/mcp-integration>
18
+ - 简体中文: <https://vpsyou.com/zh/mcp-integration>
19
+ - 繁體中文: <https://vpsyou.com/zh-TW/mcp-integration>
20
+
21
+ The checked connection record is [docs/mcp.md](docs/mcp.md): [OAuth metadata](docs/mcp.md#authorization), [request examples](docs/mcp.md#request-examples-from-the-integration-page), [target ids](docs/mcp.md#target-ids-advertised-on-2026-11-21), [Claude, Codex, and Grok Bot setup](docs/mcp.md#connect-a-documented-client), and [HTTP 401 troubleshooting](docs/mcp.md#oauth-and-http-401).
22
+
23
+ ## Command-line client
24
+
25
+ `vpsyou-cn2` calls `get_cn2_latency` on the endpoint above. `package.json` names the package `vpsyou-cn2` at version `0.1.0`. It is not yet published to npm, so install it from a checkout:
26
+
27
+ ```shell
28
+ npm install
29
+ npm run build
30
+ node dist/src/cli.js --help
31
+ ```
32
+
33
+ ```shell
34
+ node dist/src/cli.js login
35
+ node dist/src/cli.js targets
36
+ node dist/src/cli.js query --window live --json
37
+ node dist/src/cli.js logout
38
+ ```
39
+
40
+ `login` stores the sign-in in a user-only file and does not print it. `targets` lists the server's current windows and target ids. `query` defaults to `live`. Omit `--target` to omit `targetId`. Sign-in storage, scopes, and how to read the result are in [From-source client](docs/mcp.md#from-source-client).
41
+
42
+ ## Agent skill
43
+
44
+ Copy `skills/vpsyou-cn2-latency` into the skills folder your agent host loads. It is not a marketplace listing. The skill runs the same commands and links to [docs/mcp.md](docs/mcp.md).
45
+
46
+ ## What is in this repository
47
+
48
+ - [docs/mcp.md](docs/mcp.md) is the connection record.
49
+ - `src/` is the from-source client. `skills/vpsyou-cn2-latency/SKILL.md` is the agent skill.
50
+ - The MCP server runs at the hosted endpoint and is not published here.
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import { pathToFileURL } from "node:url";
4
+ import { CLIENT_VERSION, MCP_ENDPOINT, TOOL_NAME } from "./constants.js";
5
+ import { CredentialStore } from "./credentials.js";
6
+ import { CliError, exitCodeFor } from "./errors.js";
7
+ import { formatJson, formatQueryHuman, formatTargetsHuman, toolPayload } from "./format.js";
8
+ import { runLogin } from "./login.js";
9
+ import { buildToolArguments, findTool, targetsFromSchema, windowsFromSchema } from "./schema.js";
10
+ import { openQuerySession } from "./session.js";
11
+ export function parseArgs(argv) {
12
+ let json = false;
13
+ let windowValue;
14
+ let targetValue;
15
+ const positionals = [];
16
+ for (let index = 0; index < argv.length; index += 1) {
17
+ const arg = argv[index] ?? "";
18
+ if (arg === "--")
19
+ continue;
20
+ if (arg === "--json") {
21
+ json = true;
22
+ continue;
23
+ }
24
+ if (arg === "--help" || arg === "-h")
25
+ return { kind: "help" };
26
+ if (arg === "--version" || arg === "-V")
27
+ return { kind: "version" };
28
+ if (arg === "--endpoint" || arg.startsWith("--endpoint=")) {
29
+ throw new CliError("usage", `The MCP endpoint is fixed at ${MCP_ENDPOINT} and cannot be changed.`);
30
+ }
31
+ if (arg === "--window" || arg.startsWith("--window=")) {
32
+ windowValue = optionValue(argv, index, "--window");
33
+ if (arg === "--window")
34
+ index += 1;
35
+ continue;
36
+ }
37
+ if (arg === "--target" || arg.startsWith("--target=")) {
38
+ targetValue = optionValue(argv, index, "--target");
39
+ if (arg === "--target")
40
+ index += 1;
41
+ continue;
42
+ }
43
+ if (arg.startsWith("-"))
44
+ throw new CliError("usage", `Unknown option ${arg}. Run \`vpsyou-cn2 --help\`.`);
45
+ positionals.push(arg);
46
+ }
47
+ if (positionals.length === 0)
48
+ return { kind: "help" };
49
+ if (positionals.length > 1) {
50
+ throw new CliError("usage", `Unexpected argument ${positionals[1]}. Run \`vpsyou-cn2 --help\`.`);
51
+ }
52
+ const command = positionals[0];
53
+ if (windowValue !== undefined && command !== "query") {
54
+ throw new CliError("usage", "--window is only valid with query.");
55
+ }
56
+ if (targetValue !== undefined && command !== "query") {
57
+ throw new CliError("usage", "--target is only valid with query.");
58
+ }
59
+ if (command === "login")
60
+ return { kind: "login", json };
61
+ if (command === "logout")
62
+ return { kind: "logout", json };
63
+ if (command === "status")
64
+ return { kind: "status", json };
65
+ if (command === "targets")
66
+ return { kind: "targets", json };
67
+ if (command === "query")
68
+ return { kind: "query", json, window: windowValue, target: targetValue };
69
+ throw new CliError("usage", `Unknown command ${command}. Run \`vpsyou-cn2 --help\`.`);
70
+ }
71
+ export function helpText() {
72
+ return `vpsyou-cn2 ${CLIENT_VERSION}
73
+
74
+ Read CN2 latency and packet loss from the VPSYOU probe in Guangdong.
75
+ The endpoint is fixed at ${MCP_ENDPOINT} (Streamable HTTP, OAuth).
76
+ This client does not manage VPS instances and is not a global monitoring network.
77
+
78
+ The package name is vpsyou-cn2. It is not yet published to npm.
79
+ From a checkout of this repository, build it and run:
80
+
81
+ npm install
82
+ npm run build
83
+ node dist/src/cli.js --help
84
+
85
+ Usage:
86
+ vpsyou-cn2 login
87
+ vpsyou-cn2 logout
88
+ vpsyou-cn2 status [--json]
89
+ vpsyou-cn2 targets [--json]
90
+ vpsyou-cn2 query [--window live|24h|7d] [--target <id>] [--json]
91
+
92
+ login Sign in with the browser and approve read-only cn2:read.
93
+ The sign-in stays in a user-only file under your config directory.
94
+ logout Delete that local sign-in file.
95
+ status Say whether a local sign-in is stored. This does not call the server.
96
+ targets List windows and target ids from the server's current ${TOOL_NAME} schema.
97
+ query Call ${TOOL_NAME}. The default window is live. Omit --target to omit targetId.
98
+
99
+ Set VPSYOU_CN2_CONFIG_DIR to choose the private directory for the sign-in file.
100
+ That variable does not change the MCP endpoint.
101
+ `;
102
+ }
103
+ export async function run(argv, runtime = defaultRuntime()) {
104
+ try {
105
+ const command = parseArgs(argv);
106
+ if (command.kind === "help") {
107
+ runtime.stdout(helpText());
108
+ return 0;
109
+ }
110
+ if (command.kind === "version") {
111
+ runtime.stdout(`${CLIENT_VERSION}\n`);
112
+ return 0;
113
+ }
114
+ if (command.kind === "login") {
115
+ await runtime.login();
116
+ write(runtime, command.json, { ok: true, signedIn: true, endpoint: MCP_ENDPOINT }, "Signed in. The local sign-in file was updated and was not printed.\n");
117
+ return 0;
118
+ }
119
+ if (command.kind === "logout") {
120
+ const existed = runtime.store.exists();
121
+ runtime.store.remove();
122
+ write(runtime, command.json, { ok: true, removed: existed, endpoint: MCP_ENDPOINT }, existed ? "Removed the local sign-in file.\n" : "No local sign-in file was stored.\n");
123
+ return 0;
124
+ }
125
+ if (command.kind === "status") {
126
+ const stored = runtime.store.hasCredential();
127
+ write(runtime, command.json, {
128
+ ok: true,
129
+ endpoint: MCP_ENDPOINT,
130
+ credentialStored: stored,
131
+ credentialCheckedWithServer: false,
132
+ credentialFile: runtime.store.filePath,
133
+ }, stored
134
+ ? `Endpoint: ${MCP_ENDPOINT}\nA local sign-in file is stored. This command does not check it with the server.\nCredential file: ${runtime.store.filePath}\n`
135
+ : `Endpoint: ${MCP_ENDPOINT}\nNo local sign-in is stored.\nCredential file: ${runtime.store.filePath}\n`);
136
+ return 0;
137
+ }
138
+ if (!runtime.store.hasCredential()) {
139
+ throw new CliError("not_signed_in", "No local VPSYOU sign-in is stored. Run `vpsyou-cn2 login` in your terminal and approve read-only cn2:read. Do not paste tokens into chat.");
140
+ }
141
+ const session = await runtime.openSession();
142
+ try {
143
+ if (command.kind === "targets") {
144
+ const listed = await session.listTools();
145
+ const tool = findTool(listed.tools);
146
+ const windows = windowsFromSchema(tool.inputSchema);
147
+ const targets = targetsFromSchema(tool.inputSchema);
148
+ write(runtime, command.json, { ok: true, endpoint: MCP_ENDPOINT, tool: TOOL_NAME, windows, targets: targets ?? null }, formatTargetsHuman(windows, targets));
149
+ return 0;
150
+ }
151
+ const listed = await session.listTools();
152
+ const tool = findTool(listed.tools);
153
+ const args = buildToolArguments(tool.inputSchema, command.window, command.target);
154
+ const result = await session.callTool({ name: TOOL_NAME, arguments: args });
155
+ const payload = toolPayload(result);
156
+ const retrievedAt = runtime.now().toISOString();
157
+ if (result.isError) {
158
+ const message = "The tool reported an error. The payload below is not a measurement.";
159
+ write(runtime, command.json, {
160
+ ok: false,
161
+ error: { code: "tool_error", message },
162
+ endpoint: MCP_ENDPOINT,
163
+ tool: TOOL_NAME,
164
+ arguments: args,
165
+ retrievedAt,
166
+ result: payload,
167
+ }, `${message}\n${JSON.stringify(payload, null, 2)}\n`);
168
+ return 1;
169
+ }
170
+ const report = {
171
+ ok: true,
172
+ endpoint: MCP_ENDPOINT,
173
+ tool: TOOL_NAME,
174
+ arguments: args,
175
+ retrievedAt,
176
+ probe: "Guangdong",
177
+ toolDescription: tool.description ?? null,
178
+ measurementNotes: {
179
+ timestamps: "unix_milliseconds",
180
+ rtt: "milliseconds",
181
+ loss: "ratio_0_to_1",
182
+ null: "no_observed_data",
183
+ },
184
+ result: payload,
185
+ };
186
+ write(runtime, command.json, report, formatQueryHuman(report));
187
+ return 0;
188
+ }
189
+ finally {
190
+ await session.close().catch(() => undefined);
191
+ }
192
+ }
193
+ catch (error) {
194
+ const cliError = error instanceof CliError
195
+ ? error
196
+ : new CliError("request_failed", "The command failed before it could print a result.");
197
+ const json = argv.includes("--json");
198
+ if (json)
199
+ runtime.stdout(`${JSON.stringify({ ok: false, error: { code: cliError.code, message: cliError.message } })}\n`);
200
+ else
201
+ runtime.stderr(`${cliError.message}\n`);
202
+ return exitCodeFor(cliError.code);
203
+ }
204
+ }
205
+ function write(runtime, json, value, human) {
206
+ runtime.stdout(json ? formatJson(value) : human);
207
+ }
208
+ function optionValue(argv, index, name) {
209
+ const arg = argv[index] ?? "";
210
+ if (arg.startsWith(`${name}=`)) {
211
+ const value = arg.slice(name.length + 1);
212
+ if (value.length === 0)
213
+ throw new CliError("usage", `${name} needs a value.`);
214
+ return value;
215
+ }
216
+ const value = argv[index + 1];
217
+ if (!value || value.startsWith("-"))
218
+ throw new CliError("usage", `${name} needs a value.`);
219
+ return value;
220
+ }
221
+ function defaultRuntime() {
222
+ const store = new CredentialStore();
223
+ return {
224
+ store,
225
+ now: () => new Date(),
226
+ stdout: (text) => {
227
+ process.stdout.write(text);
228
+ },
229
+ stderr: (text) => {
230
+ process.stderr.write(text);
231
+ },
232
+ openSession: () => openQuerySession(store),
233
+ login: () => runLogin(store, (message) => process.stderr.write(`${message}\n`)),
234
+ };
235
+ }
236
+ const entry = process.argv[1];
237
+ const entryUrl = entry ? pathToFileURL(realpathSync(entry)).href : "";
238
+ if (entry && import.meta.url === entryUrl) {
239
+ const code = await run(process.argv.slice(2));
240
+ process.exit(code);
241
+ }
@@ -0,0 +1,14 @@
1
+ /** Hosted Streamable HTTP endpoint published by VPSYOU. Not configurable. */
2
+ export const MCP_ENDPOINT = "https://vpsyou.com/mcp";
3
+ export const TOOL_NAME = "get_cn2_latency";
4
+ export const CLIENT_NAME = "vpsyou-cn2";
5
+ export const CLIENT_VERSION = "0.1.0";
6
+ /** Read-only scope from the protected-resource metadata and the integration guide. */
7
+ export const READ_SCOPE = "cn2:read";
8
+ export const CALLBACK_HOST = "127.0.0.1";
9
+ export const CALLBACK_PORT = 47623;
10
+ export const CALLBACK_PATH = "/callback";
11
+ export const CALLBACK_URL = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;
12
+ export const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
13
+ export const REQUEST_TIMEOUT_MS = 60_000;
14
+ export const DOCUMENTED_WINDOWS = ["live", "24h", "7d"];
@@ -0,0 +1,153 @@
1
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { CliError } from "./errors.js";
5
+ function emptyFile() {
6
+ return { version: 1, clients: {}, tokens: {} };
7
+ }
8
+ export function credentialDirectory() {
9
+ const override = process.env.VPSYOU_CN2_CONFIG_DIR;
10
+ if (override && override.trim().length > 0)
11
+ return override;
12
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
13
+ if (!home) {
14
+ throw new CliError("request_failed", "HOME is not set. Set VPSYOU_CN2_CONFIG_DIR to a private directory for the local sign-in file.");
15
+ }
16
+ const base = process.env.XDG_CONFIG_HOME || join(home, ".config");
17
+ return join(base, "vpsyou-cn2");
18
+ }
19
+ export class CredentialStore {
20
+ filePath;
21
+ constructor(directory = credentialDirectory()) {
22
+ this.filePath = join(directory, "credentials.json");
23
+ }
24
+ hasCredential() {
25
+ if (!this.exists())
26
+ return false;
27
+ const { tokens } = this.read();
28
+ return Object.values(tokens).some((token) => hasSecret(token));
29
+ }
30
+ exists() {
31
+ try {
32
+ statSync(this.filePath);
33
+ return true;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ read() {
40
+ if (!this.exists())
41
+ return emptyFile();
42
+ let parsed;
43
+ try {
44
+ parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
45
+ }
46
+ catch {
47
+ throw new CliError("auth_rejected", "The local sign-in file could not be read. Run `vpsyou-cn2 logout`, then `vpsyou-cn2 login`.");
48
+ }
49
+ if (!parsed || typeof parsed !== "object" || parsed.version !== 1) {
50
+ throw new CliError("auth_rejected", "The local sign-in file is not a version this client can read. Run `vpsyou-cn2 logout`, then `vpsyou-cn2 login`.");
51
+ }
52
+ const file = parsed;
53
+ return {
54
+ version: 1,
55
+ clients: file.clients ?? {},
56
+ tokens: file.tokens ?? {},
57
+ lastIssuer: file.lastIssuer,
58
+ verifier: file.verifier,
59
+ oauthState: file.oauthState,
60
+ discovery: file.discovery,
61
+ };
62
+ }
63
+ clientInformation(issuer) {
64
+ const file = this.read();
65
+ const key = issuer ?? file.lastIssuer;
66
+ if (!key)
67
+ return undefined;
68
+ return file.clients[key];
69
+ }
70
+ saveClientInformation(issuer, info) {
71
+ const file = this.read();
72
+ file.clients[issuer] = info;
73
+ file.lastIssuer = issuer;
74
+ this.write(file);
75
+ }
76
+ tokens(issuer) {
77
+ const file = this.read();
78
+ if (issuer)
79
+ return file.tokens[issuer];
80
+ if (file.lastIssuer && file.tokens[file.lastIssuer])
81
+ return file.tokens[file.lastIssuer];
82
+ const values = Object.values(file.tokens);
83
+ return values.length === 1 ? values[0] : undefined;
84
+ }
85
+ saveTokens(issuer, tokens) {
86
+ const file = this.read();
87
+ file.tokens[issuer] = tokens;
88
+ file.lastIssuer = issuer;
89
+ this.write(file);
90
+ }
91
+ verifier() {
92
+ return this.read().verifier;
93
+ }
94
+ saveVerifier(verifier) {
95
+ const file = this.read();
96
+ file.verifier = verifier;
97
+ this.write(file);
98
+ }
99
+ oauthState() {
100
+ return this.read().oauthState;
101
+ }
102
+ saveOauthState(state) {
103
+ const file = this.read();
104
+ file.oauthState = state;
105
+ this.write(file);
106
+ }
107
+ discovery() {
108
+ return this.read().discovery;
109
+ }
110
+ saveDiscovery(state) {
111
+ const file = this.read();
112
+ file.discovery = state;
113
+ this.write(file);
114
+ }
115
+ invalidate(scope) {
116
+ if (!this.exists())
117
+ return;
118
+ if (scope === "all") {
119
+ this.remove();
120
+ return;
121
+ }
122
+ const file = this.read();
123
+ if (scope === "client")
124
+ file.clients = {};
125
+ if (scope === "tokens")
126
+ file.tokens = {};
127
+ if (scope === "verifier")
128
+ delete file.verifier;
129
+ if (scope === "discovery")
130
+ delete file.discovery;
131
+ this.write(file);
132
+ }
133
+ remove() {
134
+ rmSync(this.filePath, { force: true });
135
+ }
136
+ write(file) {
137
+ const directory = dirname(this.filePath);
138
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
139
+ chmodSync(directory, 0o700);
140
+ const temporary = join(directory, `.credentials.${process.pid}.tmp`);
141
+ const body = JSON.stringify(file);
142
+ writeFileSync(temporary, body, { mode: 0o600 });
143
+ chmodSync(temporary, 0o600);
144
+ renameSync(temporary, this.filePath);
145
+ chmodSync(this.filePath, 0o600);
146
+ }
147
+ }
148
+ function hasSecret(token) {
149
+ if (!token)
150
+ return false;
151
+ return ((typeof token.access_token === "string" && token.access_token.length > 0) ||
152
+ (typeof token.refresh_token === "string" && token.refresh_token.length > 0));
153
+ }
@@ -0,0 +1,31 @@
1
+ export class CliError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = "CliError";
6
+ this.code = code;
7
+ }
8
+ }
9
+ export function exitCodeFor(code) {
10
+ if (code === "usage" || code === "tool_missing")
11
+ return 2;
12
+ if (code === "not_signed_in" ||
13
+ code === "auth_rejected" ||
14
+ code === "callback_state" ||
15
+ code === "callback_timeout" ||
16
+ code === "callback_port") {
17
+ return 3;
18
+ }
19
+ return 1;
20
+ }
21
+ export function redact(text) {
22
+ return text
23
+ .replace(/("(?:access_token|refresh_token|id_token|client_secret|code_verifier)"\s*:\s*")[^"]*/gi, "$1[redacted]")
24
+ .replace(/\b(access_token|refresh_token|id_token|client_secret|code_verifier)=([^&\s]+)/gi, "$1=[redacted]")
25
+ .replace(/Bearer\s+\S+/gi, "Bearer [redacted]");
26
+ }
27
+ export function errorText(error) {
28
+ if (error instanceof Error)
29
+ return redact(error.message);
30
+ return redact(String(error));
31
+ }
@@ -0,0 +1,61 @@
1
+ import { MCP_ENDPOINT, TOOL_NAME } from "./constants.js";
2
+ export function toolPayload(result) {
3
+ if (result.structuredContent !== undefined)
4
+ return result.structuredContent;
5
+ if (Array.isArray(result.content) && result.content.length === 1) {
6
+ const block = result.content[0];
7
+ if (isTextBlock(block)) {
8
+ try {
9
+ return JSON.parse(block.text);
10
+ }
11
+ catch {
12
+ return block.text;
13
+ }
14
+ }
15
+ }
16
+ return result.content ?? null;
17
+ }
18
+ export function formatJson(value) {
19
+ return `${JSON.stringify(value)}\n`;
20
+ }
21
+ export function formatQueryHuman(report) {
22
+ const target = report.arguments.targetId ?? "(omitted)";
23
+ return [
24
+ "VPSYOU CN2 latency",
25
+ `Endpoint: ${report.endpoint}`,
26
+ "Probe: Guangdong ICMP, one probe",
27
+ `Window: ${report.arguments.window}`,
28
+ `Target: ${target}`,
29
+ `Retrieved: ${report.retrievedAt} (when this command received the response, not the probe timestamp)`,
30
+ "",
31
+ "Result:",
32
+ JSON.stringify(report.result, null, 2),
33
+ "",
34
+ "The server describes timestamps as Unix milliseconds, round-trip time as milliseconds, and packet loss as a ratio from 0 to 1. Null means no observed data. Names of those values are whatever fields the result contains. A reading is this probe's path to a test endpoint. It is not a global monitoring network, and this command does not manage VPS instances.",
35
+ "",
36
+ ].join("\n");
37
+ }
38
+ export function formatTargetsHuman(windows, targets) {
39
+ const lines = [
40
+ `Tool: ${TOOL_NAME}`,
41
+ `Endpoint: ${MCP_ENDPOINT}`,
42
+ `Windows: ${windows.join(", ")}`,
43
+ "Targets:",
44
+ ];
45
+ if (!targets) {
46
+ lines.push("(The server did not publish a targetId enum.)");
47
+ }
48
+ else if (targets.length === 0) {
49
+ lines.push("(The server published an empty targetId enum.)");
50
+ }
51
+ else {
52
+ lines.push(...targets);
53
+ }
54
+ return `${lines.join("\n")}\n`;
55
+ }
56
+ function isTextBlock(value) {
57
+ return (typeof value === "object" &&
58
+ value !== null &&
59
+ value.type === "text" &&
60
+ typeof value.text === "string");
61
+ }
@@ -0,0 +1,149 @@
1
+ import { createServer } from "node:http";
2
+ import { spawn } from "node:child_process";
3
+ import { Client, IssuerMismatchError, StreamableHTTPClientTransport, UnauthorizedError } from "@modelcontextprotocol/client";
4
+ import { CALLBACK_HOST, CALLBACK_PATH, CALLBACK_PORT, CLIENT_NAME, CLIENT_VERSION, LOGIN_TIMEOUT_MS, MCP_ENDPOINT, } from "./constants.js";
5
+ import { CliError } from "./errors.js";
6
+ import { assertHttpsAuthorizationUrl, callbackStateMatches, FileOAuthProvider } from "./oauth.js";
7
+ import { toSessionError } from "./session.js";
8
+ export async function openBrowser(url) {
9
+ assertHttpsAuthorizationUrl(url);
10
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? undefined : "xdg-open";
11
+ if (!command)
12
+ return false;
13
+ return new Promise((resolve) => {
14
+ const child = spawn(command, [url.href], { stdio: "ignore", detached: true });
15
+ child.once("error", () => resolve(false));
16
+ child.once("spawn", () => {
17
+ child.unref();
18
+ resolve(true);
19
+ });
20
+ });
21
+ }
22
+ export async function runLogin(store, warn) {
23
+ const callback = await listenForCallback(CALLBACK_PORT, () => store.oauthState());
24
+ const provider = new FileOAuthProvider(store, true, (url) => {
25
+ void openBrowser(url).then((opened) => {
26
+ if (!opened) {
27
+ warn("The browser did not open. Open this HTTPS authorization URL in your browser, then return here:");
28
+ warn(url.href);
29
+ }
30
+ else {
31
+ warn("Approve read-only cn2:read in the browser. This command keeps the sign-in on this computer.");
32
+ }
33
+ });
34
+ });
35
+ try {
36
+ try {
37
+ const existing = await connectForLogin(provider);
38
+ await existing.close();
39
+ return;
40
+ }
41
+ catch (error) {
42
+ if (!UnauthorizedError.isInstance(error))
43
+ throw error;
44
+ }
45
+ const params = await callback.wait();
46
+ if (!callbackStateMatches(store.oauthState(), params)) {
47
+ throw new CliError("callback_state", "Sign-in failed because the callback did not match this login. Run `vpsyou-cn2 login` again. Do not paste the callback URL into chat.");
48
+ }
49
+ const transport = new StreamableHTTPClientTransport(new URL(MCP_ENDPOINT), { authProvider: provider });
50
+ try {
51
+ await transport.finishAuth(params);
52
+ }
53
+ catch (error) {
54
+ if (error instanceof IssuerMismatchError) {
55
+ throw new CliError("auth_rejected", "Sign-in failed because the authorization server did not match the server that started the flow. Run `vpsyou-cn2 login` again.");
56
+ }
57
+ throw new CliError("auth_rejected", "Sign-in could not be completed. Run `vpsyou-cn2 login` again. Do not paste the callback URL into chat.");
58
+ }
59
+ finally {
60
+ await transport.close().catch(() => undefined);
61
+ }
62
+ const confirmed = await connectForLogin(provider);
63
+ await confirmed.close();
64
+ }
65
+ finally {
66
+ await callback.close();
67
+ }
68
+ }
69
+ async function connectForLogin(provider) {
70
+ const transport = new StreamableHTTPClientTransport(new URL(MCP_ENDPOINT), { authProvider: provider });
71
+ const client = new Client({ name: CLIENT_NAME, version: CLIENT_VERSION });
72
+ try {
73
+ await client.connect(transport);
74
+ }
75
+ catch (error) {
76
+ await transport.close().catch(() => undefined);
77
+ if (UnauthorizedError.isInstance(error))
78
+ throw error;
79
+ throw toSessionError(error);
80
+ }
81
+ return {
82
+ async close() {
83
+ await client.close();
84
+ },
85
+ };
86
+ }
87
+ export function listenForCallback(port = CALLBACK_PORT, expectedState) {
88
+ return new Promise((resolve, reject) => {
89
+ let settle;
90
+ let fail;
91
+ const pending = new Promise((resolveParams, rejectParams) => {
92
+ settle = resolveParams;
93
+ fail = rejectParams;
94
+ });
95
+ pending.catch(() => undefined);
96
+ const server = createServer((request, response) => {
97
+ handleCallbackRequest(request, response, port, settle, fail, expectedState);
98
+ });
99
+ server.on("error", (error) => {
100
+ if (error.code === "EADDRINUSE") {
101
+ reject(new CliError("callback_port", `The login callback port ${CALLBACK_HOST}:${port} is already in use. Close the other vpsyou-cn2 login and try again.`));
102
+ return;
103
+ }
104
+ reject(error);
105
+ });
106
+ server.listen(port, CALLBACK_HOST, () => {
107
+ const address = server.address();
108
+ const actualPort = typeof address === "object" && address !== null ? address.port : port;
109
+ resolve({
110
+ port: actualPort,
111
+ wait: () => withTimeout(pending, LOGIN_TIMEOUT_MS),
112
+ close: () => new Promise((done) => {
113
+ server.close(() => done());
114
+ }),
115
+ });
116
+ });
117
+ });
118
+ }
119
+ function handleCallbackRequest(request, response, port, settle, fail, expectedState) {
120
+ const url = new URL(request.url ?? "/", `http://${CALLBACK_HOST}:${port}`);
121
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
122
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
123
+ response.end("Not found");
124
+ return;
125
+ }
126
+ if (url.search.length > 4096 || (expectedState && !callbackStateMatches(expectedState(), url.searchParams))) {
127
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
128
+ response.end("Sign-in could not be confirmed. Return to the terminal.");
129
+ fail?.(new CliError("callback_state", "Sign-in failed because the callback did not match this login. Run `vpsyou-cn2 login` again. Do not paste the callback URL into chat."));
130
+ return;
131
+ }
132
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
133
+ response.end("<!doctype html><html><head><title>VPSYOU CN2</title></head><body><p>Sign-in received. You can close this window and return to the terminal.</p></body></html>");
134
+ settle?.(url.searchParams);
135
+ }
136
+ function withTimeout(pending, timeoutMs) {
137
+ return new Promise((resolve, reject) => {
138
+ const timer = setTimeout(() => {
139
+ reject(new CliError("callback_timeout", "Sign-in timed out after 10 minutes. Run `vpsyou-cn2 login` again. Do not paste a callback URL into chat."));
140
+ }, timeoutMs);
141
+ pending.then((value) => {
142
+ clearTimeout(timer);
143
+ resolve(value);
144
+ }, (error) => {
145
+ clearTimeout(timer);
146
+ reject(error);
147
+ });
148
+ });
149
+ }
@@ -0,0 +1,86 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { CALLBACK_URL, CLIENT_NAME, READ_SCOPE } from "./constants.js";
3
+ import { CliError } from "./errors.js";
4
+ export function assertHttpsAuthorizationUrl(url) {
5
+ if (url.protocol !== "https:") {
6
+ throw new CliError("auth_rejected", "Refusing to open an authorization URL that is not HTTPS.");
7
+ }
8
+ }
9
+ export function callbackStateMatches(expected, params) {
10
+ const received = params.get("state");
11
+ return typeof expected === "string" && expected.length > 0 && received === expected;
12
+ }
13
+ /**
14
+ * OAuth client storage for the official MCP SDK.
15
+ * Interactive login may open the authorization URL. Query mode never does.
16
+ */
17
+ export class FileOAuthProvider {
18
+ store;
19
+ interactive;
20
+ onAuthorizationUrl;
21
+ redirectUrl = CALLBACK_URL;
22
+ clientMetadata = {
23
+ client_name: CLIENT_NAME,
24
+ redirect_uris: [CALLBACK_URL],
25
+ grant_types: ["authorization_code", "refresh_token"],
26
+ response_types: ["code"],
27
+ token_endpoint_auth_method: "none",
28
+ application_type: "native",
29
+ scope: READ_SCOPE,
30
+ };
31
+ constructor(store, interactive, onAuthorizationUrl) {
32
+ this.store = store;
33
+ this.interactive = interactive;
34
+ this.onAuthorizationUrl = onAuthorizationUrl;
35
+ }
36
+ state() {
37
+ const value = randomUUID();
38
+ this.store.saveOauthState(value);
39
+ return value;
40
+ }
41
+ clientInformation(ctx) {
42
+ return this.store.clientInformation(ctx?.issuer);
43
+ }
44
+ saveClientInformation(info, ctx) {
45
+ const issuer = ctx?.issuer ?? info.issuer;
46
+ if (!issuer) {
47
+ throw new CliError("auth_rejected", "The authorization server did not provide an issuer to store the client registration.");
48
+ }
49
+ this.store.saveClientInformation(issuer, info);
50
+ }
51
+ tokens(ctx) {
52
+ return this.store.tokens(ctx?.issuer);
53
+ }
54
+ saveTokens(tokens, ctx) {
55
+ const issuer = ctx?.issuer ?? tokens.issuer;
56
+ if (!issuer) {
57
+ throw new CliError("auth_rejected", "The authorization server did not provide an issuer to store the sign-in.");
58
+ }
59
+ this.store.saveTokens(issuer, tokens);
60
+ }
61
+ async redirectToAuthorization(authorizationUrl) {
62
+ assertHttpsAuthorizationUrl(authorizationUrl);
63
+ if (!this.interactive)
64
+ return;
65
+ this.onAuthorizationUrl(authorizationUrl);
66
+ }
67
+ saveCodeVerifier(codeVerifier) {
68
+ this.store.saveVerifier(codeVerifier);
69
+ }
70
+ codeVerifier() {
71
+ const verifier = this.store.verifier();
72
+ if (!verifier) {
73
+ throw new CliError("auth_rejected", "The local sign-in challenge is missing. Run `vpsyou-cn2 login` again.");
74
+ }
75
+ return verifier;
76
+ }
77
+ saveDiscoveryState(state) {
78
+ this.store.saveDiscovery(state);
79
+ }
80
+ discoveryState() {
81
+ return this.store.discovery();
82
+ }
83
+ invalidateCredentials(scope) {
84
+ this.store.invalidate(scope);
85
+ }
86
+ }
@@ -0,0 +1,50 @@
1
+ import { DOCUMENTED_WINDOWS, TOOL_NAME } from "./constants.js";
2
+ import { CliError } from "./errors.js";
3
+ export function findTool(tools) {
4
+ const tool = tools.find((item) => item.name === TOOL_NAME);
5
+ if (!tool) {
6
+ throw new CliError("tool_missing", `The server did not advertise ${TOOL_NAME}. This client only calls that read-only tool.`);
7
+ }
8
+ return tool;
9
+ }
10
+ export function stringEnum(schema, property) {
11
+ if (!schema || typeof schema !== "object")
12
+ return undefined;
13
+ const properties = schema.properties;
14
+ if (!properties || typeof properties !== "object")
15
+ return undefined;
16
+ const field = properties[property];
17
+ if (!field || typeof field !== "object")
18
+ return undefined;
19
+ const values = field.enum;
20
+ if (!Array.isArray(values) || values.length === 0 || !values.every((item) => typeof item === "string")) {
21
+ return undefined;
22
+ }
23
+ return values;
24
+ }
25
+ export function windowsFromSchema(schema) {
26
+ return stringEnum(schema, "window") ?? [...DOCUMENTED_WINDOWS];
27
+ }
28
+ export function targetsFromSchema(schema) {
29
+ return stringEnum(schema, "targetId");
30
+ }
31
+ const TARGET_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32
+ export function buildToolArguments(schema, window, target) {
33
+ const windows = windowsFromSchema(schema);
34
+ const chosen = window ?? "live";
35
+ if (!windows.includes(chosen)) {
36
+ throw new CliError("usage", `Window must be one of: ${windows.join(", ")}.`);
37
+ }
38
+ const args = { window: chosen };
39
+ if (target === undefined)
40
+ return args;
41
+ if (!TARGET_ID.test(target) || target.length > 64) {
42
+ throw new CliError("usage", "Target id must match the server's targetId values. Run `vpsyou-cn2 targets`.");
43
+ }
44
+ const targets = targetsFromSchema(schema);
45
+ if (targets && !targets.includes(target)) {
46
+ throw new CliError("usage", `Target ${target} is not in the server's current targetId list. Run \`vpsyou-cn2 targets\`.`);
47
+ }
48
+ args.targetId = target;
49
+ return args;
50
+ }
@@ -0,0 +1,65 @@
1
+ import { Client, IssuerMismatchError, StreamableHTTPClientTransport, UnauthorizedError, } from "@modelcontextprotocol/client";
2
+ import { CLIENT_NAME, CLIENT_VERSION, MCP_ENDPOINT, REQUEST_TIMEOUT_MS } from "./constants.js";
3
+ import { CliError, errorText } from "./errors.js";
4
+ import { FileOAuthProvider } from "./oauth.js";
5
+ const SIGN_IN_AGAIN = "The MCP server asked for sign-in. Run `vpsyou-cn2 login` in your terminal and approve read-only cn2:read. Do not paste tokens, authorization codes, or callback URLs into chat.";
6
+ export async function openQuerySession(store) {
7
+ if (!store.hasCredential()) {
8
+ throw new CliError("not_signed_in", "No local VPSYOU sign-in is stored. Run `vpsyou-cn2 login` in your terminal and approve read-only cn2:read. Do not paste tokens into chat.");
9
+ }
10
+ const provider = new FileOAuthProvider(store, false, () => undefined);
11
+ return connect(provider, AbortSignal.timeout(REQUEST_TIMEOUT_MS));
12
+ }
13
+ export async function connect(provider, signal) {
14
+ const transport = new StreamableHTTPClientTransport(new URL(MCP_ENDPOINT), {
15
+ authProvider: provider,
16
+ requestInit: signal ? { signal } : undefined,
17
+ });
18
+ const client = new Client({ name: CLIENT_NAME, version: CLIENT_VERSION });
19
+ try {
20
+ await client.connect(transport);
21
+ }
22
+ catch (error) {
23
+ await transport.close().catch(() => undefined);
24
+ throw toSessionError(error);
25
+ }
26
+ return {
27
+ async listTools() {
28
+ try {
29
+ const listed = await client.listTools();
30
+ return {
31
+ tools: listed.tools.map((tool) => ({
32
+ name: tool.name,
33
+ description: typeof tool.description === "string" ? tool.description : undefined,
34
+ inputSchema: tool.inputSchema,
35
+ })),
36
+ };
37
+ }
38
+ catch (error) {
39
+ throw toSessionError(error);
40
+ }
41
+ },
42
+ async callTool(params) {
43
+ try {
44
+ return await client.callTool(params);
45
+ }
46
+ catch (error) {
47
+ throw toSessionError(error);
48
+ }
49
+ },
50
+ async close() {
51
+ await client.close();
52
+ },
53
+ };
54
+ }
55
+ export function toSessionError(error) {
56
+ if (error instanceof CliError)
57
+ return error;
58
+ if (UnauthorizedError.isInstance(error)) {
59
+ return new CliError("auth_rejected", SIGN_IN_AGAIN);
60
+ }
61
+ if (error instanceof IssuerMismatchError) {
62
+ return new CliError("auth_rejected", "Sign-in failed because the authorization server did not match the server that started the flow. Run `vpsyou-cn2 login` again.");
63
+ }
64
+ return new CliError("request_failed", errorText(error) || "The MCP request failed.");
65
+ }
package/docs/mcp.md ADDED
@@ -0,0 +1,240 @@
1
+ # MCP connection
2
+
3
+ Verified connection record for the hosted VPSYOU MCP server. The repository overview, client commands, and agent skill are in the [README](../README.md). This repository does not contain the VPSYOU server implementation.
4
+
5
+ The server address is:
6
+
7
+ ```text
8
+ https://vpsyou.com/mcp
9
+ ```
10
+
11
+ Official connection guides:
12
+
13
+ - English: <https://vpsyou.com/mcp-integration>
14
+ - 简体中文: <https://vpsyou.com/zh/mcp-integration>
15
+ - 繁體中文: <https://vpsyou.com/zh-TW/mcp-integration>
16
+
17
+ The English and Simplified Chinese guides were compared on 2026-11-21. They publish the same endpoint, transport, OAuth flow, client commands, `cn2:read` scope, and `get_cn2_latency` windows.
18
+
19
+ ## Connection
20
+
21
+ | Field | Value |
22
+ | --- | --- |
23
+ | Endpoint | `https://vpsyou.com/mcp` |
24
+ | Transport | Streamable HTTP |
25
+ | Authorization | OAuth |
26
+ | Scope to approve | `cn2:read` (read-only) |
27
+ | MCP Registry name | `com.vpsyou/mcp` |
28
+ | Registry title | VPSYOU CN2 Latency |
29
+ | Registry remote | `streamable-http` at `https://vpsyou.com/mcp` |
30
+
31
+ The registry entry is active and lists version `1.0.0`. Its website is the English guide above. The entry has a remote URL and does not publish a package or install command. Registry record retrieved on 2026-11-21:
32
+
33
+ <https://registry.modelcontextprotocol.io/v0/servers?search=com.vpsyou/mcp>
34
+
35
+ There is no local copy of the MCP server to install, and no API key to paste into a client. The clients documented by VPSYOU sign in with OAuth and request approval for `cn2:read`. The command-line client in this repository is a separate from-source program that talks to the hosted endpoint. Its commands are in the [README](../README.md#command-line-client).
36
+
37
+ ## Authorization
38
+
39
+ Protected resource metadata for `https://vpsyou.com/mcp`:
40
+
41
+ - <https://vpsyou.com/.well-known/oauth-protected-resource>
42
+ - <https://vpsyou.com/.well-known/oauth-protected-resource/mcp>
43
+
44
+ Both URLs returned the same document on 2026-11-21. It names the resource `https://vpsyou.com/mcp`, the authorization server `https://vpsyou.com/api/auth`, bearer tokens in the `Authorization` header, and the scope `cn2:read`. It also lists supported DPoP signing algorithms. It does not mark DPoP as required.
45
+
46
+ Authorization server metadata:
47
+
48
+ - <https://vpsyou.com/.well-known/oauth-authorization-server/api/auth>
49
+ - <https://vpsyou.com/api/auth/.well-known/oauth-authorization-server>
50
+
51
+ On 2026-11-21 that document published:
52
+
53
+ - Issuer: `https://vpsyou.com/api/auth`
54
+ - Authorization endpoint: `https://vpsyou.com/api/auth/oauth2/authorize`
55
+ - Token endpoint: `https://vpsyou.com/api/auth/oauth2/token`
56
+ - Registration endpoint: `https://vpsyou.com/api/auth/oauth2/register`
57
+ - Response type: `code`
58
+ - Grant types: `authorization_code`, `refresh_token`
59
+ - PKCE method: `S256`
60
+ - Scopes: `cn2:read`, `offline_access`
61
+ - Token endpoint authentication methods include `none` (public clients), along with confidential-client methods
62
+
63
+ The registration endpoint is the published dynamic client registration endpoint. The integration guide does not ask you to create a client ID or client secret yourself. Leave a client ID blank unless a later VPSYOU document tells you to supply one. Approve read-only `cn2:read` when the consent screen appears. The protected-resource metadata and the `WWW-Authenticate` challenge both advertise `cn2:read`. The authorization server additionally lists `offline_access`.
64
+
65
+ Use the live metadata URLs above for the full field list, including signing algorithms. Those lists can change.
66
+
67
+ ## What the server can read
68
+
69
+ The documented tool is `get_cn2_latency`.
70
+
71
+ The integration page describes the Guangdong probe. It uses ICMP to measure round-trip latency and packet loss at listed test endpoints. History is aggregated by hour. Compare readings with the measurement time and the probe location. CN2 readings reflect that probe’s path to each test endpoint. The site footer says prices and metrics on vpsyou.com are dated snapshots, not live quotes.
72
+
73
+ The tool description published by the server on 2026-11-21 says it returns CN2 test-endpoint latency and packet loss measured from Guangdong, uses the latest sample by default, and can return a historical window or one target’s time series. Null measurements mean no observed data. The server instructions published with the tool describe timestamps as Unix milliseconds, round-trip time as milliseconds, and packet loss as a ratio from 0 to 1. This guide does not include sample tool results.
74
+
75
+ Arguments in the published input schema:
76
+
77
+ | Argument | Required | Values |
78
+ | --- | --- | --- |
79
+ | `window` | No. Default `live` | `live`, `24h`, `7d` |
80
+ | `targetId` | No | One target ID from the server’s current enum. The schema says that setting it requests that target’s time series. |
81
+
82
+ The published schema sets `additionalProperties` to false. If the server’s tool definition changes, use the definition the server returns.
83
+
84
+ ### Request examples from the integration page
85
+
86
+ These are the requests shown on <https://vpsyou.com/mcp-integration>. They are not recorded responses.
87
+
88
+ Live readings, with this message for the client: “Show the latest CN2 latency and packet loss from Guangdong.”
89
+
90
+ ```json
91
+ {
92
+ "name": "get_cn2_latency",
93
+ "arguments": {
94
+ "window": "live"
95
+ }
96
+ }
97
+ ```
98
+
99
+ Last 24 hours. The page’s example asks for hourly CN2 latency and packet loss for DMIT Hong Kong and includes `targetId` `dmit-hkg`: “Show the hourly CN2 latency and packet loss for DMIT Hong Kong over the last 24 hours.”
100
+
101
+ ```json
102
+ {
103
+ "name": "get_cn2_latency",
104
+ "arguments": {
105
+ "window": "24h",
106
+ "targetId": "dmit-hkg"
107
+ }
108
+ }
109
+ ```
110
+
111
+ Last 7 days. The page’s example asks for the DMIT Hong Kong trend and uses the same target: “Show the CN2 latency and packet loss trend for DMIT Hong Kong over the last seven days.”
112
+
113
+ ```json
114
+ {
115
+ "name": "get_cn2_latency",
116
+ "arguments": {
117
+ "window": "7d",
118
+ "targetId": "dmit-hkg"
119
+ }
120
+ }
121
+ ```
122
+
123
+ `targetId` remains optional in the schema for every window. The page adds `dmit-hkg` on the 24-hour and 7-day examples.
124
+
125
+ ### Target IDs advertised on 2026-11-21
126
+
127
+ `dmit-hkg` is the only target the integration page names (DMIT Hong Kong). The tool schema on that date also enumerated:
128
+
129
+ `hostdare-lax`, `bandwagonhost-dc6`, `dmit-tyo`, `dmit-hkg`, `dmit-lax`, `gigsgigscloud-tyo`, `greencloudvps-sin`, `vps-tyo`, `nosla-fra`, `nosla-hkg`, `nosla-sjc`, `akkocloud-sjc`, `akkocloud-fra`, `akkocloud-lon`, `hostkvm-hkg`, `imidc-lax`, `imidc-hkg`, `imidc-mow`, `dedione-lax`, `serverhk-hkg`, `axion-tyo`, `axion-icn`, `axion-kul`, `axion-sea`, `axion-lax`, `axion-sjc`, `axion-fra`
130
+
131
+ Treat that list as a snapshot. The connected server’s current tool definition is the list to use.
132
+
133
+ ## Limits
134
+
135
+ - The service reads CN2 latency and packet loss from the single VPSYOU probe in Guangdong.
136
+ - It is a measurement query for the listed test endpoints. It does not provision, resize, reboot, or otherwise manage VPS instances.
137
+ - It is not a global monitoring network. A reading is the Guangdong probe’s path to a test endpoint at the reported measurement time.
138
+ - Historical series on the integration page are hourly aggregates.
139
+ - The only documented tool is `get_cn2_latency`, and the consent scope for that tool is read-only `cn2:read`.
140
+ - VPSYOU’s integration page documents Claude, Codex, and Grok Bot. This guide does not add configuration for any other client, and it does not claim model compatibility.
141
+
142
+ ## Connect a documented client
143
+
144
+ VPSYOU’s integration page documents the three clients below. The commands are connection commands for an already installed client. They are not an installer for this repository or for the MCP server.
145
+
146
+ Custom connectors depend on your plan and workspace settings.
147
+
148
+ ### Claude Code
149
+
150
+ ```shell
151
+ claude mcp add --transport http --scope user vpsyou-cn2 https://vpsyou.com/mcp
152
+ ```
153
+
154
+ Run that command in a terminal. In Claude Code, open `/mcp`, select `vpsyou-cn2`, and choose Authenticate. Sign in to VPSYOU and approve `cn2:read`.
155
+
156
+ ### Claude web and desktop
157
+
158
+ VPSYOU links to Anthropic’s custom-connector guide for Claude on the web and desktop:
159
+
160
+ <https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp>
161
+
162
+ Add a custom connector whose remote MCP URL is exactly `https://vpsyou.com/mcp`, then sign in to VPSYOU and approve `cn2:read`. Anthropic’s guide describes the current screens and the plan and admin rules. As of 2026-11-21, that guide says to choose your own OAuth client only when the server’s documentation requires a client you register yourself. This server’s documentation does not require that. Its metadata publishes dynamic client registration.
163
+
164
+ That same Anthropic guide describes `claude_desktop_config.json` as the configuration for local MCP servers. Do not use that file to point Claude at this hosted endpoint.
165
+
166
+ ### Codex
167
+
168
+ ```shell
169
+ codex mcp add vpsyou-cn2 --url https://vpsyou.com/mcp
170
+ ```
171
+
172
+ Run the add command. If no authorization page opens, run:
173
+
174
+ ```shell
175
+ codex mcp login vpsyou-cn2
176
+ ```
177
+
178
+ Authorize VPSYOU in the browser and approve `cn2:read`. Codex’s own MCP guide is <https://developers.openai.com/codex/mcp>. As of 2026-11-21 it also documents `codex mcp login --no-browser` when the terminal has no local browser: open the printed URL, then paste the full redirect URL back into the terminal.
179
+
180
+ Codex documents this Streamable HTTP configuration, which is the form written by the add command above. OAuth is Codex’s default for that URL. Do not add a bearer token or an `--oauth-client-id` for VPSYOU.
181
+
182
+ ```toml
183
+ [mcp_servers.vpsyou-cn2]
184
+ url = "https://vpsyou.com/mcp"
185
+ ```
186
+
187
+ Codex’s desktop app and IDE extension can add the same Streamable HTTP URL and then Authenticate. The Codex guide says the ChatGPT website does not read this local config file.
188
+
189
+ ### Grok Bot
190
+
191
+ Send this message, then follow the sign-in prompt and approve `cn2:read`:
192
+
193
+ ```text
194
+ Add the remote MCP server https://vpsyou.com/mcp as VPSYOU CN2 with OAuth. After I authorize it, use it to check the latest CN2 latency and packet loss from Guangdong.
195
+ ```
196
+
197
+ To add it manually, VPSYOU links to <https://docs.x.ai/grok-bot/computer-and-apps#connect-an-app>. As of 2026-11-21 that guide says to choose **Add a custom connector** at the bottom of **Connect apps**, enter the name `VPSYOU CN2`, choose remote HTTPS, and set the server URL to `https://vpsyou.com/mcp`. The OAuth client ID field is optional there. Leave it empty for this server. Save with **Add plugin**, then finish Authorize or Authenticate in the browser. A team MCP policy can block saving the connector.
198
+
199
+ ## OAuth and HTTP 401
200
+
201
+ Before OAuth is complete, a call without an `Authorization` header receives HTTP 401 and a `WWW-Authenticate` challenge. That challenge tells the client to sign in. It does not, by itself, mean `https://vpsyou.com/mcp` is down.
202
+
203
+ On 2026-11-21, a JSON-RPC request to `https://vpsyou.com/mcp` without an `Authorization` header returned HTTP 401 with:
204
+
205
+ ```text
206
+ WWW-Authenticate: Bearer resource_metadata="https://vpsyou.com/.well-known/oauth-protected-resource/mcp", scope="cn2:read"
207
+ ```
208
+
209
+ The body was a JSON-RPC error, code `-32000`, message `missing authorization header`. A client that supports MCP OAuth should read that header, discover the metadata above, and open VPSYOU sign-in.
210
+
211
+ When that happens:
212
+
213
+ 1. Finish the client’s Authenticate or login step. For Claude Code, that is `/mcp`, then `vpsyou-cn2`, then Authenticate. For Codex, run `codex mcp login vpsyou-cn2` if the browser did not open.
214
+ 2. Sign in to VPSYOU and approve read-only `cn2:read`.
215
+ 3. Return to the client after the browser step finishes. In Grok Bot, the linked guide says to use Reconnect or Reopen if the sign-in page disappears, and to finish within about 10 minutes.
216
+ 4. If the client has no custom-connector control, or an administrator policy blocks it, the limitation is the client plan or workspace. VPSYOU states that custom connectors depend on plan and workspace settings.
217
+
218
+ Sign in again from the client if a later request still returns 401 after you thought approval had finished. Do not paste an access token, client secret, or password into a config file or chat. This setup does not use a manually issued API key.
219
+
220
+ ## From-source client
221
+
222
+ `vpsyou-cn2` calls `get_cn2_latency` on the fixed endpoint. The package name `vpsyou-cn2` version `0.1.0` is not yet published to npm. The commands are in the [README](../README.md#command-line-client).
223
+
224
+ `login` uses `@modelcontextprotocol/client` 2.4.0 for Streamable HTTP, protected-resource discovery, and OAuth with the authorization server's published registration endpoint. The browser step approves `cn2:read`. The SDK also sends `offline_access` when that scope is advertised and the client metadata includes the refresh-token grant. Tokens are written to a user-only file (`0600` on Unix) under `$XDG_CONFIG_HOME/vpsyou-cn2` or `~/.config/vpsyou-cn2`. `VPSYOU_CN2_CONFIG_DIR` changes that directory only. The command does not print the file, and there is no flag to point the client at another MCP host.
225
+
226
+ `targets` and `query` read the current `get_cn2_latency` input schema after sign-in. `--window` accepts the schema's enum (`live`, `24h`, and `7d` in the schema checked on 2026-11-21). `--target` must be one of the schema's `targetId` values when that enum is present. Omit `--target` to omit `targetId`, which the schema allows. `--json` prints the tool payload, the endpoint, and `retrievedAt` (when the command received the response, not the probe time). Human output includes the same payload and the server's unit notes: Unix milliseconds, round-trip time in milliseconds, packet loss as a ratio from 0 to 1, and null for no observed data.
227
+
228
+ The tests mock the MCP session and do not sign in or call the live tool. The interactive browser login is implemented and was not run against a user account. The agent skill is described in the [README](../README.md#agent-skill).
229
+
230
+ ## Sources checked on 2026-11-21
231
+
232
+ - <https://vpsyou.com/mcp-integration> and <https://vpsyou.com/zh/mcp-integration>, including the client commands, scope note, measurement description, and the live / 24-hour / 7-day request examples in the page
233
+ - Protected resource metadata and authorization server metadata at the URLs in [Authorization](#authorization)
234
+ - One unauthenticated request to `https://vpsyou.com/mcp`, used only to record the OAuth `401` challenge
235
+ - MCP Registry search for `com.vpsyou/mcp`
236
+ - The server’s published `get_cn2_latency` input schema and server instructions, read without calling the tool
237
+ - The Claude, Codex, and Grok Bot guides linked from the VPSYOU integration page, for the client screens those products currently document
238
+ - MCP TypeScript client 2.4.0 Streamable HTTP transport and OAuth client, including dynamic client registration when the authorization server publishes `registration_endpoint`: <https://ts.sdk.modelcontextprotocol.io/v2/clients/oauth>
239
+
240
+ No tool call was made, so this guide has no measured latency or packet-loss sample. No directory listing was submitted.
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "vpsyou-cn2",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Read-only command-line client for the hosted VPSYOU CN2 MCP server.",
5
+ "type": "module",
6
+ "bin": {
7
+ "vpsyou-cn2": "./dist/src/cli.js"
8
+ },
9
+ "files": [
10
+ "dist/src",
11
+ "docs",
12
+ "skills",
13
+ "README.md"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/vpsyoucom/vpsyou-mcp.git"
18
+ },
19
+ "homepage": "https://github.com/vpsyoucom/vpsyou-mcp#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/vpsyoucom/vpsyou-mcp/issues"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "prepack": "npm run build",
29
+ "test": "npm run build && node --test dist/test/*.test.js",
30
+ "vpsyou-cn2": "node dist/src/cli.js"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/client": "2.4.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "22.19.1",
37
+ "typescript": "5.9.3"
38
+ }
39
+ }
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: vpsyou-cn2-latency
3
+ description: Use when someone asks for VPSYOU CN2 latency or packet loss from the Guangdong probe, including the latest sample or a 24-hour or 7-day history for a listed test endpoint. Do not use for VPS provisioning, plan prices, or a global monitoring network.
4
+ ---
5
+
6
+ # VPSYOU CN2 latency
7
+
8
+ Read latency and packet loss from the hosted VPSYOU MCP server at `https://vpsyou.com/mcp`. The only tool is `get_cn2_latency`. Measurements come from one ICMP probe in Guangdong. This is not VPS management and not a global monitoring network.
9
+
10
+ Use the from-source client in the `vpsyou-mcp` checkout. The npm package name `vpsyou-cn2` is not published yet. Do not run `npx` or install it from the npm registry. Do not call an undocumented HTTP API.
11
+
12
+ ## Install
13
+
14
+ From a checkout of this repository:
15
+
16
+ ```sh
17
+ npm install
18
+ npm run build
19
+ node dist/src/cli.js --help
20
+ ```
21
+
22
+ Copy the `skills/vpsyou-cn2-latency` directory into the skills folder your agent host loads. This skill is not a marketplace listing.
23
+
24
+ ## Choose the query
25
+
26
+ - Omit `--window` or pass `--window live` for the latest sample.
27
+ - Pass `--window 24h` for the last 24 hours.
28
+ - Pass `--window 7d` for the last 7 days.
29
+ - Omit `--target` to omit `targetId`. The published schema allows that.
30
+ - To select one endpoint, pass `--target` with an id from the server's current schema. The integration page's 24-hour and 7-day examples use `dmit-hkg` (DMIT Hong Kong). Run `targets` before using any other id.
31
+
32
+ ```sh
33
+ node dist/src/cli.js targets
34
+ node dist/src/cli.js query
35
+ node dist/src/cli.js query --window 24h --target dmit-hkg
36
+ node dist/src/cli.js query --window 7d --target dmit-hkg --json
37
+ node dist/src/cli.js query --json
38
+ ```
39
+
40
+ Run one query for the request. Do not schedule repeated queries or start a monitor.
41
+
42
+ ## Sign in
43
+
44
+ If the command exits with code 3, or it says no local sign-in is stored:
45
+
46
+ 1. Ask the user to run this in their own terminal, from the checkout:
47
+
48
+ ```sh
49
+ node dist/src/cli.js login
50
+ ```
51
+
52
+ 2. The user approves read-only `cn2:read` in the browser. The client may also request `offline_access` when the authorization server advertises it, because the client uses refresh tokens.
53
+ 3. Do not run `login` yourself. Do not ask for, copy, or repeat an access token, refresh token, client secret, authorization code, callback URL, or the credential file. The sign-in stays in the user's private config file.
54
+ 4. After the user says the browser step finished, run the same query again.
55
+
56
+ `status` only reports whether that file exists. It does not check the sign-in with the server. `logout` deletes the file:
57
+
58
+ ```sh
59
+ node dist/src/cli.js status
60
+ node dist/src/cli.js logout
61
+ ```
62
+
63
+ ## Read the result
64
+
65
+ Prefer `--json` when you need to quote values.
66
+
67
+ - `endpoint` is the source: `https://vpsyou.com/mcp`.
68
+ - `retrievedAt` is when the command received the response. It is not the probe measurement time.
69
+ - `result` is the tool payload. `structuredContent` is used when the server sends it. Do not rename its fields.
70
+ - Report a number only when it is present in `result`. If a value is null, say the server reported no observed data. Do not fill in latency or loss from anywhere else.
71
+ - The server describes timestamps as Unix milliseconds, round-trip time as milliseconds, and packet loss as a ratio from 0 to 1. Say which field you used.
72
+ - Say the reading is the Guangdong probe's path to the test endpoint at the measurement time in the result, when that time is present.
73
+ - If the command reports a tool error, say the call failed and quote the error payload. Do not turn that payload into a latency.
74
+
75
+ ## Sources
76
+
77
+ The endpoint, OAuth scope, tool name, and windows are the ones published at <https://vpsyou.com/mcp-integration>. Target ids come from the signed-in server's `get_cn2_latency` input schema at the time of the command. Units and the single-probe limit are the server instructions and the integration page, checked for this client on 2026-11-21. The same record is in [docs/mcp.md](../../docs/mcp.md).