test: switch integration project to folder-based manifest (#1314) (#1318)

* 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:
Cliff Hall 2026-05-18 11:54:49 -04:00 • committed by GitHub
commit 8bb389c8e3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 18 additions and 27 deletions

File diff suppressed because it is too large Load diff

View file

@ -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),
}),
);
});
});

View file

@ -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");
});
},
);
});

View file

@ -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();
});
});
});

File diff suppressed because it is too large Load diff

View 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();
}
});
});
});

View file

@ -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" });
});
});

File diff suppressed because it is too large Load diff