[v2] Мonorepo, sdk-client, sdk-server, sdk-core package split (#1279)
This commit is contained in:
parent
384311b9b8
commit
71ae3acee0
10 changed files with 12067 additions and 4817 deletions
5
test/helpers/eslint.config.mjs
Normal file
5
test/helpers/eslint.config.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// @ts-check
|
||||
|
||||
import baseConfig from '@modelcontextprotocol/eslint-config';
|
||||
|
||||
export default baseConfig;
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
import { InMemoryTransport } from '../../src/inMemory.js';
|
||||
import { Client } from '../../src/client/index.js';
|
||||
import { Server } from '../../src/server/index.js';
|
||||
import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js';
|
||||
import type { ClientCapabilities, ServerCapabilities } from '../../src/types.js';
|
||||
|
||||
export interface InMemoryTaskEnvironment {
|
||||
client: Client;
|
||||
server: Server;
|
||||
taskStore: InMemoryTaskStore;
|
||||
clientTransport: InMemoryTransport;
|
||||
serverTransport: InMemoryTransport;
|
||||
}
|
||||
|
||||
export async function createInMemoryTaskEnvironment(options?: {
|
||||
clientCapabilities?: ClientCapabilities;
|
||||
serverCapabilities?: ServerCapabilities;
|
||||
}): Promise<InMemoryTaskEnvironment> {
|
||||
const taskStore = new InMemoryTaskStore();
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test-client',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{
|
||||
capabilities: options?.clientCapabilities ?? {
|
||||
tasks: {
|
||||
list: {},
|
||||
requests: {
|
||||
tools: {
|
||||
call: {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test-server',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{
|
||||
capabilities: options?.serverCapabilities ?? {
|
||||
tasks: {
|
||||
list: {},
|
||||
requests: {
|
||||
tools: {
|
||||
call: {}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
taskStore,
|
||||
taskMessageQueue: new InMemoryTaskMessageQueue()
|
||||
}
|
||||
);
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
return {
|
||||
client,
|
||||
server,
|
||||
taskStore,
|
||||
clientTransport,
|
||||
serverTransport
|
||||
};
|
||||
}
|
||||
42
test/helpers/package.json
Normal file
42
test/helpers/package.json
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
{
|
||||
"name": "@modelcontextprotocol/test-helpers",
|
||||
"private": true,
|
||||
"version": "2.0.0-alpha.0",
|
||||
"description": "Model Context Protocol implementation for TypeScript",
|
||||
"license": "MIT",
|
||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||
"homepage": "https://modelcontextprotocol.io",
|
||||
"bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues",
|
||||
"type": "module",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20",
|
||||
"pnpm": ">=10.24.0"
|
||||
},
|
||||
"packageManager": "pnpm@10.24.0",
|
||||
"keywords": [
|
||||
"modelcontextprotocol",
|
||||
"mcp"
|
||||
],
|
||||
"scripts": {
|
||||
"lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .",
|
||||
"lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .",
|
||||
"check": "npm run typecheck && npm run lint",
|
||||
"start": "npm run server",
|
||||
"server": "tsx watch --clear-screen=false scripts/cli.ts server",
|
||||
"client": "tsx scripts/cli.ts client"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/core": "workspace:^",
|
||||
"@modelcontextprotocol/client": "workspace:^",
|
||||
"@modelcontextprotocol/server": "workspace:^",
|
||||
"zod": "catalog:runtimeShared",
|
||||
"vitest": "catalog:devTools",
|
||||
"@modelcontextprotocol/tsconfig": "workspace:^",
|
||||
"@modelcontextprotocol/vitest-config": "workspace:^",
|
||||
"@modelcontextprotocol/eslint-config": "workspace:^"
|
||||
}
|
||||
}
|
||||
22
test/helpers/src/fixtures/zodTestMatrix.ts
Normal file
22
test/helpers/src/fixtures/zodTestMatrix.ts
Normal 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];
|
||||
96
test/helpers/src/helpers/http.ts
Normal file
96
test/helpers/src/helpers/http.ts
Normal 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;
|
||||
}
|
||||
89
test/helpers/src/helpers/oauth.ts
Normal file
89
test/helpers/src/helpers/oauth.ts
Normal 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;
|
||||
}
|
||||
33
test/helpers/src/helpers/tasks.ts
Normal file
33
test/helpers/src/helpers/tasks.ts
Normal 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));
|
||||
}
|
||||
}
|
||||
4
test/helpers/src/index.ts
Normal file
4
test/helpers/src/index.ts
Normal 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';
|
||||
14
test/helpers/tsconfig.json
Normal file
14
test/helpers/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "@modelcontextprotocol/tsconfig",
|
||||
"include": ["./", "../integration/test/helpers/mcp.ts"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"*": ["./*"],
|
||||
"@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"],
|
||||
"@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"],
|
||||
"@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"],
|
||||
"@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"]
|
||||
}
|
||||
}
|
||||
}
|
||||
3
test/helpers/vitest.config.js
Normal file
3
test/helpers/vitest.config.js
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import baseConfig from '../../common/vitest-config/vitest.config.js';
|
||||
|
||||
export default baseConfig;
|
||||
Loading…
Reference in a new issue