Migrate all three clients + core + test-servers from
@modelcontextprotocol/sdk@1.29 to SDK v2 (2.0.0-beta.4), keeping behavior
identical against legacy (2025-11-25) servers. Foundation for the SDK V2 +
New Spec stack.
Packages
- Split @modelcontextprotocol/sdk -> @modelcontextprotocol/client (Client,
transports, OAuth, error taxonomy, protocol types) + core (Zod schemas);
stdio -> client/stdio, Ajv -> client/validators/ajv. Test-servers ->
@modelcontextprotocol/server (+ server-legacy/sse). Deterministic import
rewrite (schemas -> core, everything else -> client); the codemod misroutes
client code to /server so it was not used for path routing.
- new Client(..., { versionNegotiation: { mode: 'legacy' } }) — nothing
2026-era goes on the wire.
Runtime (core/mcp/inspectorClient.ts)
- Error taxonomy: McpError -> ProtocolError, ErrorCode -> ProtocolErrorCode;
RequestTimeout -> SdkError/SdkErrorCode.
- Handlers take method strings; task methods (tasks/*, notifications/tasks/*)
use the 3-arg custom form (excluded from v2's spec-method set).
- Legacy tasks kept working (per project requirement): requestor tasks re-
implemented over raw client.request + explicit deprecated schemas;
experimental.tasks.callToolStream replaced by a local pollTaskToolCall
async generator (with _progressHandlers revival so task-execution progress
still reaches the caller). Receiver (server-initiated) tasks: the v2 Client
validates a sampling/elicit handler result and rejects the legacy { task }
response with -32602 — installReceiverTaskResponseBypass swaps the wrapped
entry in the private _requestHandlers map for the task-augmented branch so
{ task } reaches the wire (fixes server-initiated sampling-via-task).
- Pagination: list verbs use raw client.request({method}, List*ResultSchema)
for single-page behavior (v2's client.listX() auto-aggregate all pages).
Web / auth / apps
- Rename local JsonSchemaType -> InspectorFormSchema + add toFormSchema()
structural narrowing at the SDK-schema -> form boundary.
- ext-apps still peers on SDK v1: one compat boundary with documented casts
(remove when ext-apps#702 lands a v2 peer).
- OAuth provider saveClientInformation reconciled with v2's
OAuthClientInformationContext; InvalidClientMetadataError re-homed as a
local class (server-legacy/auth is not browser-safe).
- vitest.shared.mts dedupes @modelcontextprotocol/client+core to one copy so
vi.mock intercepts the SUT's import.
Accepted v2 behavior changes (per #1624 / spec §9.2): unknown-tool call
rejects with -32602; cancellation is stream-abort (no guaranteed
notifications/cancelled frame); output-schema strictness restored via the
Inspector's own Ajv check on the default path.
npm run ci green: validate (web 3087 / cli 212 / tui 274 / launcher 5),
coverage (>=90 per-file, all clients), smoke (launcher/cli/web), storybook
(410).
Closes #1624
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
218 lines
7.1 KiB
TypeScript
218 lines
7.1 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,
|
|
});
|
|
|
|
return { transport };
|
|
}
|
|
}
|