inspector/clients/cli/__tests__/stored-auth.test.ts
Cliff Hall a029e42a19
cli: Wave 3 — programmatic review path (rollup of #1573–#1575) (#1655)
* feat(cli): programmatic ergonomics — initialize, tool-args-json, connect-timeout, env-var fixes

Adds the #1573 programmatic-ergonomics surface to the CLI, re-implemented
informed by PR #1510 and adapted to the v2/main OAuth-wired cli.ts:

- `--method initialize` — connect-only probe emitting
  `{serverInfo, protocolVersion, capabilities, instructions}`.
- `--tool-args-json '{"k":"v"}'` — tool args passed verbatim as JSON (no
  key=value coercion); mutually exclusive with `--tool-arg`, with clear
  errors for combined use, malformed JSON, and non-object values.
- `--connect-timeout <ms>` — default 15000 for ad-hoc `--server-url`/target
  runs, file-level timeout otherwise; `0` disables. Backed by the exported
  `withConnectTimeout()` helper.
- MCP_CATALOG_PATH is ignored when an ad-hoc target is given, so a shell that
  exports it can still run one-off ad-hoc invocations.
- MCP_STORAGE_DIR is honored by core `getStateFilePath` (`<dir>/oauth.json`),
  below the per-file MCP_INSPECTOR_OAUTH_STATE_PATH override.

Tests: new programmatic-ergonomics.test.ts (CLI, in-process runCli + direct
withConnectTimeout unit tests) and getStateFilePath resolution cases in the
web storage integration suite. Per-file coverage gate stays ≥90.
README: documents the new flags and env-var semantics.

Closes #1573

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

* feat(cli): --app-info probe + --format json envelope

Adds the #1574 app-probing and machine-readable output surface, re-implemented
informed by PR #1510 and adapted to the v2/main OAuth-wired cli.ts.

- `--method tools/call --tool-name <t> --app-info` — prints one JSON line
  describing the tool's app posture (hasApp, resourceUri, csp, permissions,
  domain, …) WITHOUT invoking the tool; exit 0 when it has an app, 2 (no_app)
  when it doesn't. A missing tool exits 5 (tool_not_found) — distinct from the
  no-app exit so a typo isn't mistaken for "no app".
- `--method tools/list --app-info` — one NDJSON line per tool over a single
  connection (`| jq -c 'select(.hasApp)'`).
- `--format json` — a single stdout envelope (`{result}` plus `{appInfo}` as a
  sibling key for App tools), no banner, so any method pipes into jq.
- A tools/call returning isError:true now exits 5 (tool_is_error) after
  printing its payload, so && chains stop on a failed call.

Implementation: `collectAppInfo()` (core `extractAppInfo` + a tolerated
resource read that reports `resourceError`), an NDJSON loop in tools/list, and
a single `emitResult()` that owns format + exit-code handling. `runMethod` now
returns a `MethodOutcome` discriminated union so the NDJSON path can signal
"already emitted".

Tests: app-info.test.ts (exit-0/2/5 + NDJSON + no-invoke), format-json.test.ts
(envelope shapes + bad --format), emit-result.test.ts (direct unit coverage of
the isError→exit-5 and resourceError branches via exported emitResult/
collectAppInfo). Updated the tools.test "nonexistent tool" case to the new
exit-5 tool_not_found contract. Per-file coverage ≥90 on all four dimensions
(cli.ts 100% stmts/funcs/lines). README documents the flags, NDJSON shape, and
exit semantics.

Closes #1574

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

* feat(cli): stored-auth suite — --use-stored-auth, --wait-for-auth, --list-stored-auth, --print-handoff

Adds the #1575 web→CLI OAuth handoff surface, re-implemented informed by PR
#1510 and adapted to v2/main.

- `--use-stored-auth` — read the shared oauth.json and inject
  `Authorization: Bearer <token>` for --server-url; exit 3 (no_stored_token),
  listing stored keys, when none matches.
- `--wait-for-auth <sec>` — poll oauth.json (500ms) until a token for
  --server-url appears, then proceed; timeout → exit 3 (auth_wait_timeout).
- `--list-stored-auth` — print `{oauthStatePath, storedServerUrls}` and exit
  (short-circuit, no connect).
- `--print-handoff` — emit `{serverUrl, deepLink, portForwardCmd,
  oauthStatePath, apiToken, note}` for --server-url and exit.

Adaptations vs. the reference:
- State-path resolution reuses core `getStateFilePath()` (the
  MCP_INSPECTOR_OAUTH_STATE_PATH → <MCP_STORAGE_DIR>/oauth.json → default
  precedence added in #1573) instead of a CLI-local resolver.
- The state file is read through the shared isomorphic
  `parseOAuthPersistBlob`, so both the plain `{servers,idpSessions}` layout the
  web backend writes and the legacy `{state,version}` envelope are accepted.
- `parseArgs` now returns a ParseResult union so the short-circuit modes return
  without a server connection.

Blind injection: the token is passed as-is; a stale one surfaces as HTTP 401 →
exit 3. Documented in the README along with all four flags, the state-path
precedence, and a follow-up note that --print-handoff's deepLink shape is
interim pending #1576's canonical handoff format.

Tests: stored-auth.test.ts drives injection, --header coexistence, missing
--server-url, no-token exit-3, URL-normalisation matching, MCP_STORAGE_DIR
resolution, listing, handoff (+note), wait-for-auth polling/timeout, and
normalizeServerUrl units — all against a real in-process HTTP test server.
Per-file coverage ≥90 on all four dimensions (cli.ts 100% stmts/funcs/lines).

Closes #1575

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

* docs(core): scope MCP_STORAGE_DIR comment in getStateFilePath to the OAuth backend

Address review of PR #1651: the doc comment claimed MCP_STORAGE_DIR was
honoured "across the app, so setting it once points every persist backend at
the same directory", but the branch only relocates oauth.json. Narrow the
comment to state it is OAuth-backend-only (client.json/mcp.json still resolve
from getDefaultStorageDir → HOME) and record why the resolution lives here
rather than in getDefaultStorageDir (the default-path constant is evaluated at
module load, so a runtime-set MCP_STORAGE_DIR — as the CLI stored-auth /
--wait-for-auth flows set it — must be read at call time). Comment-only; no
behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

* review(cli): per-tool-tolerant app-info listing + drop dead helper (PR #1653)

Address review of PR #1653:

- collectAppInfo now never throws: a malformed `_meta.ui.resourceUri`
  (extractAppInfo throws) folds into `{hasApp:false, resourceError}` just like a
  resources/read failure. This makes `tools/list --app-info` per-tool tolerant —
  one bad tool no longer aborts the whole NDJSON listing with a generic exit-1.
  Guarding inside collectAppInfo (vs. a loop-local try/catch) keeps the branch
  unit-testable; added an emit-result.test.ts case for the malformed-URI path.
- Documented that `tools/list --app-info` always emits NDJSON regardless of
  `--format` (the per-tool list shape is fixed; --format json only reshapes the
  single-result paths) — in both the code comment and the README.
- Removed the now-unused `expectJsonError` helper (its only caller moved to the
  exit-5 tool_not_found contract).

Coverage stays ≥90 on all four dimensions (cli.ts 100% stmts/funcs/lines).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

* review(cli): stored-auth follow-ups — TODO(#1576), wait-for-auth guard test, docs (PR #1655)

Address review of PR #1655:

- Added an explicit TODO(#1576) on buildHandoff's deepLink: `transport:"http"`
  is hardcoded even for SSE, and `autoConnect=<token>` is not one of the three
  token sources the web app reads (per CLAUDE.md) — both to be reconciled with
  #1576's canonical handoff format.
- Added a test for `--wait-for-auth` without `--server-url`, covering the
  previously-untested `--wait-for-auth` arm of the shared missing-server-url
  guard's message ternary.
- Documented that `--list-stored-auth` / `--print-handoff` are mutually
  exclusive short-circuit modes (list takes precedence) and that a stored
  refresh_token is not yet used (noted as a follow-up in code + README).

No behavior change; coverage stays ≥90 on all four dimensions (cli.ts 100%
stmts/funcs/lines).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 22:14:23 -04:00

380 lines
12 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { join, dirname } from "node:path";
import { tmpdir } from "node:os";
import { runCli } from "./helpers/cli-runner.js";
import { expectCliFailure, expectCliSuccess } from "./helpers/assertions.js";
import { normalizeServerUrl } from "../src/cli.js";
import {
createTestServerHttp,
createEchoTool,
createTestServerInfo,
} from "@modelcontextprotocol/inspector-test-server";
/**
* Writes an oauth.json fixture in the plain `{ servers, idpSessions }` layout
* the web backend persists (also accepted: the legacy `{ state, version }`
* envelope). The CLI reads it through the shared `parseOAuthPersistBlob`, so
* both sides agree on the format and the URL-normalised server key.
*/
function writeOAuthFixture(servers: Record<string, unknown>): string {
const dir = mkdtempSync(join(tmpdir(), "inspector-cli-stored-auth-"));
const file = join(dir, "oauth.json");
writeFileSync(file, JSON.stringify({ servers, idpSessions: {} }), "utf8");
return file;
}
describe("normalizeServerUrl", () => {
it("canonicalises a URL via new URL().href (lowercases scheme/host)", () => {
expect(normalizeServerUrl("HTTP://Example.COM/Mcp")).toBe(
"http://example.com/Mcp",
);
});
it("returns the raw string when the value is not a parseable URL", () => {
expect(normalizeServerUrl("not a url")).toBe("not a url");
});
});
describe("--use-stored-auth", () => {
let server: ReturnType<typeof createTestServerHttp>;
let serverUrl: string;
let fixturePath: string;
const TOKEN = "stored-access-token-abc";
beforeAll(async () => {
server = createTestServerHttp({
serverInfo: createTestServerInfo(),
tools: [createEchoTool()],
});
await server.start();
serverUrl = server.url;
fixturePath = writeOAuthFixture({
[serverUrl]: { tokens: { access_token: TOKEN, token_type: "Bearer" } },
});
});
afterAll(async () => {
await server.stop();
rmSync(fixturePath, { force: true });
});
it("injects the stored token as Authorization: Bearer on the outgoing request", async () => {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--use-stored-auth",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixturePath } },
);
expectCliSuccess(result);
const recorded = server.getRecordedRequests();
expect(recorded.length).toBeGreaterThan(0);
const last = recorded[recorded.length - 1]!;
expect(last.headers?.authorization).toBe(`Bearer ${TOKEN}`);
});
it("merges with --header (explicit headers + stored auth coexist)", async () => {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--use-stored-auth",
"--header",
"X-Trace: abc",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixturePath } },
);
expectCliSuccess(result);
const last = server.getRecordedRequests().at(-1)!;
expect(last.headers?.authorization).toBe(`Bearer ${TOKEN}`);
expect(last.headers?.["x-trace"]).toBe("abc");
});
it("errors clearly when --server-url is missing", async () => {
const result = await runCli(
["--use-stored-auth", "--method", "tools/list"],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixturePath } },
);
expectCliFailure(result);
expect(result.stderr).toContain("--use-stored-auth requires --server-url");
});
it("errors clearly when --wait-for-auth is set without --server-url", async () => {
// Exercises the `--wait-for-auth` arm of the shared missing-server-url
// guard's message ternary (the --use-stored-auth arm is covered above).
const result = await runCli(
["--wait-for-auth", "5", "--method", "tools/list"],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixturePath } },
);
expectCliFailure(result);
expect(result.stderr).toContain("--wait-for-auth requires --server-url");
});
it("errors with exit 3 (AUTH_REQUIRED) and lists stored keys when no token matches", async () => {
const other = writeOAuthFixture({
"https://other.example/mcp": {
tokens: { access_token: "x", token_type: "Bearer" },
},
});
try {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--use-stored-auth",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: other } },
);
expect(result.exitCode).toBe(3);
const env = JSON.parse(result.stderr.trim()) as {
error: { code: string; message: string };
};
expect(env.error.code).toBe("no_stored_token");
expect(env.error.message).toContain("No stored OAuth token");
expect(env.error.message).toContain("https://other.example/mcp");
} finally {
rmSync(other, { force: true });
}
});
it("matches a stored key even when --server-url differs by URL normalisation", async () => {
// Store under the normalised form; pass the upper-cased scheme on the
// command line. new URL().href lowercases the scheme, so the lookup still
// resolves.
const normalised = normalizeServerUrl(serverUrl);
const upper = serverUrl.replace("http://", "HTTP://");
const fixture = writeOAuthFixture({
[normalised]: { tokens: { access_token: TOKEN, token_type: "Bearer" } },
});
try {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
upper,
"--use-stored-auth",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixture } },
);
expectCliSuccess(result);
} finally {
rmSync(fixture, { force: true });
}
});
it("honours MCP_STORAGE_DIR when MCP_INSPECTOR_OAUTH_STATE_PATH is unset", async () => {
const dir = dirname(fixturePath);
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--use-stored-auth",
"--method",
"tools/list",
],
{ env: { MCP_STORAGE_DIR: dir } },
);
expectCliSuccess(result);
const last = server.getRecordedRequests().at(-1)!;
expect(last.headers?.authorization).toBe(`Bearer ${TOKEN}`);
});
});
describe("--list-stored-auth", () => {
it("prints the stored server URLs and the resolved state path", async () => {
const fixture = writeOAuthFixture({
"https://a.example/mcp": {
tokens: { access_token: "t1", token_type: "Bearer" },
},
"https://b.example/mcp": { tokens: {} },
});
try {
const result = await runCli(["--list-stored-auth"], {
env: { MCP_INSPECTOR_OAUTH_STATE_PATH: fixture },
});
expectCliSuccess(result);
const out = JSON.parse(result.stdout) as {
oauthStatePath: string;
storedServerUrls: string[];
};
expect(out.oauthStatePath).toBe(fixture);
expect(out.storedServerUrls).toEqual(["https://a.example/mcp"]);
} finally {
rmSync(fixture, { force: true });
}
});
it("emits an empty list when the state file is absent", async () => {
const result = await runCli(["--list-stored-auth"], {
env: { MCP_INSPECTOR_OAUTH_STATE_PATH: "/no/such/file.json" },
});
expectCliSuccess(result);
const out = JSON.parse(result.stdout) as { storedServerUrls: string[] };
expect(out.storedServerUrls).toEqual([]);
});
});
describe("--print-handoff", () => {
it("emits a JSON handoff block with deepLink, port-forward command, and the resolved state path", async () => {
const result = await runCli(
["--print-handoff", "--server-url", "https://x.example/mcp"],
{
env: {
MCP_INSPECTOR_API_TOKEN: "tok123",
CLIENT_PORT: "16274",
MCP_SANDBOX_PORT: "16275",
MCP_STORAGE_DIR: "/tmp/inspector-storage",
MCP_INSPECTOR_OAUTH_STATE_PATH: "",
},
},
);
expectCliSuccess(result);
const out = JSON.parse(result.stdout) as {
serverUrl: string;
deepLink: string;
portForwardCmd: string;
oauthStatePath: string;
apiToken: string;
};
expect(out.serverUrl).toBe("https://x.example/mcp");
expect(out.deepLink).toContain("autoConnect=tok123");
expect(out.deepLink).toContain("serverUrl=https%3A%2F%2Fx.example%2Fmcp");
expect(out.portForwardCmd).toContain("--tcp 16274:16274");
expect(out.portForwardCmd).toContain("--tcp 16275:16275");
expect(out.oauthStatePath).toBe(
join("/tmp/inspector-storage", "oauth.json"),
);
expect(out.apiToken).toBe("tok123");
});
it("includes a note when MCP_INSPECTOR_API_TOKEN is unset", async () => {
const result = await runCli(
["--print-handoff", "--server-url", "https://x.example/mcp"],
{ env: { MCP_INSPECTOR_API_TOKEN: "" } },
);
expectCliSuccess(result);
const out = JSON.parse(result.stdout) as {
apiToken: string | null;
note?: string;
};
expect(out.apiToken).toBeNull();
expect(out.note).toContain("MCP_INSPECTOR_API_TOKEN is not set");
});
it("requires --server-url", async () => {
const result = await runCli(["--print-handoff"]);
expectCliFailure(result);
expect(result.stderr).toContain("--print-handoff requires --server-url");
});
});
describe("--wait-for-auth", () => {
let server: ReturnType<typeof createTestServerHttp>;
let serverUrl: string;
beforeAll(async () => {
server = createTestServerHttp({
serverInfo: createTestServerInfo(),
tools: [createEchoTool()],
});
await server.start();
serverUrl = server.url;
});
afterAll(async () => {
await server.stop();
});
it("polls until the token appears, then proceeds with it", async () => {
const dir = mkdtempSync(join(tmpdir(), "inspector-cli-wait-"));
const file = join(dir, "oauth.json");
// Write the token after a short delay so the first poll misses.
setTimeout(() => {
writeFileSync(
file,
JSON.stringify({
servers: {
[normalizeServerUrl(serverUrl)]: {
tokens: { access_token: "waited-tok", token_type: "Bearer" },
},
},
idpSessions: {},
}),
"utf8",
);
}, 200);
try {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--wait-for-auth",
"5",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: file } },
);
expectCliSuccess(result);
const last = server.getRecordedRequests().at(-1)!;
expect(last.headers?.authorization).toBe("Bearer waited-tok");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("times out with exit 3 (AUTH_REQUIRED) when no token appears", async () => {
const result = await runCli(
[
"--transport",
"http",
"--server-url",
serverUrl,
"--wait-for-auth",
"1",
"--method",
"tools/list",
],
{ env: { MCP_INSPECTOR_OAUTH_STATE_PATH: "/no/such/file.json" } },
);
expect(result.exitCode).toBe(3);
const env = JSON.parse(result.stderr.trim()) as {
error: { code: string };
};
expect(env.error.code).toBe("auth_wait_timeout");
});
it("rejects a non-positive timeout", async () => {
const result = await runCli([
"--server-url",
"https://x.example/mcp",
"--wait-for-auth",
"0",
"--method",
"tools/list",
]);
expectCliFailure(result);
expect(result.stderr).toContain("positive number of seconds");
});
});