[v2] Мonorepo, sdk-client, sdk-server, sdk-core package split (#1279)

This commit is contained in:
Konstantin Konstantinov 2025-12-19 15:19:02 +02:00 • committed by GitHub
commit 71ae3acee0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 12067 additions and 4817 deletions

View file

@ -0,0 +1,22 @@
import * as z3 from 'zod/v3';
import * as z4 from 'zod/v4';
// Shared Zod namespace type that exposes the common surface area used in tests.
export type ZNamespace = typeof z3 & typeof z4;
export const zodTestMatrix = [
{
zodVersionLabel: 'Zod v3',
z: z3 as ZNamespace,
isV3: true as const,
isV4: false as const
},
{
zodVersionLabel: 'Zod v4',
z: z4 as ZNamespace,
isV3: false as const,
isV4: true as const
}
] as const;
export type ZodMatrixEntry = (typeof zodTestMatrix)[number];

View file

@ -0,0 +1,96 @@
import type { Server, ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
import type { Response } from 'express';
import { vi } from 'vitest';
/**
* Attach a listener to an existing server on a random localhost port and return its base URL.
*/
export async function listenOnRandomPort(server: Server, host: string = '127.0.0.1'): Promise<URL> {
return new Promise<URL>(resolve => {
server.listen(0, host, () => {
const addr = server.address() as AddressInfo;
resolve(new URL(`http://${host}:${addr.port}`));
});
});
}
// =========================
// HTTP/Express mock helpers
// =========================
/**
* Create a minimal Express-like Response mock for tests.
*
* The mock supports:
* - redirect()
* - status().json().send() chaining
* - set()/header()
* - optional getRedirectUrl() helper used in some tests
*/
export function createExpressResponseMock(options: { trackRedirectUrl?: boolean } = {}): Response & {
getRedirectUrl?: () => string;
} {
let capturedRedirectUrl: string | undefined;
const res: Partial<Response> & { getRedirectUrl?: () => string } = {
redirect: vi.fn((urlOrStatus: string | number, maybeUrl?: string | number) => {
if (options.trackRedirectUrl) {
if (typeof urlOrStatus === 'string') {
capturedRedirectUrl = urlOrStatus;
} else if (typeof maybeUrl === 'string') {
capturedRedirectUrl = maybeUrl;
}
}
return res as Response;
}) as unknown as Response['redirect'],
status: vi.fn<Response['status']>().mockImplementation((_code: number) => {
// status code is ignored for now; tests assert it via jest/vitest spies
return res as Response;
}),
json: vi.fn<Response['json']>().mockImplementation((_body: unknown) => {
// body is ignored; tests usually assert via spy
return res as Response;
}),
send: vi.fn<Response['send']>().mockImplementation((_body?: unknown) => {
// body is ignored; tests usually assert via spy
return res as Response;
}),
set: vi.fn<Response['set']>().mockImplementation((_field: string, _value?: string | string[]) => {
// header value is ignored in the generic mock; tests spy on set()
return res as Response;
}),
header: vi.fn<Response['header']>().mockImplementation((_field: string, _value?: string | string[]) => {
return res as Response;
})
};
if (options.trackRedirectUrl) {
res.getRedirectUrl = () => {
if (capturedRedirectUrl === undefined) {
throw new Error('No redirect URL was captured. Ensure redirect() was called first.');
}
return capturedRedirectUrl;
};
}
return res as Response & { getRedirectUrl?: () => string };
}
/**
* Create a Node http.ServerResponse mock used for low-level transport tests.
*
* All core methods are jest/vitest fns returning `this` so that
* tests can assert on writeHead/write/on/end calls.
*/
export function createNodeServerResponseMock(): ServerResponse {
const res = {
writeHead: vi.fn<ServerResponse['writeHead']>().mockReturnThis(),
write: vi.fn<ServerResponse['write']>().mockReturnThis(),
on: vi.fn<ServerResponse['on']>().mockReturnThis(),
end: vi.fn<ServerResponse['end']>().mockReturnThis()
};
return res as unknown as ServerResponse;
}

View file

@ -0,0 +1,89 @@
import type { FetchLike } from '@modelcontextprotocol/core';
import { vi } from 'vitest';
export interface MockOAuthFetchOptions {
resourceServerUrl: string;
authServerUrl: string;
/**
* Optional hook to inspect or override the token request.
*/
onTokenRequest?: (url: URL, init: RequestInit | undefined) => void | Promise<void>;
}
/**
* Shared mock fetch implementation for OAuth flows used in client tests.
*
* It handles:
* - OAuth Protected Resource Metadata discovery
* - Authorization Server Metadata discovery
* - Token endpoint responses
*/
export function createMockOAuthFetch(options: MockOAuthFetchOptions): FetchLike {
const { resourceServerUrl, authServerUrl, onTokenRequest } = options;
return async (input: string | URL, init?: RequestInit): Promise<Response> => {
const url = input instanceof URL ? input : new URL(input);
// Protected resource metadata discovery
if (url.origin === resourceServerUrl.slice(0, -1) && url.pathname === '/.well-known/oauth-protected-resource') {
return new Response(
JSON.stringify({
resource: resourceServerUrl,
authorization_servers: [authServerUrl]
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
}
// Authorization server metadata discovery
if (url.origin === authServerUrl && url.pathname === '/.well-known/oauth-authorization-server') {
return new Response(
JSON.stringify({
issuer: authServerUrl,
authorization_endpoint: `${authServerUrl}/authorize`,
token_endpoint: `${authServerUrl}/token`,
response_types_supported: ['code'],
token_endpoint_auth_methods_supported: ['client_secret_basic', 'private_key_jwt']
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
}
// Token endpoint
if (url.origin === authServerUrl && url.pathname === '/token') {
if (onTokenRequest) {
await onTokenRequest(url, init);
}
return new Response(
JSON.stringify({
access_token: 'test-access-token',
token_type: 'Bearer'
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
}
throw new Error(`Unexpected URL in mock OAuth fetch: ${url.toString()}`);
};
}
type MockFetch = (...args: unknown[]) => unknown;
/**
* Helper to install a vi.fn-based global.fetch mock for tests that rely on global fetch.
*/
export function mockGlobalFetch(): MockFetch {
const mockFetch = vi.fn() as unknown as MockFetch;
(globalThis as { fetch?: MockFetch }).fetch = mockFetch;
return mockFetch;
}

View file

@ -0,0 +1,33 @@
import type { Task } from '@modelcontextprotocol/core';
/**
* Polls the provided getTask function until the task reaches the desired status or times out.
*/
export async function waitForTaskStatus(
getTask: (taskId: string) => Promise<Task | null | undefined>,
taskId: string,
desiredStatus: Task['status'],
{
intervalMs = 100,
timeoutMs = 10_000
}: {
intervalMs?: number;
timeoutMs?: number;
} = {}
): Promise<Task> {
const start = Date.now();
// eslint-disable-next-line no-constant-condition
while (true) {
const task = await getTask(taskId);
if (task && task.status === desiredStatus) {
return task;
}
if (Date.now() - start > timeoutMs) {
throw new Error(`Timed out waiting for task ${taskId} to reach status ${desiredStatus}`);
}
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
}

View file

@ -0,0 +1,4 @@
export * from './fixtures/zodTestMatrix.js';
export * from './helpers/http.js';
export * from './helpers/oauth.js';
export * from './helpers/tasks.js';