* test: switch integration project to folder-based manifest (#1314) Replace the `integrationTests` enumeration in vite.config.ts with a folder glob (`src/test/integration/**/*.test.ts`). Files under that folder run in the integration vitest project (node env, 30s timeouts); everything else runs in the unit project (happy-dom). This removes the silent misclassification trap from #1307: a new integration-style test no longer falls into the unit project (and happy-dom) just because someone forgot to add it to the array. The 13 ported v1.5 tests + their helpers move under src/test/integration/ in a strict mirror of core/ source layout (mcp/, auth/, auth/node/, storage/). Renames use git mv so history is preserved. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: address PR review on #1318 (glob extensions + AGENTS doc) - vite.config.ts: widen integrationGlob from `*.test.ts` to `*.test.{ts,tsx}` so the integration folder fully owns its contents. Without this, a `.test.tsx` placed under src/test/integration/ would match the unit project's `{ts,tsx}` include, fail the unit `.ts`-only exclude, and silently land under happy-dom — the exact misclassification trap this PR set out to close. - AGENTS.md: update the line describing where integration tests live; it still pointed at the old `src/test/core/` location and the removed `integrationTests` enumeration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
02182e3b6c
commit
8bb389c8e3
16 changed files with 18 additions and 27 deletions
|
|
@ -90,7 +90,7 @@ All work should be driven by items on the project board.
|
|||
- Run unit tests with `npm run test` (or `npm run test:watch` during development) from `clients/web/`
|
||||
- Run `npm run test:coverage` to verify the per-file gate: lines ≥ 90, statements ≥ 85, functions ≥ 80, branches ≥ 50 (CI enforces this gate). Branches is intentionally relaxed because Mantine portal/media-query branches are not exercisable under happy-dom; new business-logic branches should still be covered.
|
||||
- Run `npm run test:integration` (also from `clients/web/`) for the v1.5-ported InspectorClient + transport + auth integration suite. It runs under a separate `integration` vitest project in node env (no happy-dom) with 30s timeouts. The script builds `test-servers/` first via `tsc -p ../../test-servers --noCheck` so the stdio MCP test server can be spawned as a real subprocess. CI runs it as its own step after unit tests.
|
||||
- Test files live alongside the source as `<Name>.test.tsx` (or `.test.ts` for non-React modules). v1.5-ported integration tests live under `clients/web/src/test/core/` and are wired into the `integration` project via the `integrationTests` list in `vite.config.ts`.
|
||||
- Test files live alongside the source as `<Name>.test.tsx` (or `.test.ts` for non-React modules). v1.5-ported integration tests live under `clients/web/src/test/integration/`, mirroring the `core/` source layout (`mcp/`, `mcp/node/`, `mcp/remote/`, `auth/`, `auth/node/`, `storage/`). Any test file under that folder is automatically picked up by the `integration` vitest project (node env, 30s timeouts) via the folder glob in `vite.config.ts` — placement is the manifest, there is no enumeration to keep in sync. Tests outside the folder run in the `unit` project (happy-dom). When adding a new test for, e.g., `core/mcp/remote/foo.ts`, put it at `src/test/integration/mcp/remote/foo.test.ts`.
|
||||
- Use `renderWithMantine` from `src/test/renderWithMantine.tsx` to render components — it wraps in `MantineProvider` with the project theme
|
||||
|
||||
### Responding to Code Reviews
|
||||
|
|
|
|||
317
clients/web/src/test/integration/auth/discovery.test.ts
Normal file
317
clients/web/src/test/integration/auth/discovery.test.ts
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
discoverScopes,
|
||||
getAuthorizationServerUrl,
|
||||
} from "@inspector/core/auth/discovery.js";
|
||||
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
|
||||
// Mock SDK functions
|
||||
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
discoverAuthorizationServerMetadata: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("OAuth Scope Discovery", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return scopes from resource metadata when available", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: ["read", "write", "admin"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write admin");
|
||||
});
|
||||
|
||||
it("should fall back to OAuth metadata scopes when resource metadata has no scopes", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: [],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should fall back to OAuth metadata scopes when resource metadata is not provided", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should return undefined when no scopes are available", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: [],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined when discovery fails", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockRejectedValue(
|
||||
new Error("Discovery failed"),
|
||||
);
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined when metadata is undefined", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(undefined);
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should use OAuth metadata scopes when resource has scopes_supported undefined", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: undefined as unknown as string[],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should return single scope when only one scope is supported", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["openid"],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBe("openid");
|
||||
});
|
||||
|
||||
it("should pass fetchFn to discoverAuthorizationServerMetadata when provided", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
await discoverScopes("http://localhost:3000", undefined, mockFetchFn);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", "http://localhost:3000"),
|
||||
{ fetchFn: mockFetchFn },
|
||||
);
|
||||
});
|
||||
|
||||
it("should use authorization_servers URL from resource metadata for discovery (different domain)", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://auth-server.com",
|
||||
authorization_endpoint: "https://auth-server.com/authorize",
|
||||
token_endpoint: "https://auth-server.com/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: ["https://auth-server.com/"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://auth-server.com/"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("should preserve full path in authorization_servers URL", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://auth-server.com/realms/my-realm",
|
||||
authorization_endpoint:
|
||||
"https://auth-server.com/realms/my-realm/authorize",
|
||||
token_endpoint: "https://auth-server.com/realms/my-realm/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: ["https://auth-server.com/realms/my-realm/"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://auth-server.com/realms/my-realm/"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("should fall back to serverUrl when authorization_servers is empty", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://mcp-server.com",
|
||||
authorization_endpoint: "https://mcp-server.com/authorize",
|
||||
token_endpoint: "https://mcp-server.com/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: [],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", "https://mcp-server.com"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAuthorizationServerUrl", () => {
|
||||
const serverUrl = "https://mcp.example.com";
|
||||
|
||||
it("returns server URL when resourceMetadata is null", () => {
|
||||
expect(getAuthorizationServerUrl(serverUrl, null)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns server URL when resourceMetadata is undefined", () => {
|
||||
expect(getAuthorizationServerUrl(serverUrl)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns server URL when authorization_servers is empty array", () => {
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to server URL when authorization_servers[0] is empty string", () => {
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [""],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns authorization_servers[0] when present and truthy", () => {
|
||||
const authUrl = "https://auth.example.com/";
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [authUrl],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL(authUrl),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,240 @@
|
|||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import {
|
||||
createOAuthCallbackServer,
|
||||
type OAuthCallbackServer,
|
||||
} from "@inspector/core/auth/node/oauth-callback-server.js";
|
||||
|
||||
describe("OAuthCallbackServer", () => {
|
||||
let server: OAuthCallbackServer;
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) await server.stop();
|
||||
});
|
||||
|
||||
it("start() returns port and redirectUrl", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
expect(result.port).toBeGreaterThan(0);
|
||||
expect(result.redirectUrl).toBe(
|
||||
`http://127.0.0.1:${result.port}/oauth/callback`,
|
||||
);
|
||||
});
|
||||
|
||||
it("start() supports custom host, path, and port", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
path: "/custom/path",
|
||||
});
|
||||
|
||||
expect(result.redirectUrl).toBe(
|
||||
`http://127.0.0.1:${result.port}/custom/path`,
|
||||
);
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?code=abc&state=xyz returns 200 and invokes onCallback", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const received: { code?: string; state?: string } = {};
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async (p) => {
|
||||
received.code = p.code;
|
||||
received.state = p.state;
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=authcode123&state=mystate`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/html");
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth complete");
|
||||
expect(html).toContain("close this window");
|
||||
expect(received.code).toBe("authcode123");
|
||||
expect(received.state).toBe("mystate");
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?code=abc returns 200 and invokes onCallback without state", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const received: { code?: string; state?: string } = {};
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async (p) => {
|
||||
received.code = p.code;
|
||||
received.state = p.state;
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=xyz`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(received.code).toBe("xyz");
|
||||
expect(received.state).toBeUndefined();
|
||||
});
|
||||
|
||||
it("GET /oauth/callback/guided returns 404 (single path only)", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback/guided?code=guided-code`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?error=access_denied returns 400 and invokes onError", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const errors: Array<{
|
||||
error: string;
|
||||
error_description?: string | null;
|
||||
}> = [];
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onError: (p) => errors.push(p),
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?error=access_denied&error_description=User%20denied`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
expect(html).toContain("access_denied");
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]!.error).toBe("access_denied");
|
||||
expect(errors[0]!.error_description).toBe("User denied");
|
||||
});
|
||||
|
||||
it("GET /oauth/callback (missing code and error) returns 400", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?state=foo`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
});
|
||||
|
||||
it("GET /other returns 404", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(`http://localhost:${result.port}/other`);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("POST /oauth/callback returns 405", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=x`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(405);
|
||||
});
|
||||
|
||||
it("stops server after first successful callback so second request fails", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async () => {},
|
||||
});
|
||||
|
||||
const first = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=first`,
|
||||
);
|
||||
expect(first.status).toBe(200);
|
||||
|
||||
// Server stops after sending 200, so second request gets connection refused
|
||||
await expect(
|
||||
fetch(`http://localhost:${result.port}/oauth/callback?code=second`),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("stop() closes the server", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
await server.stop();
|
||||
|
||||
await expect(
|
||||
fetch(`http://localhost:${result.port}/oauth/callback?code=x`),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("succeeds with 200 when no onCallback handler is configured", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=lonely`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth complete");
|
||||
});
|
||||
|
||||
it("returns 409 when a callback arrives after handled=true but before stop completes", async () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
// Hold onCallback open so handled=true is set but the server hasn't
|
||||
// yet finished stopping — second request slips into the 409 branch.
|
||||
onCallback: async () => {
|
||||
await gate;
|
||||
},
|
||||
});
|
||||
|
||||
const firstP = fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=first`,
|
||||
);
|
||||
// Give the server time to register handled=true before second hit.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const secondP = fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=second`,
|
||||
);
|
||||
const second = await secondP;
|
||||
expect(second.status).toBe(409);
|
||||
release();
|
||||
const first = await firstP;
|
||||
expect(first.status).toBe(200);
|
||||
});
|
||||
|
||||
it("onCallback rejection returns 500 and error HTML", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async () => {
|
||||
throw new Error("exchange failed");
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=abc`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
expect(html).toContain("exchange failed");
|
||||
});
|
||||
});
|
||||
601
clients/web/src/test/integration/auth/node/storage.test.ts
Normal file
601
clients/web/src/test/integration/auth/node/storage.test.ts
Normal file
|
|
@ -0,0 +1,601 @@
|
|||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
NodeOAuthStorage,
|
||||
getOAuthStore,
|
||||
clearAllOAuthClientState,
|
||||
} from "@inspector/core/auth/node/storage-node.js";
|
||||
import type {
|
||||
OAuthClientInformation,
|
||||
OAuthTokens,
|
||||
OAuthMetadata,
|
||||
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { waitForStateFile } from "@modelcontextprotocol/inspector-test-server";
|
||||
|
||||
// Unique path per process so parallel test files don't share the same state file
|
||||
const testStatePath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-${process.pid}-storage-node.json`,
|
||||
);
|
||||
|
||||
describe("NodeOAuthStorage", () => {
|
||||
let storage: NodeOAuthStorage;
|
||||
const testServerUrl = "http://localhost:3000";
|
||||
const stateFilePath = testStatePath;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Clean up any existing state file
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
|
||||
// Reset store state by clearing all servers
|
||||
const store = getOAuthStore(testStatePath);
|
||||
const state = store.getState();
|
||||
// Clear all server states
|
||||
Object.keys(state.servers).forEach((url) => {
|
||||
state.clearServerState(url);
|
||||
});
|
||||
|
||||
storage = new NodeOAuthStorage(testStatePath);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up state file after each test
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
|
||||
// Reset store state
|
||||
const store = getOAuthStore(testStatePath);
|
||||
const state = store.getState();
|
||||
Object.keys(state.servers).forEach((url) => {
|
||||
state.clearServerState(url);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClientInformation", () => {
|
||||
it("should return undefined when no client information is stored", async () => {
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored client information", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
client_secret: "test-secret",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(clientInfo.client_id);
|
||||
expect(result?.client_secret).toBe(clientInfo.client_secret);
|
||||
});
|
||||
|
||||
it("should return preregistered client information when requested", async () => {
|
||||
const preregisteredInfo: OAuthClientInformation = {
|
||||
client_id: "preregistered-id",
|
||||
client_secret: "preregistered-secret",
|
||||
};
|
||||
|
||||
// Store as preregistered by directly setting it in the store
|
||||
const store = getOAuthStore(testStatePath);
|
||||
store.getState().setServerState(testServerUrl, {
|
||||
preregisteredClientInformation: preregisteredInfo,
|
||||
});
|
||||
|
||||
const result = await storage.getClientInformation(testServerUrl, true);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(preregisteredInfo.client_id);
|
||||
expect(result?.client_secret).toBe(preregisteredInfo.client_secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveClientInformation", () => {
|
||||
it("should save client information", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(clientInfo.client_id);
|
||||
});
|
||||
|
||||
it("should overwrite existing client information", async () => {
|
||||
const firstInfo: OAuthClientInformation = {
|
||||
client_id: "first-id",
|
||||
};
|
||||
|
||||
const secondInfo: OAuthClientInformation = {
|
||||
client_id: "second-id",
|
||||
};
|
||||
|
||||
storage.saveClientInformation(testServerUrl, firstInfo);
|
||||
storage.saveClientInformation(testServerUrl, secondInfo);
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(secondInfo.client_id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTokens", () => {
|
||||
it("should return undefined when no tokens are stored", async () => {
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored tokens", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(tokens);
|
||||
});
|
||||
|
||||
it("should persist and return refresh_token", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
refresh_token: "test-refresh-token",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.access_token).toBe(tokens.access_token);
|
||||
expect(result?.refresh_token).toBe(tokens.refresh_token);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveTokens", () => {
|
||||
it("should save tokens", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(tokens);
|
||||
});
|
||||
|
||||
it("should overwrite existing tokens", async () => {
|
||||
const firstTokens: OAuthTokens = {
|
||||
access_token: "first-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
const secondTokens: OAuthTokens = {
|
||||
access_token: "second-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, firstTokens);
|
||||
await storage.saveTokens(testServerUrl, secondTokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(secondTokens);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCodeVerifier", () => {
|
||||
it("should return undefined when no code verifier is stored", async () => {
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored code verifier", async () => {
|
||||
const codeVerifier = "test-code-verifier";
|
||||
|
||||
await storage.saveCodeVerifier(testServerUrl, codeVerifier);
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
|
||||
expect(result).toBe(codeVerifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveCodeVerifier", () => {
|
||||
it("should save code verifier", async () => {
|
||||
const codeVerifier = "test-code-verifier";
|
||||
|
||||
await storage.saveCodeVerifier(testServerUrl, codeVerifier);
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
|
||||
expect(result).toBe(codeVerifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getScope", () => {
|
||||
it("should return undefined when no scope is stored", async () => {
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored scope", async () => {
|
||||
const scope = "read write";
|
||||
|
||||
await storage.saveScope(testServerUrl, scope);
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
|
||||
expect(result).toBe(scope);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveScope", () => {
|
||||
it("should save scope", async () => {
|
||||
const scope = "read write";
|
||||
|
||||
await storage.saveScope(testServerUrl, scope);
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
|
||||
expect(result).toBe(scope);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getServerMetadata", () => {
|
||||
it("should return null when no metadata is stored", async () => {
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return stored metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
|
||||
expect(result).toEqual(metadata);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveServerMetadata", () => {
|
||||
it("should save server metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
|
||||
expect(result).toEqual(metadata);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearClientInformation", () => {
|
||||
it("removes the dynamically-registered client information by default", async () => {
|
||||
await storage.saveClientInformation(testServerUrl, {
|
||||
client_id: "dyn",
|
||||
});
|
||||
expect(await storage.getClientInformation(testServerUrl)).toEqual({
|
||||
client_id: "dyn",
|
||||
});
|
||||
storage.clearClientInformation(testServerUrl);
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("removes the preregistered client information when isPreregistered=true", async () => {
|
||||
await storage.savePreregisteredClientInformation(testServerUrl, {
|
||||
client_id: "pre",
|
||||
});
|
||||
expect(await storage.getClientInformation(testServerUrl, true)).toEqual({
|
||||
client_id: "pre",
|
||||
});
|
||||
storage.clearClientInformation(testServerUrl, true);
|
||||
expect(
|
||||
await storage.getClientInformation(testServerUrl, true),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("individual clear methods", () => {
|
||||
it("clearTokens removes only tokens", async () => {
|
||||
await storage.saveTokens(testServerUrl, {
|
||||
access_token: "t",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
expect(await storage.getTokens(testServerUrl)).toBeDefined();
|
||||
storage.clearTokens(testServerUrl);
|
||||
expect(await storage.getTokens(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearCodeVerifier removes only the PKCE verifier", async () => {
|
||||
await storage.saveCodeVerifier(testServerUrl, "verifier");
|
||||
expect(storage.getCodeVerifier(testServerUrl)).toBe("verifier");
|
||||
storage.clearCodeVerifier(testServerUrl);
|
||||
expect(storage.getCodeVerifier(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearScope removes only the scope", async () => {
|
||||
await storage.saveScope(testServerUrl, "read write");
|
||||
expect(storage.getScope(testServerUrl)).toBe("read write");
|
||||
storage.clearScope(testServerUrl);
|
||||
expect(storage.getScope(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearServerMetadata removes only the cached metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
expect(storage.getServerMetadata(testServerUrl)).toEqual(metadata);
|
||||
storage.clearServerMetadata(testServerUrl);
|
||||
expect(storage.getServerMetadata(testServerUrl)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearServerState", () => {
|
||||
it("should clear all state for a server", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
|
||||
storage.clear(testServerUrl);
|
||||
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
expect(await storage.getTokens(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not affect state for other servers", async () => {
|
||||
const otherServerUrl = "http://localhost:4000";
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
await storage.saveClientInformation(otherServerUrl, clientInfo);
|
||||
|
||||
storage.clear(testServerUrl);
|
||||
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
const otherResult = await storage.getClientInformation(otherServerUrl);
|
||||
expect(otherResult).toBeDefined();
|
||||
expect(otherResult?.client_id).toBe(clientInfo.client_id);
|
||||
expect(otherResult).toEqual(clientInfo);
|
||||
});
|
||||
});
|
||||
|
||||
describe("multiple servers", () => {
|
||||
it("should store separate state for different servers", async () => {
|
||||
const server1Url = "http://localhost:3000";
|
||||
const server2Url = "http://localhost:4000";
|
||||
|
||||
const clientInfo1: OAuthClientInformation = {
|
||||
client_id: "client-1",
|
||||
};
|
||||
|
||||
const clientInfo2: OAuthClientInformation = {
|
||||
client_id: "client-2",
|
||||
};
|
||||
|
||||
storage.saveClientInformation(server1Url, clientInfo1);
|
||||
storage.saveClientInformation(server2Url, clientInfo2);
|
||||
|
||||
const result1 = await storage.getClientInformation(server1Url);
|
||||
const result2 = await storage.getClientInformation(server2Url);
|
||||
expect(result1).toEqual(clientInfo1);
|
||||
expect(result2).toEqual(clientInfo2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth Store (Zustand)", () => {
|
||||
const stateFilePath = testStatePath;
|
||||
|
||||
beforeEach(async () => {
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
});
|
||||
|
||||
it("should create a new store", () => {
|
||||
const store = getOAuthStore(testStatePath);
|
||||
expect(store).toBeDefined();
|
||||
expect(store.getState).toBeDefined();
|
||||
expect(store.setState).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return the same store instance via getOAuthStore", () => {
|
||||
const store1 = getOAuthStore(testStatePath);
|
||||
const store2 = getOAuthStore(testStatePath);
|
||||
expect(store1).toBe(store2);
|
||||
});
|
||||
|
||||
it("should persist state to file", async () => {
|
||||
// Use a unique path so no other test (e.g. "should overwrite..." with second-id) can
|
||||
// write to the same file; Zustand persist is async and can race with shared paths.
|
||||
const persistTestPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-persist-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
try {
|
||||
if (process.env.DEBUG_WAIT_FOR_STATE_FILE === "1") {
|
||||
console.error("[storage-node.test] state file path:", persistTestPath);
|
||||
}
|
||||
const store = getOAuthStore(persistTestPath);
|
||||
const serverUrl = "http://localhost:3000";
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
store.getState().setServerState(serverUrl, {
|
||||
clientInformation: clientInfo,
|
||||
});
|
||||
|
||||
type StateShape = {
|
||||
state: {
|
||||
servers: Record<
|
||||
string,
|
||||
{ clientInformation?: OAuthClientInformation }
|
||||
>;
|
||||
};
|
||||
};
|
||||
const parsed = await waitForStateFile<StateShape>(
|
||||
persistTestPath,
|
||||
(p) => {
|
||||
const s = (p as StateShape)?.state?.servers?.[serverUrl];
|
||||
return !!s?.clientInformation;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
expect(parsed.state.servers[serverUrl]?.clientInformation).toEqual(
|
||||
clientInfo,
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(persistTestPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NodeOAuthStorage with custom storagePath", () => {
|
||||
const testServerUrl = "http://localhost:3999";
|
||||
|
||||
it("should use custom path for state file", async () => {
|
||||
const customPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-test-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
|
||||
try {
|
||||
const storage = new NodeOAuthStorage(customPath);
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "custom-path-token",
|
||||
token_type: "Bearer",
|
||||
refresh_token: "custom-refresh",
|
||||
};
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
|
||||
type StateShape = {
|
||||
state: {
|
||||
servers: Record<string, { tokens?: { access_token?: string } }>;
|
||||
};
|
||||
};
|
||||
const parsed = await waitForStateFile<StateShape>(
|
||||
customPath,
|
||||
(p) => {
|
||||
const t = (p as StateShape)?.state?.servers?.[testServerUrl]?.tokens;
|
||||
return t?.access_token === tokens.access_token;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
|
||||
expect(parsed.state.servers[testServerUrl]?.tokens?.access_token).toBe(
|
||||
tokens.access_token,
|
||||
);
|
||||
|
||||
const stored = await storage.getTokens(testServerUrl);
|
||||
expect(stored?.access_token).toBe(tokens.access_token);
|
||||
expect(stored?.refresh_token).toBe(tokens.refresh_token);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(customPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("clearAllOAuthClientState clears every server in the default store", async () => {
|
||||
const defaultStore = getOAuthStore();
|
||||
defaultStore.getState().setServerState("http://server-a.test", {
|
||||
tokens: { access_token: "a", token_type: "Bearer" },
|
||||
});
|
||||
defaultStore.getState().setServerState("http://server-b.test", {
|
||||
tokens: { access_token: "b", token_type: "Bearer" },
|
||||
});
|
||||
clearAllOAuthClientState();
|
||||
const all = defaultStore.getState();
|
||||
expect(all.getServerState("http://server-a.test").tokens).toBeUndefined();
|
||||
expect(all.getServerState("http://server-b.test").tokens).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should isolate state from default store", async () => {
|
||||
const customPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-isolate-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
|
||||
try {
|
||||
const defaultStore = getOAuthStore();
|
||||
defaultStore.getState().setServerState(testServerUrl, {
|
||||
tokens: {
|
||||
access_token: "default-token",
|
||||
token_type: "Bearer",
|
||||
},
|
||||
});
|
||||
|
||||
const customStorage = new NodeOAuthStorage(customPath);
|
||||
await customStorage.saveTokens(testServerUrl, {
|
||||
access_token: "custom-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
|
||||
const fromCustom = await customStorage.getTokens(testServerUrl);
|
||||
expect(fromCustom?.access_token).toBe("custom-token");
|
||||
|
||||
const defaultStorage = new NodeOAuthStorage();
|
||||
const fromDefault = await defaultStorage.getTokens(testServerUrl);
|
||||
expect(fromDefault?.access_token).toBe("default-token");
|
||||
|
||||
defaultStore.getState().clearServerState(testServerUrl);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(customPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
441
clients/web/src/test/integration/auth/state-machine.test.ts
Normal file
441
clients/web/src/test/integration/auth/state-machine.test.ts
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
OAuthStateMachine,
|
||||
oauthTransitions,
|
||||
} from "@inspector/core/auth/state-machine.js";
|
||||
import type { AuthGuidedState, OAuthStep } from "@inspector/core/auth/types.js";
|
||||
import { EMPTY_GUIDED_STATE } from "@inspector/core/auth/types.js";
|
||||
import type { BaseOAuthClientProvider } from "@inspector/core/auth/providers.js";
|
||||
import type {
|
||||
OAuthMetadata,
|
||||
OAuthProtectedResourceMetadata,
|
||||
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
|
||||
// Mock SDK functions
|
||||
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
discoverAuthorizationServerMetadata: vi.fn(),
|
||||
discoverOAuthProtectedResourceMetadata: vi.fn(),
|
||||
registerClient: vi.fn(),
|
||||
startAuthorization: vi.fn(),
|
||||
exchangeAuthorization: vi.fn(),
|
||||
selectResourceURL: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("OAuthStateMachine", () => {
|
||||
let mockProvider: BaseOAuthClientProvider;
|
||||
let updateState: (updates: Partial<AuthGuidedState>) => void;
|
||||
let state: AuthGuidedState;
|
||||
|
||||
beforeEach(() => {
|
||||
state = { ...EMPTY_GUIDED_STATE };
|
||||
updateState = vi.fn((updates: Partial<AuthGuidedState>) => {
|
||||
state = { ...state, ...updates };
|
||||
});
|
||||
|
||||
mockProvider = {
|
||||
serverUrl: "http://localhost:3000",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
scope: "read write",
|
||||
clientMetadata: {
|
||||
redirect_uris: ["http://localhost:3000/callback"],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code"],
|
||||
response_types: ["code"],
|
||||
client_name: "Test Client",
|
||||
scope: "read write",
|
||||
},
|
||||
clientInformation: vi.fn(),
|
||||
saveClientInformation: vi.fn(),
|
||||
tokens: vi.fn(),
|
||||
saveTokens: vi.fn(),
|
||||
codeVerifier: vi.fn(() => "test-code-verifier"),
|
||||
clear: vi.fn(),
|
||||
state: vi.fn(() => "test-state"),
|
||||
getServerMetadata: vi.fn(() => null),
|
||||
saveServerMetadata: vi.fn(),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
});
|
||||
|
||||
describe("oauthTransitions", () => {
|
||||
it("should have transitions for all OAuth steps", () => {
|
||||
const steps: OAuthStep[] = [
|
||||
"metadata_discovery",
|
||||
"client_registration",
|
||||
"authorization_redirect",
|
||||
"authorization_code",
|
||||
"token_request",
|
||||
"complete",
|
||||
];
|
||||
|
||||
steps.forEach((step) => {
|
||||
expect(oauthTransitions[step]).toBeDefined();
|
||||
expect(oauthTransitions[step].canTransition).toBeDefined();
|
||||
expect(oauthTransitions[step].execute).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuthStateMachine", () => {
|
||||
it("should create state machine instance", () => {
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
|
||||
expect(stateMachine).toBeDefined();
|
||||
});
|
||||
|
||||
it("should update state when executeStep is called", async () => {
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(updateState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Resource metadata discovery and selection", () => {
|
||||
const serverUrl = "http://localhost:3000";
|
||||
const resourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const {
|
||||
discoverAuthorizationServerMetadata,
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
selectResourceURL,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockReset();
|
||||
vi.mocked(selectResourceURL).mockReset();
|
||||
});
|
||||
|
||||
it("should discover resource metadata from well-known and use first authorization server", async () => {
|
||||
const selectedResource = new URL("http://localhost:3000");
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
resourceMetadata as OAuthProtectedResourceMetadata,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(selectedResource);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
);
|
||||
expect(selectResourceURL).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
resourceMetadata,
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata,
|
||||
resource: selectedResource,
|
||||
resourceMetadataError: null,
|
||||
authServerUrl: new URL("http://localhost:3000"),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use authorization_servers URL from resource metadata for auth server discovery", async () => {
|
||||
const authServerUrl = "https://auth-server.com/";
|
||||
const resourceMetaDifferentAuth: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [authServerUrl],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
const selectedResource = new URL(serverUrl);
|
||||
const {
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
discoverAuthorizationServerMetadata,
|
||||
selectResourceURL,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
resourceMetaDifferentAuth,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(selectedResource);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL(authServerUrl),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: resourceMetaDifferentAuth,
|
||||
authServerUrl: new URL(authServerUrl),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should call selectResourceURL only when resource metadata is present", async () => {
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue(
|
||||
new Error(
|
||||
"Resource server does not implement OAuth 2.0 Protected Resource Metadata.",
|
||||
),
|
||||
);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(selectResourceURL).not.toHaveBeenCalled();
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: null,
|
||||
resourceMetadataError: expect.any(Error),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use default auth server URL when discovery fails", async () => {
|
||||
const {
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
discoverAuthorizationServerMetadata,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue(
|
||||
new Error("Discovery failed"),
|
||||
);
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", serverUrl),
|
||||
{}, // No fetchFn when not provided (conditional spread omits it)
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
authServerUrl: new URL("/", serverUrl),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use default auth server when metadata has empty authorization_servers", async () => {
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const metaNoServers = {
|
||||
...resourceMetadata,
|
||||
authorization_servers: [] as string[],
|
||||
};
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
metaNoServers as OAuthProtectedResourceMetadata,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(
|
||||
new URL("http://localhost:3000"),
|
||||
);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(selectResourceURL).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
metaNoServers,
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: metaNoServers,
|
||||
authServerUrl: new URL("/", serverUrl),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass fetchFn to registerClient when provided", async () => {
|
||||
const { registerClient } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
vi.mocked(registerClient).mockResolvedValue({
|
||||
redirect_uris: ["http://localhost/callback"],
|
||||
client_id: "registered-client-id",
|
||||
});
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
mockFetchFn,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
expect(state.oauthStep).toBe("client_registration");
|
||||
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(registerClient).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
expect.objectContaining({
|
||||
fetchFn: mockFetchFn,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass fetchFn to exchangeAuthorization when provided", async () => {
|
||||
const { exchangeAuthorization } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
const metadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
vi.mocked(exchangeAuthorization).mockResolvedValue({
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
|
||||
const providerWithMetadata = {
|
||||
...mockProvider,
|
||||
getServerMetadata: vi.fn(() => metadata),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
|
||||
const tokenRequestState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
oauthMetadata: metadata as OAuthMetadata,
|
||||
oauthClientInfo: { client_id: "test-client" },
|
||||
authorizationCode: "test-code",
|
||||
};
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
providerWithMetadata,
|
||||
updateState,
|
||||
mockFetchFn,
|
||||
);
|
||||
await stateMachine.executeStep(tokenRequestState);
|
||||
|
||||
expect(exchangeAuthorization).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
expect.objectContaining({
|
||||
fetchFn: mockFetchFn,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("token_request execute throws when client information cannot be obtained", async () => {
|
||||
const metadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
const providerNoClient = {
|
||||
...mockProvider,
|
||||
getServerMetadata: vi.fn(() => metadata),
|
||||
clientInformation: vi.fn(async () => undefined),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
|
||||
const tokenState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
oauthMetadata: metadata as OAuthMetadata,
|
||||
authorizationCode: "code-without-client",
|
||||
};
|
||||
|
||||
await expect(
|
||||
oauthTransitions.token_request.execute({
|
||||
state: tokenState,
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: providerNoClient,
|
||||
updateState,
|
||||
}),
|
||||
).rejects.toThrow("Client information not available for token exchange");
|
||||
});
|
||||
|
||||
it("complete.canTransition always returns false (terminal state)", async () => {
|
||||
const result = await oauthTransitions.complete.canTransition({
|
||||
state: { ...EMPTY_GUIDED_STATE, oauthStep: "complete" },
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: mockProvider,
|
||||
updateState,
|
||||
});
|
||||
expect(result).toBe(false);
|
||||
// execute is a no-op
|
||||
await expect(
|
||||
oauthTransitions.complete.execute({
|
||||
state: { ...EMPTY_GUIDED_STATE, oauthStep: "complete" },
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: mockProvider,
|
||||
updateState,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("executeStep throws when the current step cannot transition", async () => {
|
||||
// metadata_discovery.canTransition is unconditional (returns true), but
|
||||
// token_request requires authorizationCode + metadata + clientInfo; an
|
||||
// empty state will refuse to transition.
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
const blockedState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
};
|
||||
await expect(stateMachine.executeStep(blockedState)).rejects.toThrow(
|
||||
/Cannot transition from token_request/,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
/**
|
||||
* OAuth client test fixtures for InspectorClient OAuth tests.
|
||||
* These produce InspectorClient OAuth configuration and simulate OAuth flows.
|
||||
*/
|
||||
|
||||
import type {
|
||||
OAuthNavigation,
|
||||
RedirectUrlProvider,
|
||||
} from "@inspector/core/auth/providers.js";
|
||||
import type { OAuthStorage } from "@inspector/core/auth/storage.js";
|
||||
import { ConsoleNavigation } from "@inspector/core/auth/providers.js";
|
||||
import { NodeOAuthStorage } from "@inspector/core/auth/node/storage-node.js";
|
||||
|
||||
/** Creates a static RedirectUrlProvider for tests. Single URL for both modes. */
|
||||
function createStaticRedirectUrlProvider(
|
||||
redirectUrl: string,
|
||||
): RedirectUrlProvider {
|
||||
return {
|
||||
getRedirectUrl: () => redirectUrl,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates OAuth configuration for InspectorClient tests
|
||||
*/
|
||||
export function createOAuthClientConfig(options: {
|
||||
mode: "static" | "dcr" | "cimd";
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
clientMetadataUrl?: string;
|
||||
redirectUrl: string;
|
||||
scope?: string;
|
||||
}): {
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
clientMetadataUrl?: string;
|
||||
redirectUrlProvider: RedirectUrlProvider;
|
||||
scope?: string;
|
||||
storage: OAuthStorage;
|
||||
navigation: OAuthNavigation;
|
||||
} {
|
||||
const config: {
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
clientMetadataUrl?: string;
|
||||
redirectUrlProvider: RedirectUrlProvider;
|
||||
scope?: string;
|
||||
storage: OAuthStorage;
|
||||
navigation: OAuthNavigation;
|
||||
} = {
|
||||
redirectUrlProvider: createStaticRedirectUrlProvider(options.redirectUrl),
|
||||
storage: new NodeOAuthStorage(),
|
||||
navigation: new ConsoleNavigation(),
|
||||
};
|
||||
|
||||
if (options.mode === "static") {
|
||||
if (!options.clientId) {
|
||||
throw new Error("clientId is required for static mode");
|
||||
}
|
||||
config.clientId = options.clientId;
|
||||
if (options.clientSecret) {
|
||||
config.clientSecret = options.clientSecret;
|
||||
}
|
||||
} else if (options.mode === "dcr") {
|
||||
// DCR mode - no clientId needed, will be registered
|
||||
if (options.clientId) {
|
||||
config.clientId = options.clientId;
|
||||
}
|
||||
} else if (options.mode === "cimd") {
|
||||
if (!options.clientMetadataUrl) {
|
||||
throw new Error("clientMetadataUrl is required for CIMD mode");
|
||||
}
|
||||
config.clientMetadataUrl = options.clientMetadataUrl;
|
||||
}
|
||||
|
||||
if (options.scope) {
|
||||
config.scope = options.scope;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Client metadata document for CIMD testing
|
||||
*/
|
||||
export interface ClientMetadataDocument {
|
||||
redirect_uris: string[];
|
||||
token_endpoint_auth_method?: string;
|
||||
grant_types?: string[];
|
||||
response_types?: string[];
|
||||
client_name?: string;
|
||||
client_uri?: string;
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Express server that serves a client metadata document for CIMD testing
|
||||
* The server runs on a different port and serves the metadata at the root path
|
||||
*
|
||||
* @param metadata - The client metadata document to serve
|
||||
* @returns Object with server URL and cleanup function
|
||||
*/
|
||||
export async function createClientMetadataServer(
|
||||
metadata: ClientMetadataDocument,
|
||||
): Promise<{ url: string; stop: () => Promise<void> }> {
|
||||
const express = await import("express");
|
||||
const app = express.default();
|
||||
|
||||
app.get("/", (_req, res) => {
|
||||
res.json(metadata);
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = app.listen(0, () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Failed to get server address"));
|
||||
return;
|
||||
}
|
||||
const port = address.port;
|
||||
const url = `http://localhost:${port}`;
|
||||
|
||||
resolve({
|
||||
url,
|
||||
stop: async () => {
|
||||
return new Promise<void>((resolveStop) => {
|
||||
server.close(() => {
|
||||
resolveStop();
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to programmatically complete OAuth authorization
|
||||
* Makes HTTP GET request to authorization URL and extracts authorization code
|
||||
* The test server's authorization endpoint auto-approves and redirects with code
|
||||
*
|
||||
* @param authorizationUrl - The authorization URL from oauthAuthorizationRequired event
|
||||
* @returns Authorization code extracted from redirect URL
|
||||
*/
|
||||
export async function completeOAuthAuthorization(
|
||||
authorizationUrl: URL,
|
||||
): Promise<string> {
|
||||
const response = await fetch(authorizationUrl.toString(), {
|
||||
redirect: "manual",
|
||||
});
|
||||
|
||||
if (response.status !== 302 && response.status !== 301) {
|
||||
throw new Error(
|
||||
`Expected redirect (302/301), got ${response.status}: ${await response.text()}`,
|
||||
);
|
||||
}
|
||||
|
||||
const redirectUrl = response.headers.get("location");
|
||||
if (!redirectUrl) {
|
||||
throw new Error("No Location header in redirect response");
|
||||
}
|
||||
|
||||
const redirectUrlObj = new URL(redirectUrl);
|
||||
const code = redirectUrlObj.searchParams.get("code");
|
||||
if (!code) {
|
||||
throw new Error(`No authorization code in redirect URL: ${redirectUrl}`);
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,200 @@
|
|||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
vi,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
} from "vitest";
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import * as fs from "node:fs/promises";
|
||||
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
|
||||
import { createTransportNode } from "@inspector/core/mcp/node/transport.js";
|
||||
import type { MCPServerConfig } from "@inspector/core/mcp/types.js";
|
||||
import { NodeOAuthStorage } from "@inspector/core/auth/node/storage-node.js";
|
||||
import { createOAuthClientConfig } from "../helpers/oauth-client-fixtures.js";
|
||||
import type { InspectorClientOptions } from "@inspector/core/mcp/inspectorClient.js";
|
||||
|
||||
const oauthTestStatePath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-oauth-${process.pid}-inspectorClient-oauth-fetchFn.json`,
|
||||
);
|
||||
|
||||
function createTestOAuthConfig(
|
||||
options: Parameters<typeof createOAuthClientConfig>[0],
|
||||
) {
|
||||
return {
|
||||
...createOAuthClientConfig(options),
|
||||
storage: new NodeOAuthStorage(oauthTestStatePath),
|
||||
};
|
||||
}
|
||||
|
||||
const mockAuth = vi.fn();
|
||||
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
auth: (...args: unknown[]) => mockAuth(...args),
|
||||
}));
|
||||
|
||||
describe("InspectorClient OAuth fetchFn", () => {
|
||||
let client: InspectorClient;
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await fs.unlink(oauthTestStatePath);
|
||||
} catch {
|
||||
// Ignore if file does not exist or already removed
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
mockAuth.mockImplementation(
|
||||
async (provider: { redirectToAuthorization: (url: URL) => void }) => {
|
||||
provider.redirectToAuthorization(
|
||||
new URL("http://example.com/oauth/authorize"),
|
||||
);
|
||||
return "REDIRECT";
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (client) {
|
||||
try {
|
||||
await client.disconnect();
|
||||
} catch {
|
||||
// Ignore disconnect errors
|
||||
}
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should pass fetchFn to auth() when provided", async () => {
|
||||
const mockFetchFn = vi.fn();
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-client",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
});
|
||||
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig,
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
fetch: mockFetchFn,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const url = await client.authenticate();
|
||||
|
||||
expect(url).toBeInstanceOf(URL);
|
||||
expect(mockAuth).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
fetchFn: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass fetchFn to auth() when not provided (uses default fetch)", async () => {
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-client",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
});
|
||||
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig,
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
} as InspectorClientOptions,
|
||||
);
|
||||
|
||||
await client.authenticate();
|
||||
|
||||
expect(mockAuth).toHaveBeenCalled();
|
||||
const callArgs = mockAuth.mock.calls[0]!;
|
||||
const options = callArgs[1];
|
||||
expect(options).toHaveProperty("fetchFn");
|
||||
expect(typeof options.fetchFn).toBe("function");
|
||||
});
|
||||
|
||||
it("should pass fetchFn to auth() in completeOAuthFlow when provided", async () => {
|
||||
const mockFetchFn = vi.fn();
|
||||
mockAuth.mockImplementation(
|
||||
async (provider: { saveTokens: (tokens: unknown) => void }) => {
|
||||
provider.saveTokens({
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
return "AUTHORIZED";
|
||||
},
|
||||
);
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-client",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
});
|
||||
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig,
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
fetch: mockFetchFn,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await client.completeOAuthFlow("test-authorization-code");
|
||||
|
||||
expect(mockAuth).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
authorizationCode: "test-authorization-code",
|
||||
fetchFn: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,515 @@
|
|||
/**
|
||||
* End-to-end OAuth tests for InspectorClient using RemoteOAuthStorage.
|
||||
* Tests OAuth flows with remote storage (HTTP API) instead of file storage.
|
||||
* These tests verify that OAuth state persists correctly via the remote storage API.
|
||||
*/
|
||||
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { mkdtempSync, rmSync, unlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { serve } from "@hono/node-server";
|
||||
import type { ServerType } from "@hono/node-server";
|
||||
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
|
||||
import { createRemoteTransport } from "@inspector/core/mcp/remote/createRemoteTransport.js";
|
||||
import { createRemoteFetch } from "@inspector/core/mcp/remote/createRemoteFetch.js";
|
||||
import { RemoteOAuthStorage } from "@inspector/core/auth/remote/storage-remote.js";
|
||||
import { NodeOAuthStorage } from "@inspector/core/auth/node/storage-node.js";
|
||||
import { createRemoteApp } from "@inspector/core/mcp/remote/node/server.js";
|
||||
import {
|
||||
TestServerHttp,
|
||||
waitForOAuthWellKnown,
|
||||
waitForRemoteStore,
|
||||
getDefaultServerConfig,
|
||||
createOAuthTestServerConfig,
|
||||
clearOAuthTestData,
|
||||
} from "@modelcontextprotocol/inspector-test-server";
|
||||
import {
|
||||
createOAuthClientConfig,
|
||||
completeOAuthAuthorization,
|
||||
} from "../helpers/oauth-client-fixtures.js";
|
||||
import { ConsoleNavigation } from "@inspector/core/auth/providers.js";
|
||||
import type { InspectorClientOptions } from "@inspector/core/mcp/inspectorClient.js";
|
||||
import type { MCPServerConfig } from "@inspector/core/mcp/types.js";
|
||||
|
||||
const oauthTestStatePath = join(
|
||||
tmpdir(),
|
||||
`mcp-oauth-${process.pid}-inspectorClient-oauth-remote-storage-e2e.json`,
|
||||
);
|
||||
|
||||
function createTestOAuthConfig(
|
||||
options: Parameters<typeof createOAuthClientConfig>[0],
|
||||
) {
|
||||
return {
|
||||
...createOAuthClientConfig(options),
|
||||
storage: new NodeOAuthStorage(oauthTestStatePath),
|
||||
};
|
||||
}
|
||||
|
||||
interface TransportConfig {
|
||||
name: string;
|
||||
serverType: "sse" | "streamable-http";
|
||||
clientType: "sse" | "streamable-http";
|
||||
endpoint: string;
|
||||
}
|
||||
|
||||
const transports: TransportConfig[] = [
|
||||
{
|
||||
name: "SSE",
|
||||
serverType: "sse",
|
||||
clientType: "sse",
|
||||
endpoint: "/sse",
|
||||
},
|
||||
{
|
||||
name: "Streamable HTTP",
|
||||
serverType: "streamable-http",
|
||||
clientType: "streamable-http",
|
||||
endpoint: "/mcp",
|
||||
},
|
||||
];
|
||||
|
||||
interface StartRemoteServerOptions {
|
||||
storageDir?: string;
|
||||
}
|
||||
|
||||
async function startRemoteServer(
|
||||
port: number,
|
||||
options: StartRemoteServerOptions = {},
|
||||
): Promise<{
|
||||
baseUrl: string;
|
||||
server: ServerType;
|
||||
authToken: string;
|
||||
}> {
|
||||
const { app, authToken } = createRemoteApp({
|
||||
storageDir: options.storageDir,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = serve(
|
||||
{ fetch: app.fetch, port, hostname: "127.0.0.1" },
|
||||
(info) => {
|
||||
const actualPort =
|
||||
info && typeof info === "object" && "port" in info
|
||||
? (info as { port: number }).port
|
||||
: port;
|
||||
resolve({
|
||||
baseUrl: `http://127.0.0.1:${actualPort}`,
|
||||
server,
|
||||
authToken,
|
||||
});
|
||||
},
|
||||
);
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
describe("InspectorClient OAuth E2E with Remote Storage", () => {
|
||||
let mcpServer: TestServerHttp;
|
||||
let remoteServer: ServerType | null = null;
|
||||
let remoteBaseUrl: string | null = null;
|
||||
let remoteAuthToken: string | null = null;
|
||||
let client: InspectorClient;
|
||||
let tempDir: string | null = null;
|
||||
const testRedirectUrl = "http://localhost:3001/oauth/callback";
|
||||
|
||||
beforeEach(() => {
|
||||
clearOAuthTestData();
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-remote-storage-test-"));
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
try {
|
||||
unlinkSync(oauthTestStatePath);
|
||||
} catch {
|
||||
// Ignore if file does not exist or already removed
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (client) {
|
||||
await client.disconnect();
|
||||
}
|
||||
if (mcpServer) {
|
||||
await mcpServer.stop();
|
||||
}
|
||||
if (remoteServer) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
remoteServer!.close((err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
remoteServer = null;
|
||||
}
|
||||
if (tempDir) {
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
tempDir = null;
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function setupRemoteServer(): Promise<void> {
|
||||
const { baseUrl, server, authToken } = await startRemoteServer(0, {
|
||||
storageDir: tempDir!,
|
||||
});
|
||||
remoteServer = server;
|
||||
remoteBaseUrl = baseUrl;
|
||||
remoteAuthToken = authToken;
|
||||
}
|
||||
|
||||
describe.each(transports)(
|
||||
"Static/Preregistered Client Mode ($name)",
|
||||
(transport) => {
|
||||
it("should complete OAuth flow with static client using remote storage", async () => {
|
||||
await setupRemoteServer();
|
||||
|
||||
const staticClientId = "test-static-client";
|
||||
const staticClientSecret = "test-static-secret";
|
||||
|
||||
// Create test server with OAuth enabled and static client
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: transport.serverType,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: true,
|
||||
staticClients: [
|
||||
{
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUris: [testRedirectUrl],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
mcpServer = new TestServerHttp(serverConfig);
|
||||
const port = await mcpServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
await waitForOAuthWellKnown(serverUrl);
|
||||
|
||||
// Create client with remote transport and remote OAuth storage
|
||||
const createTransport = createRemoteTransport({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteFetch = createRemoteFetch({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteStorage = new RemoteOAuthStorage({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
storeId: "oauth",
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransport,
|
||||
fetch: remoteFetch,
|
||||
oauth: {
|
||||
storage: remoteStorage,
|
||||
navigation: new ConsoleNavigation(),
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
};
|
||||
|
||||
client = new InspectorClient(
|
||||
{
|
||||
type: transport.clientType,
|
||||
url: `${serverUrl}${transport.endpoint}`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig,
|
||||
);
|
||||
|
||||
const authUrl = await client.runGuidedAuth();
|
||||
if (!authUrl) throw new Error("Expected authorization URL");
|
||||
expect(authUrl.href).toContain("/oauth/authorize");
|
||||
|
||||
const authCode = await completeOAuthAuthorization(authUrl);
|
||||
await client.completeOAuthFlow(authCode);
|
||||
await client.connect();
|
||||
|
||||
// Verify tokens are stored
|
||||
const tokens = await client.getOAuthTokens();
|
||||
expect(tokens).toBeDefined();
|
||||
expect(tokens?.access_token).toBeDefined();
|
||||
expect(tokens?.token_type).toBe("Bearer");
|
||||
|
||||
// Connection should now be successful
|
||||
expect(client.getStatus()).toBe("connected");
|
||||
});
|
||||
|
||||
it("should persist OAuth state and reload on new client instance", async () => {
|
||||
await setupRemoteServer();
|
||||
|
||||
const staticClientId = "test-static-client-reload";
|
||||
const staticClientSecret = "test-static-secret-reload";
|
||||
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: transport.serverType,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: true,
|
||||
staticClients: [
|
||||
{
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUris: [testRedirectUrl],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
mcpServer = new TestServerHttp(serverConfig);
|
||||
const port = await mcpServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
await waitForOAuthWellKnown(serverUrl);
|
||||
|
||||
const createTransport = createRemoteTransport({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteFetch = createRemoteFetch({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteStorage = new RemoteOAuthStorage({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
storeId: "oauth",
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
|
||||
// First client: complete OAuth flow
|
||||
const oauthConfig1 = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig1: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransport,
|
||||
fetch: remoteFetch,
|
||||
oauth: {
|
||||
storage: remoteStorage,
|
||||
navigation: oauthConfig1.navigation,
|
||||
redirectUrlProvider: oauthConfig1.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig1.clientId,
|
||||
clientSecret: oauthConfig1.clientSecret,
|
||||
clientMetadataUrl: oauthConfig1.clientMetadataUrl,
|
||||
scope: oauthConfig1.scope,
|
||||
},
|
||||
};
|
||||
|
||||
const client1 = new InspectorClient(
|
||||
{
|
||||
type: transport.clientType,
|
||||
url: `${serverUrl}${transport.endpoint}`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig1,
|
||||
);
|
||||
|
||||
const authUrl = await client1.runGuidedAuth();
|
||||
if (!authUrl) throw new Error("Expected authorization URL");
|
||||
const authCode = await completeOAuthAuthorization(authUrl);
|
||||
await client1.completeOAuthFlow(authCode);
|
||||
await client1.connect();
|
||||
|
||||
const tokens1 = await client1.getOAuthTokens();
|
||||
expect(tokens1).toBeDefined();
|
||||
await client1.disconnect();
|
||||
|
||||
// Wait until remote server has persisted state before creating second client
|
||||
await waitForRemoteStore(
|
||||
remoteBaseUrl!,
|
||||
"oauth",
|
||||
remoteAuthToken!,
|
||||
(body) => {
|
||||
const b = body as {
|
||||
state?: {
|
||||
servers?: Record<
|
||||
string,
|
||||
{ tokens?: { access_token?: string } }
|
||||
>;
|
||||
};
|
||||
};
|
||||
return !!(
|
||||
b?.state?.servers &&
|
||||
Object.values(b.state.servers).some(
|
||||
(s) => s?.tokens?.access_token,
|
||||
)
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Second client: should load persisted state
|
||||
const remoteStorage2 = new RemoteOAuthStorage({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
storeId: "oauth",
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
|
||||
const oauthConfig2 = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig2: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransport,
|
||||
fetch: remoteFetch,
|
||||
oauth: {
|
||||
storage: remoteStorage2,
|
||||
navigation: oauthConfig2.navigation,
|
||||
redirectUrlProvider: oauthConfig2.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig2.clientId,
|
||||
clientSecret: oauthConfig2.clientSecret,
|
||||
clientMetadataUrl: oauthConfig2.clientMetadataUrl,
|
||||
scope: oauthConfig2.scope,
|
||||
},
|
||||
};
|
||||
|
||||
client = new InspectorClient(
|
||||
{
|
||||
type: transport.clientType,
|
||||
url: `${serverUrl}${transport.endpoint}`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig2,
|
||||
);
|
||||
|
||||
// Wait for storage to hydrate and tokens to be available
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const tokens = await client.getOAuthTokens();
|
||||
if (!tokens) {
|
||||
throw new Error("Tokens not yet loaded from storage");
|
||||
}
|
||||
return tokens;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
|
||||
// Should be able to connect without re-authenticating
|
||||
await client.connect();
|
||||
expect(client.getStatus()).toBe("connected");
|
||||
|
||||
// Tokens should be loaded from remote storage
|
||||
const tokens2 = await client.getOAuthTokens();
|
||||
expect(tokens2).toBeDefined();
|
||||
expect(tokens2?.access_token).toBe(tokens1?.access_token);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe.each(transports)(
|
||||
"DCR (Dynamic Client Registration) Mode ($name)",
|
||||
(transport) => {
|
||||
it("should register client and complete OAuth flow using remote storage", async () => {
|
||||
await setupRemoteServer();
|
||||
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: transport.serverType,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: true,
|
||||
supportDCR: true,
|
||||
}),
|
||||
};
|
||||
|
||||
mcpServer = new TestServerHttp(serverConfig);
|
||||
const port = await mcpServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
await waitForOAuthWellKnown(serverUrl);
|
||||
|
||||
const createTransport = createRemoteTransport({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteFetch = createRemoteFetch({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
const remoteStorage = new RemoteOAuthStorage({
|
||||
baseUrl: remoteBaseUrl!,
|
||||
storeId: "oauth",
|
||||
authToken: remoteAuthToken!,
|
||||
});
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "dcr",
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransport,
|
||||
fetch: remoteFetch,
|
||||
oauth: {
|
||||
storage: remoteStorage,
|
||||
navigation: new ConsoleNavigation(),
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
};
|
||||
|
||||
client = new InspectorClient(
|
||||
{
|
||||
type: transport.clientType,
|
||||
url: `${serverUrl}${transport.endpoint}`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig,
|
||||
);
|
||||
|
||||
const authUrl = await client.runGuidedAuth();
|
||||
if (!authUrl) throw new Error("Expected authorization URL");
|
||||
expect(authUrl.href).toContain("/oauth/authorize");
|
||||
|
||||
const authCode = await completeOAuthAuthorization(authUrl);
|
||||
await client.completeOAuthFlow(authCode);
|
||||
await client.connect();
|
||||
|
||||
// Verify tokens are stored
|
||||
const tokens = await client.getOAuthTokens();
|
||||
expect(tokens).toBeDefined();
|
||||
expect(tokens?.access_token).toBeDefined();
|
||||
|
||||
expect(client.getStatus()).toBe("connected");
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -0,0 +1,553 @@
|
|||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import * as fs from "node:fs/promises";
|
||||
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
|
||||
import { FetchRequestLogState } from "@inspector/core/mcp/state/index.js";
|
||||
import { createTransportNode } from "@inspector/core/mcp/node/transport.js";
|
||||
import type { MCPServerConfig } from "@inspector/core/mcp/types.js";
|
||||
import { NodeOAuthStorage } from "@inspector/core/auth/node/storage-node.js";
|
||||
import {
|
||||
TestServerHttp,
|
||||
waitForEvent,
|
||||
getDefaultServerConfig,
|
||||
createOAuthTestServerConfig,
|
||||
clearOAuthTestData,
|
||||
} from "@modelcontextprotocol/inspector-test-server";
|
||||
import {
|
||||
createOAuthClientConfig,
|
||||
completeOAuthAuthorization,
|
||||
} from "../helpers/oauth-client-fixtures.js";
|
||||
import type { InspectorClientOptions } from "@inspector/core/mcp/inspectorClient.js";
|
||||
|
||||
const oauthTestStatePath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-oauth-${process.pid}-inspectorClient-oauth.json`,
|
||||
);
|
||||
|
||||
function createTestOAuthConfig(
|
||||
options: Parameters<typeof createOAuthClientConfig>[0],
|
||||
) {
|
||||
return {
|
||||
...createOAuthClientConfig(options),
|
||||
storage: new NodeOAuthStorage(oauthTestStatePath),
|
||||
};
|
||||
}
|
||||
|
||||
describe("InspectorClient OAuth", () => {
|
||||
let client: InspectorClient;
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await fs.unlink(oauthTestStatePath);
|
||||
} catch {
|
||||
// Ignore if file does not exist or already removed
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
// Create client with HTTP transport (OAuth only works with HTTP transports)
|
||||
const config: MCPServerConfig = {
|
||||
type: "sse",
|
||||
url: "http://localhost:3000/sse",
|
||||
};
|
||||
client = new InspectorClient(config, {
|
||||
environment: { transport: createTransportNode },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (client) {
|
||||
try {
|
||||
await client.disconnect();
|
||||
} catch {
|
||||
// Ignore disconnect errors
|
||||
}
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("OAuth Configuration", () => {
|
||||
it("should set OAuth configuration", () => {
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-client-id",
|
||||
clientSecret: "test-secret",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
scope: "read write",
|
||||
});
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" },
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Configuration should be set (no error thrown)
|
||||
expect(client).toBeDefined();
|
||||
});
|
||||
|
||||
it("should set OAuth configuration with clientMetadataUrl for CIMD", () => {
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "cimd",
|
||||
clientMetadataUrl: "https://example.com/client-metadata.json",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
scope: "read write",
|
||||
});
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" },
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(client).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth Token Management", () => {
|
||||
beforeEach(() => {
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-client-id",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
});
|
||||
client = new InspectorClient(
|
||||
{ type: "sse", url: "http://localhost:3000/sse" },
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should return undefined tokens when not authorized", async () => {
|
||||
const tokens = await client.getOAuthTokens();
|
||||
expect(tokens).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should clear OAuth tokens", () => {
|
||||
client.clearOAuthTokens();
|
||||
// Should not throw
|
||||
expect(client).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return false for isOAuthAuthorized when not authorized", async () => {
|
||||
const isAuthorized = await client.isOAuthAuthorized();
|
||||
expect(isAuthorized).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth fetch tracking", () => {
|
||||
let testServer: TestServerHttp;
|
||||
const testRedirectUrl = "http://localhost:3001/oauth/callback";
|
||||
|
||||
beforeEach(() => {
|
||||
clearOAuthTestData();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (testServer) {
|
||||
await testServer.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("should track auth fetches with category 'auth' during guided auth", async () => {
|
||||
const staticClientId = "test-auth-fetch-client";
|
||||
const staticClientSecret = "test-auth-fetch-secret";
|
||||
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: "sse" as const,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: false,
|
||||
supportDCR: true,
|
||||
staticClients: [
|
||||
{
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUris: [testRedirectUrl],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
testServer = new TestServerHttp(serverConfig);
|
||||
const port = await testServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const testClient = new InspectorClient(
|
||||
{
|
||||
type: "sse",
|
||||
url: `${serverUrl}/sse`,
|
||||
} as MCPServerConfig,
|
||||
{
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const fetchRequestLogState = new FetchRequestLogState(testClient);
|
||||
// beginGuidedAuth runs metadata_discovery, client_registration, authorization_redirect
|
||||
// (stops at authorization_code awaiting user). Produces auth fetches only (no connect yet).
|
||||
await testClient.beginGuidedAuth();
|
||||
|
||||
const fetchRequests = fetchRequestLogState.getFetchRequests();
|
||||
const authFetches = fetchRequests.filter(
|
||||
(req) => req.category === "auth",
|
||||
);
|
||||
expect(authFetches.length).toBeGreaterThan(0);
|
||||
const hasOAuthUrls = authFetches.some(
|
||||
(req) =>
|
||||
req.url.includes("well-known") ||
|
||||
req.url.includes("/oauth/") ||
|
||||
req.url.includes("token"),
|
||||
);
|
||||
expect(hasOAuthUrls).toBe(true);
|
||||
|
||||
fetchRequestLogState.destroy();
|
||||
await testClient.disconnect();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth Events", () => {
|
||||
let testServer: TestServerHttp;
|
||||
const testRedirectUrl = "http://localhost:3001/oauth/callback";
|
||||
|
||||
beforeEach(() => {
|
||||
clearOAuthTestData();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (testServer) {
|
||||
await testServer.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("should dispatch oauthAuthorizationRequired event", async () => {
|
||||
const staticClientId = "test-event-client";
|
||||
const staticClientSecret = "test-event-secret";
|
||||
|
||||
// Create test server with OAuth enabled and DCR support (for authenticate() normal mode)
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: "sse" as const,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: false, // Don't require auth for this test
|
||||
supportDCR: true, // Enable DCR so authenticate() can work
|
||||
staticClients: [
|
||||
{
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUris: [testRedirectUrl],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
testServer = new TestServerHttp(serverConfig);
|
||||
const port = await testServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
|
||||
// Create client with OAuth config pointing to test server
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
};
|
||||
|
||||
const testClient = new InspectorClient(
|
||||
{
|
||||
type: "sse",
|
||||
url: `${serverUrl}/sse`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig,
|
||||
);
|
||||
|
||||
testClient.authenticate().catch(() => {});
|
||||
|
||||
const detail = await waitForEvent<{ url: URL }>(
|
||||
testClient,
|
||||
"oauthAuthorizationRequired",
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(detail).toHaveProperty("url");
|
||||
expect(detail.url).toBeInstanceOf(URL);
|
||||
expect(detail.url.href).toContain("/oauth/authorize");
|
||||
await testClient.disconnect();
|
||||
});
|
||||
|
||||
it("should dispatch oauthError event when OAuth flow fails", async () => {
|
||||
// Create a minimal test server just for metadata discovery
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: "sse" as const,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: false,
|
||||
supportDCR: true,
|
||||
}),
|
||||
};
|
||||
|
||||
testServer = new TestServerHttp(serverConfig);
|
||||
const port = await testServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: "test-error-client",
|
||||
clientSecret: "test-error-secret",
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
};
|
||||
|
||||
const testClient = new InspectorClient(
|
||||
{
|
||||
type: "sse",
|
||||
url: `${serverUrl}/sse`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig,
|
||||
);
|
||||
|
||||
testClient.completeOAuthFlow("invalid-test-code").catch(() => {});
|
||||
|
||||
const detail = await waitForEvent<{ error: Error }>(
|
||||
testClient,
|
||||
"oauthError",
|
||||
{
|
||||
timeout: 3000,
|
||||
},
|
||||
);
|
||||
expect(detail).toHaveProperty("error");
|
||||
expect(detail.error).toBeInstanceOf(Error);
|
||||
await testClient.disconnect();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Token Injection in HTTP Transports", () => {
|
||||
let testServer: TestServerHttp;
|
||||
const testRedirectUrl = "http://localhost:3001/oauth/callback";
|
||||
|
||||
beforeEach(() => {
|
||||
clearOAuthTestData();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (testServer) {
|
||||
await testServer.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("should inject Bearer token in HTTP requests when OAuth is configured", async () => {
|
||||
const staticClientId = "test-token-injection-client";
|
||||
const staticClientSecret = "test-token-injection-secret";
|
||||
|
||||
// Create test server with OAuth enabled and auth required
|
||||
const serverConfig = {
|
||||
...getDefaultServerConfig(),
|
||||
serverType: "sse" as const,
|
||||
...createOAuthTestServerConfig({
|
||||
requireAuth: true,
|
||||
supportDCR: true,
|
||||
staticClients: [
|
||||
{
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUris: [testRedirectUrl],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
testServer = new TestServerHttp(serverConfig);
|
||||
const port = await testServer.start();
|
||||
const serverUrl = `http://localhost:${port}`;
|
||||
|
||||
const oauthConfig = createTestOAuthConfig({
|
||||
mode: "static",
|
||||
clientId: staticClientId,
|
||||
clientSecret: staticClientSecret,
|
||||
redirectUrl: testRedirectUrl,
|
||||
});
|
||||
const clientConfig: InspectorClientOptions = {
|
||||
environment: {
|
||||
transport: createTransportNode,
|
||||
oauth: {
|
||||
storage: oauthConfig.storage,
|
||||
navigation: oauthConfig.navigation,
|
||||
redirectUrlProvider: oauthConfig.redirectUrlProvider,
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
clientId: oauthConfig.clientId,
|
||||
clientSecret: oauthConfig.clientSecret,
|
||||
clientMetadataUrl: oauthConfig.clientMetadataUrl,
|
||||
scope: oauthConfig.scope,
|
||||
},
|
||||
};
|
||||
|
||||
const testClient = new InspectorClient(
|
||||
{
|
||||
type: "sse",
|
||||
url: `${serverUrl}/sse`,
|
||||
} as MCPServerConfig,
|
||||
clientConfig,
|
||||
);
|
||||
const fetchRequestLogState = new FetchRequestLogState(testClient);
|
||||
|
||||
// Auth-provider flow: authenticate first, complete OAuth, then connect.
|
||||
// connect() creates transport with authProvider; tokens are already in storage.
|
||||
const authorizationUrl = await testClient.authenticate();
|
||||
const authCode = await completeOAuthAuthorization(authorizationUrl);
|
||||
await testClient.completeOAuthFlow(authCode);
|
||||
|
||||
await testClient.connect();
|
||||
|
||||
const tokens = await testClient.getOAuthTokens();
|
||||
expect(tokens).toBeDefined();
|
||||
expect(tokens?.access_token).toBeDefined();
|
||||
|
||||
// listTools() succeeds only if authProvider injects Bearer token
|
||||
const toolsResult = await testClient.listTools();
|
||||
expect(toolsResult).toBeDefined();
|
||||
|
||||
const fetchRequests = fetchRequestLogState.getFetchRequests();
|
||||
expect(fetchRequests.length).toBeGreaterThan(0);
|
||||
|
||||
// Auth fetches (discovery, token exchange) should have category 'auth'
|
||||
const authFetches = fetchRequests.filter(
|
||||
(req) => req.category === "auth",
|
||||
);
|
||||
expect(authFetches.length).toBeGreaterThan(0);
|
||||
const oauthFetches = authFetches.filter(
|
||||
(req) =>
|
||||
req.url.includes("well-known") ||
|
||||
req.url.includes("/oauth/") ||
|
||||
req.url.includes("/token"),
|
||||
);
|
||||
expect(oauthFetches.length).toBeGreaterThan(0);
|
||||
|
||||
// Transport fetches (SSE, MCP) should have category 'transport'
|
||||
const transportFetches = fetchRequests.filter(
|
||||
(req) => req.category === "transport",
|
||||
);
|
||||
expect(transportFetches.length).toBeGreaterThan(0);
|
||||
|
||||
const mcpPostRequests = transportFetches.filter(
|
||||
(req) =>
|
||||
req.method === "POST" &&
|
||||
(req.url.includes("/sse") || req.url.includes("/mcp")) &&
|
||||
!req.url.includes("/oauth"),
|
||||
);
|
||||
if (mcpPostRequests.length > 0) {
|
||||
const hasAuthHeader = mcpPostRequests.some((req) => {
|
||||
const authHeader =
|
||||
req.requestHeaders?.["Authorization"] ||
|
||||
req.requestHeaders?.["authorization"];
|
||||
return authHeader && authHeader.startsWith("Bearer ");
|
||||
});
|
||||
if (hasAuthHeader) {
|
||||
expect(hasAuthHeader).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
await testClient.disconnect();
|
||||
});
|
||||
});
|
||||
});
|
||||
4606
clients/web/src/test/integration/mcp/inspectorClient.test.ts
Normal file
4606
clients/web/src/test/integration/mcp/inspectorClient.test.ts
Normal file
File diff suppressed because it is too large
Load diff
195
clients/web/src/test/integration/mcp/node/transport.test.ts
Normal file
195
clients/web/src/test/integration/mcp/node/transport.test.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { getServerType } from "@inspector/core/mcp/config.js";
|
||||
import { createTransportNode } from "@inspector/core/mcp/node/transport.js";
|
||||
import type {
|
||||
MCPServerConfig,
|
||||
FetchRequestEntryBase,
|
||||
} from "@inspector/core/mcp/types.js";
|
||||
import {
|
||||
createTestServerHttp,
|
||||
createEchoTool,
|
||||
createTestServerInfo,
|
||||
} from "@modelcontextprotocol/inspector-test-server";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
describe("Transport", () => {
|
||||
describe("getServerType", () => {
|
||||
it("should return stdio for stdio config", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "stdio",
|
||||
command: "echo",
|
||||
args: ["hello"],
|
||||
};
|
||||
expect(getServerType(config)).toBe("stdio");
|
||||
});
|
||||
|
||||
it("should return sse for sse config", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "sse",
|
||||
url: "http://localhost:3000/sse",
|
||||
};
|
||||
expect(getServerType(config)).toBe("sse");
|
||||
});
|
||||
|
||||
it("should return streamable-http for streamable-http config", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "streamable-http",
|
||||
url: "http://localhost:3000/mcp",
|
||||
};
|
||||
expect(getServerType(config)).toBe("streamable-http");
|
||||
});
|
||||
|
||||
it("should default to stdio when type is not present", () => {
|
||||
const config: MCPServerConfig = {
|
||||
command: "echo",
|
||||
args: ["hello"],
|
||||
};
|
||||
expect(getServerType(config)).toBe("stdio");
|
||||
});
|
||||
|
||||
it("should throw error for invalid type", () => {
|
||||
const config = {
|
||||
type: "invalid",
|
||||
command: "echo",
|
||||
} as unknown as MCPServerConfig;
|
||||
expect(() => getServerType(config)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTransport", () => {
|
||||
it("should create stdio transport", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "stdio",
|
||||
command: "echo",
|
||||
args: ["hello"],
|
||||
};
|
||||
const result = createTransportNode(config);
|
||||
expect(result.transport).toBeDefined();
|
||||
});
|
||||
|
||||
it("should create SSE transport", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "sse",
|
||||
url: "http://localhost:3000/sse",
|
||||
};
|
||||
const result = createTransportNode(config);
|
||||
expect(result.transport).toBeDefined();
|
||||
});
|
||||
|
||||
it("should create streamable-http transport", () => {
|
||||
const config: MCPServerConfig = {
|
||||
type: "streamable-http",
|
||||
url: "http://localhost:3000/mcp",
|
||||
};
|
||||
const result = createTransportNode(config);
|
||||
expect(result.transport).toBeDefined();
|
||||
});
|
||||
|
||||
it("should call onFetchRequest callback for SSE transport", async () => {
|
||||
const server = createTestServerHttp({
|
||||
serverInfo: createTestServerInfo(),
|
||||
tools: [createEchoTool()],
|
||||
serverType: "sse",
|
||||
});
|
||||
|
||||
try {
|
||||
await server.start();
|
||||
|
||||
const config: MCPServerConfig = {
|
||||
type: "sse",
|
||||
url: server.url,
|
||||
};
|
||||
|
||||
const fetchRequests: FetchRequestEntryBase[] = [];
|
||||
const result = createTransportNode(config, {
|
||||
onFetchRequest: (entry) => {
|
||||
fetchRequests.push(entry);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.transport).toBeDefined();
|
||||
|
||||
// Actually connect and make a request to verify fetch tracking works
|
||||
const client = new Client(
|
||||
{
|
||||
name: "test-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{
|
||||
capabilities: {},
|
||||
},
|
||||
);
|
||||
|
||||
await client.connect(result.transport);
|
||||
await client.listTools();
|
||||
await client.close();
|
||||
|
||||
// Verify fetch requests were tracked
|
||||
expect(fetchRequests.length).toBeGreaterThan(0);
|
||||
// SSE uses GET for the initial connection
|
||||
const getRequest = fetchRequests.find((r) => r.method === "GET");
|
||||
expect(getRequest).toBeDefined();
|
||||
if (getRequest) {
|
||||
expect(getRequest.url).toContain("/sse");
|
||||
expect(getRequest.requestHeaders).toBeDefined();
|
||||
}
|
||||
} finally {
|
||||
await server.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("should call onFetchRequest callback for streamable-http transport", async () => {
|
||||
const server = createTestServerHttp({
|
||||
serverInfo: createTestServerInfo(),
|
||||
tools: [createEchoTool()],
|
||||
serverType: "streamable-http",
|
||||
});
|
||||
|
||||
try {
|
||||
await server.start();
|
||||
|
||||
const config: MCPServerConfig = {
|
||||
type: "streamable-http",
|
||||
url: server.url,
|
||||
};
|
||||
|
||||
const fetchRequests: FetchRequestEntryBase[] = [];
|
||||
const result = createTransportNode(config, {
|
||||
onFetchRequest: (entry) => {
|
||||
fetchRequests.push(entry);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.transport).toBeDefined();
|
||||
|
||||
// Actually connect and make a request to verify fetch tracking works
|
||||
const client = new Client(
|
||||
{
|
||||
name: "test-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{
|
||||
capabilities: {},
|
||||
},
|
||||
);
|
||||
|
||||
await client.connect(result.transport);
|
||||
await client.listTools();
|
||||
await client.close();
|
||||
|
||||
// Verify fetch requests were tracked
|
||||
expect(fetchRequests.length).toBeGreaterThan(0);
|
||||
const request = fetchRequests[0];
|
||||
expect(request).toBeDefined();
|
||||
expect(request.url).toContain("/mcp");
|
||||
expect(request.method).toBe("POST");
|
||||
expect(request.requestHeaders).toBeDefined();
|
||||
expect(request.responseStatus).toBeDefined();
|
||||
expect(request.responseHeaders).toBeDefined();
|
||||
expect(request.duration).toBeDefined();
|
||||
} finally {
|
||||
await server.stop();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { createRemoteApp } from "@inspector/core/mcp/remote/node/server.js";
|
||||
|
||||
describe("createRemoteApp GET /api/config", () => {
|
||||
it("includes sandboxUrl in response when option is set", async () => {
|
||||
const sandboxUrl = "http://localhost:9123/sandbox";
|
||||
const { app } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
allowedOrigins: ["http://127.0.0.1:6274"],
|
||||
sandboxUrl,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
});
|
||||
const res = await app.request(new Request("http://test/api/config"));
|
||||
expect(res.status).toBe(200);
|
||||
const data = (await res.json()) as { sandboxUrl?: string };
|
||||
expect(data.sandboxUrl).toBe(sandboxUrl);
|
||||
});
|
||||
|
||||
it("omits sandboxUrl when option is not set", async () => {
|
||||
const { app } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
allowedOrigins: ["http://127.0.0.1:6274"],
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
});
|
||||
const res = await app.request(new Request("http://test/api/config"));
|
||||
expect(res.status).toBe(200);
|
||||
const data = (await res.json()) as { sandboxUrl?: string };
|
||||
expect(data).not.toHaveProperty("sandboxUrl");
|
||||
});
|
||||
|
||||
it("uses initialConfig when provided instead of env", async () => {
|
||||
const { app } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
allowedOrigins: ["http://127.0.0.1:6274"],
|
||||
initialConfig: {
|
||||
defaultCommand: "my-server",
|
||||
defaultArgs: ["--foo"],
|
||||
defaultTransport: "stdio",
|
||||
defaultCwd: "/tmp",
|
||||
defaultEnvironment: { PATH: "/usr/bin" },
|
||||
},
|
||||
});
|
||||
const res = await app.request(new Request("http://test/api/config"));
|
||||
expect(res.status).toBe(200);
|
||||
const data = (await res.json()) as {
|
||||
defaultCommand?: string;
|
||||
defaultArgs?: string[];
|
||||
defaultTransport?: string;
|
||||
defaultCwd?: string;
|
||||
defaultEnvironment?: Record<string, string>;
|
||||
};
|
||||
expect(data.defaultCommand).toBe("my-server");
|
||||
expect(data.defaultArgs).toEqual(["--foo"]);
|
||||
expect(data.defaultTransport).toBe("stdio");
|
||||
expect(data.defaultCwd).toBe("/tmp");
|
||||
expect(data.defaultEnvironment).toEqual({ PATH: "/usr/bin" });
|
||||
});
|
||||
});
|
||||
1507
clients/web/src/test/integration/mcp/remote/transport.test.ts
Normal file
1507
clients/web/src/test/integration/mcp/remote/transport.test.ts
Normal file
File diff suppressed because it is too large
Load diff
417
clients/web/src/test/integration/storage/adapters.test.ts
Normal file
417
clients/web/src/test/integration/storage/adapters.test.ts
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
/**
|
||||
* Tests for storage adapters (file, remote).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, afterEach, vi } from "vitest";
|
||||
import { waitForRemoteStore } from "@modelcontextprotocol/inspector-test-server";
|
||||
import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { serve } from "@hono/node-server";
|
||||
import type { ServerType } from "@hono/node-server";
|
||||
import { createFileStorageAdapter } from "@inspector/core/storage/adapters/file-storage.js";
|
||||
import { createRemoteStorageAdapter } from "@inspector/core/storage/adapters/remote-storage.js";
|
||||
import { createOAuthStore } from "@inspector/core/auth/store.js";
|
||||
import { createRemoteApp } from "@inspector/core/mcp/remote/node/server.js";
|
||||
|
||||
interface StartRemoteServerOptions {
|
||||
storageDir?: string;
|
||||
}
|
||||
|
||||
async function startRemoteServer(
|
||||
port: number,
|
||||
options: StartRemoteServerOptions = {},
|
||||
): Promise<{
|
||||
baseUrl: string;
|
||||
server: ServerType;
|
||||
authToken: string;
|
||||
}> {
|
||||
const { app, authToken } = createRemoteApp({
|
||||
storageDir: options.storageDir,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = serve(
|
||||
{ fetch: app.fetch, port, hostname: "127.0.0.1" },
|
||||
(info) => {
|
||||
const actualPort =
|
||||
info && typeof info === "object" && "port" in info
|
||||
? (info as { port: number }).port
|
||||
: port;
|
||||
resolve({
|
||||
baseUrl: `http://127.0.0.1:${actualPort}`,
|
||||
server,
|
||||
authToken,
|
||||
});
|
||||
},
|
||||
);
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
describe("Storage adapters", () => {
|
||||
describe("createRemoteStorageAdapter (unit, mocked fetch)", () => {
|
||||
function makeAdapter(fetchFn: typeof fetch, authToken?: string) {
|
||||
return createRemoteStorageAdapter({
|
||||
baseUrl: "http://remote.example/",
|
||||
storeId: "test",
|
||||
fetchFn,
|
||||
authToken,
|
||||
})!;
|
||||
}
|
||||
|
||||
it("getItem returns null on 404 and parses stored blob otherwise", async () => {
|
||||
const fetchFn = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("not found", { status: 404 }))
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ state: { hi: 1 }, version: 0 })),
|
||||
)
|
||||
.mockResolvedValueOnce(new Response("{}"));
|
||||
|
||||
const adapter = makeAdapter(fetchFn as typeof fetch);
|
||||
expect(await adapter.getItem("anything")).toBeNull();
|
||||
const blob = await adapter.getItem("anything");
|
||||
expect(blob).toBeTruthy();
|
||||
// Empty object response → treated as "not initialized" → null.
|
||||
expect(await adapter.getItem("anything")).toBeNull();
|
||||
});
|
||||
|
||||
it("getItem throws on non-404 error responses", async () => {
|
||||
const fetchFn = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("boom", { status: 500 }));
|
||||
const adapter = makeAdapter(fetchFn as typeof fetch);
|
||||
await expect(adapter.getItem("x")).rejects.toThrow(/500/);
|
||||
});
|
||||
|
||||
it("setItem throws when the POST fails", async () => {
|
||||
const fetchFn = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("nope", { status: 500 }));
|
||||
const adapter = makeAdapter(fetchFn as typeof fetch);
|
||||
await expect(
|
||||
adapter.setItem("name", { state: { a: 1 }, version: 0 }),
|
||||
).rejects.toThrow(/500/);
|
||||
});
|
||||
|
||||
it("removeItem tolerates 404 but rethrows on other failures", async () => {
|
||||
const fetchFn = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response("boom", { status: 500 }));
|
||||
const adapter = makeAdapter(fetchFn as typeof fetch);
|
||||
await expect(adapter.removeItem("x")).resolves.toBeUndefined();
|
||||
await expect(adapter.removeItem("x")).resolves.toBeUndefined();
|
||||
await expect(adapter.removeItem("x")).rejects.toThrow(/500/);
|
||||
});
|
||||
|
||||
it("sends the x-mcp-remote-auth header on all three verbs when authToken is set", async () => {
|
||||
const fetchFn = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValue(new Response("{}"));
|
||||
const adapter = makeAdapter(fetchFn as typeof fetch, "secret");
|
||||
await adapter.getItem("x");
|
||||
await adapter.setItem("x", { state: {}, version: 0 });
|
||||
await adapter.removeItem("x");
|
||||
for (const call of fetchFn.mock.calls) {
|
||||
const headers = call[1]?.headers as Record<string, string> | undefined;
|
||||
expect(headers?.["x-mcp-remote-auth"]).toBe("Bearer secret");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("FileStorageAdapter", () => {
|
||||
let tempDir: string | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
if (tempDir) {
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
tempDir = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("creates store and persists state", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const filePath = join(tempDir!, "test-store.json");
|
||||
const storage = createFileStorageAdapter({ filePath });
|
||||
const store = createOAuthStore(storage);
|
||||
|
||||
// Set some state
|
||||
store.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "test-token", token_type: "Bearer" },
|
||||
});
|
||||
|
||||
// Wait for persistence (Zustand persist is async; poll for file so we don't race with cleanup)
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(existsSync(filePath)).toBe(true);
|
||||
},
|
||||
{ timeout: 2000, interval: 20 },
|
||||
);
|
||||
const fileContent = readFileSync(filePath, "utf-8");
|
||||
const parsed = JSON.parse(fileContent);
|
||||
expect(parsed.state.servers["https://example.com"].tokens).toEqual({
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
});
|
||||
|
||||
it("loads persisted state on initialization", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const filePath = join(tempDir!, "test-store.json");
|
||||
|
||||
// Create initial store and persist
|
||||
const storage1 = createFileStorageAdapter({ filePath });
|
||||
const store1 = createOAuthStore(storage1);
|
||||
store1.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "initial-token", token_type: "Bearer" },
|
||||
});
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(existsSync(filePath)).toBe(true);
|
||||
},
|
||||
{ timeout: 2000, interval: 20 },
|
||||
);
|
||||
|
||||
// Create new store instance (should load persisted state)
|
||||
const storage2 = createFileStorageAdapter({ filePath });
|
||||
const store2 = createOAuthStore(storage2);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const state = store2.getState().getServerState("https://example.com");
|
||||
expect(state.tokens).toEqual({
|
||||
access_token: "initial-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
});
|
||||
|
||||
it("handles empty state after clear", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const filePath = join(tempDir!, "test-store.json");
|
||||
const storage = createFileStorageAdapter({ filePath });
|
||||
const store = createOAuthStore(storage);
|
||||
|
||||
// Set state and persist
|
||||
store.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "test-token", token_type: "Bearer" },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
expect(existsSync(filePath)).toBe(true);
|
||||
|
||||
// Clear all servers (this will persist empty state)
|
||||
const state = store.getState();
|
||||
const urls = Object.keys(state.servers);
|
||||
for (const url of urls) {
|
||||
state.clearServerState(url);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Verify file still exists but with empty servers
|
||||
expect(existsSync(filePath)).toBe(true);
|
||||
const fileContent = readFileSync(filePath, "utf-8");
|
||||
const parsed = JSON.parse(fileContent);
|
||||
expect(Object.keys(parsed.state.servers).length).toBe(0);
|
||||
});
|
||||
|
||||
it("removeItem deletes the underlying file", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const filePath = join(tempDir!, "test-store.json");
|
||||
const storage = createFileStorageAdapter({ filePath });
|
||||
// createJSONStorage returns a PersistStorage<S> wrapper that delegates to
|
||||
// our adapter's removeItem callback (line 25 of file-storage.ts).
|
||||
const store = createOAuthStore(storage);
|
||||
store.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "t", token_type: "Bearer" },
|
||||
});
|
||||
await vi.waitFor(() => expect(existsSync(filePath)).toBe(true), {
|
||||
timeout: 2000,
|
||||
interval: 20,
|
||||
});
|
||||
await storage!.removeItem("inspector-oauth-store");
|
||||
expect(existsSync(filePath)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RemoteStorageAdapter", () => {
|
||||
let remoteServer: ServerType | null = null;
|
||||
let tempDir: string | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (remoteServer) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
remoteServer!.close((err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
remoteServer = null;
|
||||
}
|
||||
if (tempDir) {
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
tempDir = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("creates store and persists state via HTTP", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const { baseUrl, server, authToken } = await startRemoteServer(0, {
|
||||
storageDir: tempDir,
|
||||
});
|
||||
remoteServer = server;
|
||||
|
||||
const storage = createRemoteStorageAdapter({
|
||||
baseUrl,
|
||||
storeId: "test-store",
|
||||
authToken,
|
||||
});
|
||||
const store = createOAuthStore(storage);
|
||||
|
||||
// Set some state
|
||||
store.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "test-token", token_type: "Bearer" },
|
||||
});
|
||||
|
||||
await waitForRemoteStore(baseUrl, "test-store", authToken, (body) => {
|
||||
const d = body as {
|
||||
state?: {
|
||||
servers?: Record<string, { tokens?: { access_token?: string } }>;
|
||||
};
|
||||
};
|
||||
return (
|
||||
d?.state?.servers?.["https://example.com"]?.tokens?.access_token ===
|
||||
"test-token"
|
||||
);
|
||||
});
|
||||
|
||||
// Verify via API
|
||||
const res = await fetch(`${baseUrl}/api/storage/test-store`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"x-mcp-remote-auth": `Bearer ${authToken}`,
|
||||
},
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const storeData = await res.json();
|
||||
expect(storeData.state.servers["https://example.com"].tokens).toEqual({
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
});
|
||||
|
||||
it("loads persisted state on initialization", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const { baseUrl, server, authToken } = await startRemoteServer(0, {
|
||||
storageDir: tempDir,
|
||||
});
|
||||
remoteServer = server;
|
||||
|
||||
// Create initial store and persist
|
||||
const storage1 = createRemoteStorageAdapter({
|
||||
baseUrl,
|
||||
storeId: "test-store",
|
||||
authToken,
|
||||
});
|
||||
const store1 = createOAuthStore(storage1);
|
||||
store1.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "initial-token", token_type: "Bearer" },
|
||||
});
|
||||
await waitForRemoteStore(baseUrl, "test-store", authToken, (body) => {
|
||||
const d = body as {
|
||||
state?: {
|
||||
servers?: Record<string, { tokens?: { access_token?: string } }>;
|
||||
};
|
||||
};
|
||||
return (
|
||||
d?.state?.servers?.["https://example.com"]?.tokens?.access_token ===
|
||||
"initial-token"
|
||||
);
|
||||
});
|
||||
|
||||
// Create new store instance (should load persisted state)
|
||||
const storage2 = createRemoteStorageAdapter({
|
||||
baseUrl,
|
||||
storeId: "test-store",
|
||||
authToken,
|
||||
});
|
||||
const store2 = createOAuthStore(storage2);
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const state = store2.getState().getServerState("https://example.com");
|
||||
if (!state.tokens) throw new Error("Store not yet hydrated");
|
||||
return state;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
|
||||
const state = store2.getState().getServerState("https://example.com");
|
||||
expect(state.tokens).toEqual({
|
||||
access_token: "initial-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
});
|
||||
|
||||
it("handles empty state after clear", async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-"));
|
||||
const { baseUrl, server, authToken } = await startRemoteServer(0, {
|
||||
storageDir: tempDir,
|
||||
});
|
||||
remoteServer = server;
|
||||
|
||||
const storage = createRemoteStorageAdapter({
|
||||
baseUrl,
|
||||
storeId: "test-store",
|
||||
authToken,
|
||||
});
|
||||
const store = createOAuthStore(storage);
|
||||
|
||||
// Set state and persist
|
||||
store.getState().setServerState("https://example.com", {
|
||||
tokens: { access_token: "test-token", token_type: "Bearer" },
|
||||
});
|
||||
await waitForRemoteStore(baseUrl, "test-store", authToken, (body) => {
|
||||
const d = body as { state?: { servers?: Record<string, unknown> } };
|
||||
return !!d?.state?.servers && Object.keys(d.state.servers).length > 0;
|
||||
});
|
||||
|
||||
// Verify it exists
|
||||
let res = await fetch(`${baseUrl}/api/storage/test-store`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"x-mcp-remote-auth": `Bearer ${authToken}`,
|
||||
},
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const storeData = await res.json();
|
||||
expect(Object.keys(storeData.state.servers).length).toBeGreaterThan(0);
|
||||
|
||||
// Clear all servers (this will persist empty state)
|
||||
const state = store.getState();
|
||||
const urls = Object.keys(state.servers);
|
||||
for (const url of urls) {
|
||||
state.clearServerState(url);
|
||||
}
|
||||
await waitForRemoteStore(baseUrl, "test-store", authToken, (body) => {
|
||||
const d = body as { state?: { servers?: Record<string, unknown> } };
|
||||
return !d?.state?.servers || Object.keys(d.state.servers).length === 0;
|
||||
});
|
||||
|
||||
// Verify it's empty
|
||||
res = await fetch(`${baseUrl}/api/storage/test-store`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"x-mcp-remote-auth": `Bearer ${authToken}`,
|
||||
},
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const emptyStore = await res.json();
|
||||
expect(Object.keys(emptyStore.state.servers).length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -70,26 +70,17 @@ const projectResolve = {
|
|||
dedupe: sharedDedupe,
|
||||
};
|
||||
|
||||
// v1.5-ported integration tests that need a node-env vitest project — they
|
||||
// spawn real HTTP/stdio servers via test-servers/, run end-to-end OAuth flows,
|
||||
// talk to fs/network, or mock `@modelcontextprotocol/sdk/client/auth.js` (the
|
||||
// SDK auth mock identity is lost under happy-dom + Vitest 4, but works under
|
||||
// node env). Tracked in #1307.
|
||||
const integrationTests = [
|
||||
'clients/web/src/test/core/inspectorClient.test.ts',
|
||||
'clients/web/src/test/core/inspectorClient-oauth.test.ts',
|
||||
'clients/web/src/test/core/inspectorClient-oauth-e2e.test.ts',
|
||||
'clients/web/src/test/core/inspectorClient-oauth-fetchFn.test.ts',
|
||||
'clients/web/src/test/core/inspectorClient-oauth-remote-storage-e2e.test.ts',
|
||||
'clients/web/src/test/core/transport.test.ts',
|
||||
'clients/web/src/test/core/remote-transport.test.ts',
|
||||
'clients/web/src/test/core/remote-server-config.test.ts',
|
||||
'clients/web/src/test/core/storage-adapters.test.ts',
|
||||
'clients/web/src/test/core/auth/storage-node.test.ts',
|
||||
'clients/web/src/test/core/auth/oauth-callback-server.test.ts',
|
||||
'clients/web/src/test/core/auth/discovery.test.ts',
|
||||
'clients/web/src/test/core/auth/state-machine.test.ts',
|
||||
];
|
||||
// Integration tests live under clients/web/src/test/integration/ and run in
|
||||
// the node-env vitest project below. The folder is the manifest: anything
|
||||
// inside it is integration (node env, 30s timeout, real servers); anything
|
||||
// outside is a unit test (happy-dom). This prevents the silent
|
||||
// misclassification trap where a file's environment depended on whether
|
||||
// someone remembered to add it to an enumeration (#1314).
|
||||
//
|
||||
// Match `{ts,tsx}` to mirror the unit project's include below — otherwise a
|
||||
// stray `.test.tsx` placed inside this folder would slip past the integration
|
||||
// include AND fail to be excluded from unit, silently landing under happy-dom.
|
||||
const integrationGlob = 'clients/web/src/test/integration/**/*.test.{ts,tsx}';
|
||||
|
||||
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
|
||||
export default defineConfig({
|
||||
|
|
@ -182,7 +173,7 @@ export default defineConfig({
|
|||
// global lifecycle hooks; cleanup is invoked manually in setup.ts.
|
||||
include: ['clients/web/src/**/*.test.{ts,tsx}'],
|
||||
// Integration tests run in the integration project below (node env).
|
||||
exclude: integrationTests,
|
||||
exclude: [integrationGlob],
|
||||
setupFiles: [path.join(dirname, 'src/test/setup.ts')],
|
||||
},
|
||||
},
|
||||
|
|
@ -199,7 +190,7 @@ export default defineConfig({
|
|||
// Same reason as the unit project: rooted at repoRoot so vitest
|
||||
// can transform core/ modules and run tests against the source.
|
||||
root: repoRoot,
|
||||
include: integrationTests,
|
||||
include: [integrationGlob],
|
||||
// Integration tests spawn real HTTP/stdio servers via test-servers/,
|
||||
// bind sockets, run e2e OAuth flows, and exercise filesystem-backed
|
||||
// storage. 30s matches the v1.5 core/vitest.config.ts.
|
||||
|
|
|
|||
Loading…
Reference in a new issue