Some checks failed
Run install, format, lint, build, and test on every push / build (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish-github-container-registry (push) Has been cancelled
* OAuth: re-key store to (server, issuer) + SEP-837/2350/2352 auth UX (#1625) Re-key the persisted OAuth store to (server, issuer) and add the SEP-837/2350/2352 authorization-hardening UX. The SDK v2 auth() drives the SEP-2352 flow off the provider's ctx.issuer; the Inspector's job is to honor it and round-trip the issuer stamp. SEP-2352 — issuer-bound credentials - ServerOAuthState nests issuer-bound credentials under byIssuer[issuer] = { clientInformation, clientRegistrationKind, tokens }, with an activeIssuer pointer answering the transport's ctx-less per-request bearer read. - Fix a latent bug: OAuthStorageBase re-parsed tokens/client-info through OAuthTokensSchema/OAuthClientInformationSchema, which strip the non-RFC `issuer` field and silently defeat the SDK's discardIfIssuerMismatch. The store re-attaches the stamp from the byIssuer key. - BaseOAuthClientProvider threads ctx.issuer and implements discoveryState()/saveDiscoveryState() (activates the SDK's callback-leg AuthorizationServerMismatchError binding check) and invalidateCredentials(). - Lazy, migration-free upgrade: a legacy pre-1625 blob's top-level clientInformation/tokens are returned as an unkeyed fallback until the first issuer-stamped save promotes them into byIssuer. SEP-837 — application_type - DCR declares application_type: "native" (localhost Inspector). - ClientSettingsForm renders RegistrationRejectedError detail and reflects DCR's deprecated-in-favor-of-CIMD (SEP-991) status. SEP-2350 — step-up scope union - Per-server onInsufficientScope (reauthorize | throw) setting wired ServerSettingsForm -> StoredMCPServer.oauth -> StreamableHTTPClientTransport. - StepUpAuthModal visualizes the prior-union-challenged scope set, tagging each scope `new` vs `already granted`. mcpAuth simplification - Delete the hand-rolled authorizeWithoutRefresh (mishandled issuer stamping); forward forceReauthorization/skipIssuerMetadataValidation to native SDK auth() so both the initial and step-up paths get SEP-2352 stamping. Vocabulary + docs - OAuthStep gains cimd_fetch / issuer_comparison / scope_step_up (recorded on a step-up redirect); the Network tab labels auth requests by OAuth phase. - v2_auth_hardening.md gains an as-built status section. Deferred to the era-aware card: the SdkError(EraNegotiationFailed) -> UnauthorizedError unwrap and finishAuth(URLSearchParams) form (only fire under non-legacy negotiation). Closes #1625 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Address @claude review: issuer-stamp source gating + clear/activeIssuer + phase over-match - SEP-2352: stamp the issuer only when the credential actually came from the byIssuer slot (`fromSlot`), not merely when a slot exists. A partially-populated slot alongside a surviving legacy field would otherwise stamp a legacy (possibly cross-AS) credential with the current issuer, defeating discardIfIssuerMismatch. - Issuer-scoped clears no longer promote the cleared issuer to `activeIssuer` (updateIssuerSlot gains a `setActive` flag; save paths keep the promotion). - oauthNetworkPhase matches register/token/authorize as the final path segment (trailing slash tolerated) so `/token/refresh` or `/api/register/foo` no longer over-match. - Tests for all three. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
223 lines
7.3 KiB
TypeScript
223 lines
7.3 KiB
TypeScript
import { getServerType } from "../config.js";
|
|
import type {
|
|
MCPServerConfig,
|
|
StdioServerConfig,
|
|
SseServerConfig,
|
|
StreamableHttpServerConfig,
|
|
CreateTransportOptions,
|
|
CreateTransportResult,
|
|
InspectorServerSettings,
|
|
} from "../types.js";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { SSEClientTransport } from "@modelcontextprotocol/client";
|
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
import { createFetchTracker } from "../fetchTracking.js";
|
|
import { createAuthChallengeInterceptFetch } from "./authChallengeFetch.js";
|
|
import type { Dispatcher } from "undici";
|
|
|
|
/** Node's `RequestInit` plus the undici-specific `dispatcher` option. */
|
|
type NodeRequestInit = RequestInit & { dispatcher?: Dispatcher };
|
|
|
|
/** Standard proxy env vars, in the precedence undici's EnvHttpProxyAgent uses. */
|
|
const PROXY_ENV_VARS = [
|
|
"HTTPS_PROXY",
|
|
"https_proxy",
|
|
"HTTP_PROXY",
|
|
"http_proxy",
|
|
] as const;
|
|
|
|
/**
|
|
* First proxy URL found in the environment, or `undefined` if none is set.
|
|
* Exported for tests and so callers can decide whether proxying is in effect.
|
|
*/
|
|
export function readProxyEnv(): string | undefined {
|
|
for (const name of PROXY_ENV_VARS) {
|
|
const value = process.env[name];
|
|
if (value && value.trim() !== "") return value;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Wraps a fetch function so outbound HTTP/HTTPS requests honor the standard
|
|
* `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` environment variables.
|
|
*
|
|
* Node's built-in `fetch` (the bundled undici) accepts a `dispatcher` option
|
|
* in `RequestInit`; undici's `EnvHttpProxyAgent` reads the proxy env vars and
|
|
* routes per-request, so a single dispatcher covers both schemes and respects
|
|
* `NO_PROXY`. The `undici` package is loaded lazily on first call so callers
|
|
* that never set a proxy env var (TUI, web backend) need no extra dependency.
|
|
* If the proxy is configured but `undici` is unavailable, the wrapper throws
|
|
* with an actionable message rather than silently ignoring the env var.
|
|
*/
|
|
export function withProxyDispatcher(baseFetch: typeof fetch): typeof fetch {
|
|
if (readProxyEnv() === undefined) return baseFetch;
|
|
|
|
let dispatcherPromise: Promise<Dispatcher> | undefined;
|
|
const getDispatcher = (): Promise<Dispatcher> => {
|
|
dispatcherPromise ??= import("undici").then(
|
|
({ EnvHttpProxyAgent }) => new EnvHttpProxyAgent(),
|
|
(cause: unknown) => {
|
|
throw new Error(
|
|
"HTTPS_PROXY / HTTP_PROXY is set but the `undici` package is not " +
|
|
"available. Install it (it ships with the CLI client) or unset the " +
|
|
"proxy env var.",
|
|
{ cause },
|
|
);
|
|
},
|
|
);
|
|
return dispatcherPromise;
|
|
};
|
|
|
|
const proxiedFetch: typeof fetch = async (input, init) => {
|
|
const dispatcher = await getDispatcher();
|
|
return baseFetch(input, { ...init, dispatcher } as NodeRequestInit);
|
|
};
|
|
return proxiedFetch;
|
|
}
|
|
|
|
/**
|
|
* Build the wire `headers` record from `settings.headers`, dropping rows with
|
|
* empty keys (the form lets users leave new rows blank). Returns `undefined`
|
|
* when the result is empty so we can omit the field instead of sending `{}`.
|
|
*/
|
|
function headersFromSettings(
|
|
settings: InspectorServerSettings | undefined,
|
|
): Record<string, string> | undefined {
|
|
if (!settings || settings.headers.length === 0) return undefined;
|
|
const out: Record<string, string> = {};
|
|
for (const { key, value } of settings.headers) {
|
|
if (key.trim() === "") continue;
|
|
out[key] = value;
|
|
}
|
|
return Object.keys(out).length > 0 ? out : undefined;
|
|
}
|
|
|
|
/**
|
|
* Creates the appropriate transport for an MCP server configuration.
|
|
*/
|
|
export function createTransportNode(
|
|
config: MCPServerConfig,
|
|
options: CreateTransportOptions = {},
|
|
): CreateTransportResult {
|
|
const serverType = getServerType(config);
|
|
const {
|
|
fetchFn: optionsFetchFn,
|
|
onStderr,
|
|
pipeStderr = false,
|
|
onFetchRequest,
|
|
onFetchResponseBody,
|
|
authProvider,
|
|
settings,
|
|
interceptAuthChallenges = false,
|
|
} = options;
|
|
|
|
// Proxy-wrap first so the auth-challenge interceptor observes responses from
|
|
// the (optionally proxied) network call.
|
|
const baseFetch = withProxyDispatcher(optionsFetchFn ?? globalThis.fetch);
|
|
const fetchWithOptionalAuthIntercept = interceptAuthChallenges
|
|
? createAuthChallengeInterceptFetch(baseFetch)
|
|
: baseFetch;
|
|
|
|
if (serverType === "stdio") {
|
|
const stdioConfig = config as StdioServerConfig;
|
|
const transport = new StdioClientTransport({
|
|
command: stdioConfig.command,
|
|
args: stdioConfig.args || [],
|
|
env: stdioConfig.env,
|
|
cwd: stdioConfig.cwd,
|
|
stderr: pipeStderr ? "pipe" : undefined,
|
|
});
|
|
|
|
// Set up stderr listener if requested
|
|
if (pipeStderr && transport.stderr && onStderr) {
|
|
transport.stderr.on("data", (data: Buffer) => {
|
|
const logEntry = data.toString().trim();
|
|
if (logEntry) {
|
|
onStderr({
|
|
timestamp: new Date(),
|
|
message: logEntry,
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
return { transport: transport };
|
|
} else if (serverType === "sse") {
|
|
const sseConfig = config as SseServerConfig;
|
|
const url = new URL(sseConfig.url);
|
|
|
|
// A caller-supplied eventSourceInit.fetch wins as-is (explicit fetch is not
|
|
// re-wrapped for proxying); the default path uses fetchWithOptionalAuthIntercept
|
|
// (the proxy-aware baseFetch plus the optional auth-challenge intercept).
|
|
const sseFetch =
|
|
(sseConfig.eventSourceInit?.fetch as typeof fetch) ||
|
|
fetchWithOptionalAuthIntercept;
|
|
const trackedFetch = onFetchRequest
|
|
? createFetchTracker(sseFetch, {
|
|
trackRequest: onFetchRequest,
|
|
updateResponseBody: onFetchResponseBody,
|
|
})
|
|
: sseFetch;
|
|
|
|
const headers = headersFromSettings(settings);
|
|
|
|
const eventSourceInit: Record<string, unknown> = {
|
|
...sseConfig.eventSourceInit,
|
|
...(headers && { headers }),
|
|
fetch: trackedFetch,
|
|
};
|
|
|
|
const requestInit: RequestInit = {
|
|
...sseConfig.requestInit,
|
|
...(headers && { headers }),
|
|
};
|
|
|
|
const postFetch = onFetchRequest
|
|
? createFetchTracker(fetchWithOptionalAuthIntercept, {
|
|
trackRequest: onFetchRequest,
|
|
updateResponseBody: onFetchResponseBody,
|
|
})
|
|
: fetchWithOptionalAuthIntercept;
|
|
|
|
const transport = new SSEClientTransport(url, {
|
|
authProvider,
|
|
eventSourceInit,
|
|
requestInit,
|
|
fetch: postFetch,
|
|
});
|
|
|
|
return { transport };
|
|
} else {
|
|
// streamable-http
|
|
const httpConfig = config as StreamableHttpServerConfig;
|
|
const url = new URL(httpConfig.url);
|
|
|
|
const headers = headersFromSettings(settings);
|
|
|
|
const requestInit: RequestInit = {
|
|
...httpConfig.requestInit,
|
|
...(headers && { headers }),
|
|
};
|
|
|
|
const transportFetch = onFetchRequest
|
|
? createFetchTracker(fetchWithOptionalAuthIntercept, {
|
|
trackRequest: onFetchRequest,
|
|
updateResponseBody: onFetchResponseBody,
|
|
})
|
|
: fetchWithOptionalAuthIntercept;
|
|
|
|
const transport = new StreamableHTTPClientTransport(url, {
|
|
authProvider,
|
|
requestInit,
|
|
fetch: transportFetch,
|
|
// SEP-2350: how the transport reacts to a `403 insufficient_scope`
|
|
// challenge. Defaults to the SDK's `reauthorize` when unset.
|
|
...(settings?.oauthOnInsufficientScope && {
|
|
onInsufficientScope: settings.oauthOnInsufficientScope,
|
|
}),
|
|
});
|
|
|
|
return { transport };
|
|
}
|
|
}
|