出品者:Wenli

A TypeScript SDK for building MCP servers and clients that connect LLMs to tools, resources, and prompts via a standardized protocol. Supports Node.js, Bun, Deno, Express, Hono, and Fastify.
This block provides the TypeScript SDK for the Model Context Protocol (MCP), covering both the client-side transport/auth layer and the shared core protocol primitives. It is aimed at developers building MCP clients, integrating OAuth flows, or implementing custom transports against MCP-compliant servers.
client/ - MCP client package: high-level Client class, OAuth auth helpers, SSE/stdio/Streamable HTTP transports, middleware, cross-app access utilitiesclient/src/client/ - Core client implementation files: auth, transport adapters, middleware pipelineclient/src/experimental/ - Experimental task client APIs (may change without notice)client/src/validators/ - Cloudflare Worker-specific JSON schema validator shimcore/ - Shared MCP protocol primitives: types, transport interfaces, task management, URI templates, auth utilitiescore/src/auth/ - OAuth error classes and error codescore/src/errors/ - SDK-level error types (SdkError, SdkErrorCode)core/src/experimental/ - Experimental task store interfaces and in-memory implementationcore/src/exports/ - Curated stable public API surface re-exported by client/server packagescore/src/shared/ - Protocol base class, auth types, transport interface, task manager, stdio helperscore/src/types/ - MCP wire protocol constants and type definitionscore/src/validators/ - AJV and Cloudflare Worker JSON schema validator implementationsnpm install @modelcontextprotocol/sdk@2.0.0-alpha.0
# If using the client package directly from source:
npm install typescript tsx
# For AJV-based schema validation (Node.js):
npm install ajv
# For OAuth / JWT auth extensions:
npm install jose
# For Zod-based schema definitions (Standard Schema compatible):
npm install zod
No native modules, pod install, or native build steps are required. This is pure TypeScript/JavaScript.
Copy the source/ directory into your project, e.g. as src/mcp-sdk/.
Update tsconfig.json to include the source:
隔離されたサンドボックスを起動しサーバー側で実行 — ローカル設定不要。
このバージョンの Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
パイプライン avcp-2026-08-04.1 · SHA-256 450aec56cf101b58…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
レビュー日 2026年8月4日
この製品をお使いのAI IDE・Webビルダー・クラウドIDEに直接取り込みます。
Tetreesを対応AI IDEに接続し、所有製品の一覧取得と検証済みZIPの取得を、販売者のアップロード権限を公開せずに行えます。
まだレビューがありません。
Sign in to join the discussion
Loading discussion…
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022",
"strict": true,
"paths": {
"@modelcontextprotocol/core/*": ["./src/mcp-sdk/core/src/*"],
"@modelcontextprotocol/client/*": ["./src/mcp-sdk/client/src/*"]
}
},
"include": ["src"]
}
npm install @modelcontextprotocol/sdk@2.0.0-alpha.0
MCP_SERVER_URL=https://your-mcp-server.example.com
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret
client/src/validators/cfWorker.ts instead of the default AJV validator.Clientimport { Client } from '@modelcontextprotocol/client';
const client = new Client(options: ClientOptions);
The main entry point for connecting to an MCP server. Handles the protocol handshake, capability negotiation, and exposes methods for calling tools, listing resources, and managing prompts. Instantiate once per server connection and reuse across requests.
authimport { auth } from '@modelcontextprotocol/client';
await auth(provider: OAuthClientProvider, options: { serverUrl: string }): Promise<AuthResult>;
Orchestrates the full OAuth 2.0 authorization flow against an MCP server. Call this before making authenticated requests when the server returns a 401. It handles discovery, PKCE, token exchange, and token refresh internally via the provided OAuthClientProvider.
discoverOAuthServerInfoimport { discoverOAuthServerInfo } from '@modelcontextprotocol/client';
const info: OAuthServerInfo = await discoverOAuthServerInfo(serverUrl: string);
Fetches and parses the OAuth authorization server metadata from a given MCP server URL. Use this to inspect supported grant types and endpoints before initiating an auth flow, or to pre-populate UI with server capabilities.
OAuthError / OAuthErrorCodeimport { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core';
try { ... } catch (e) {
if (e instanceof OAuthError) {
console.error(e.errorCode); // OAuthErrorCode enum value
}
}
Structured error class thrown by auth operations. Use errorCode to distinguish between invalid_client, access_denied, invalid_token, and other standard OAuth error responses in your error handling logic.
TaskManagerimport { TaskManager } from '@modelcontextprotocol/core';
const manager = new TaskManager(store: RequestTaskStore, options?: TaskManagerOptions);
Manages long-running request tasks with cancellation and progress tracking. Attach to a server or client protocol instance when you need to handle requests that outlive a single response message.
Establish a client connection using the Streamable HTTP transport, perform capability negotiation, and call a tool.
import { Client } from '@modelcontextprotocol/client';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client/client/streamableHttp.js';
const transport = new StreamableHTTPClientTransport(
new URL('https://your-mcp-server.example.com/mcp')
);
const client = new Client({
name: 'my-app',
version: '1.0.0'
});
await client.connect(transport);
const result = await client.callTool({
name: 'get_weather',
arguments: { location: 'London' }
});
console.log(result);
await client.close();
Discover server OAuth metadata, run the authorization code flow, and attach credentials to subsequent requests.
import {
auth,
discoverOAuthServerInfo,
UnauthorizedError,
type OAuthClientProvider
} from '@modelcontextprotocol/client';
const serverUrl = 'https://your-mcp-server.example.com';
const info = await discoverOAuthServerInfo(serverUrl);
console.log('Authorization endpoint:', info.authorizationEndpoint);
const provider: OAuthClientProvider = {
clientMetadata: {
client_name: 'My MCP App',
redirect_uris: ['http://localhost:3000/callback']
},
async redirectToAuthorization(url) {
console.log('Visit:', url.toString());
},
async saveTokens(tokens) {
// persist tokens to storage
},
async tokens() {
// return stored tokens or undefined
return undefined;
},
async saveCodeVerifier(verifier) { /* store verifier */ },
async codeVerifier() { return 'stored-verifier'; }
};
const result = await auth(provider, { serverUrl });
console.log('Auth result:', result);
Subscribe to task progress for long-running MCP operations using the experimental tasks client API.
import { Client } from '@modelcontextprotocol/client';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client/client/streamableHttp.js';
// Experimental — may change without notice
import { } from '@modelcontextprotocol/client/experimental';
import { InMemoryTaskStore } from '@modelcontextprotocol/core';
const store = new InMemoryTaskStore();
const transport = new StreamableHTTPClientTransport(
new URL('https://your-mcp-server.example.com/mcp')
);
const client = new Client({ name: 'task-demo', version: '1.0.0' });
await client.connect(transport);
// Long-running tool call with task tracking
const response = await client.callTool({
name: 'long_analysis',
arguments: { dataset: 'large' }
});
console.log(response);
await client.close();
client/src/index.ts - Complete public API surface for the client package; all stable exports are named explicitly here.client/src/client/auth.ts - Full OAuth 2.0 flow implementation: discovery, PKCE, token exchange, refresh, dynamic client registration.client/src/client/authExtensions.ts - Advanced auth providers: ClientCredentialsProvider, PrivateKeyJwtProvider, CrossAppAccessProvider.client/src/client/client.ts - Client class and ClientOptions; high-level MCP protocol operations.client/src/client/crossAppAccess.ts - JWT-based cross-application access grant helpers.client/src/client/middleware.ts - Middleware pipeline types and Middleware interface for intercepting client requests.client/src/client/streamableHttp.ts - Streamable HTTP transport implementation.client/src/client/sse.ts - SSE (Server-Sent Events) transport for legacy MCP servers.client/src/client/stdio.ts - stdio transport for local process-based MCP servers.client/src/experimental/tasks/client.ts - Experimental task subscription and progress client APIs.client/src/validators/cfWorker.ts - Cloudflare Worker-compatible JSON schema validator shim.core/src/index.ts - Internal barrel for all core exports; used by client/server packages, not end users directly.core/src/exports/public/index.ts - Curated stable public API subset; what end users should depend on.core/src/shared/protocol.ts - Protocol base class and core request/notification infrastructure.core/src/shared/auth.ts - OAuth and OpenID Connect TypeScript type definitions.core/src/shared/transport.ts - Transport interface definition.core/src/shared/taskManager.ts - TaskManager class for managing long-running request lifecycles.core/src/auth/errors.ts - OAuthError and OAuthErrorCode structured error types.core/src/errors/sdkErrors.ts - SdkError and SdkErrorCode for SDK-level (non-wire) errors.core/src/experimental/tasks/ - Task store interfaces and InMemoryTaskStore implementation..js extensions in imports: The SDK uses NodeNext module resolution; when importing from source files, always include the .js extension even for .ts files (e.g. ./auth.js), or TypeScript will fail to resolve the module.OAuthClientProvider must implement all callbacks: Missing any of tokens, saveTokens, redirectToAuthorization, saveCodeVerifier, or codeVerifier will cause runtime errors during the auth flow; implement stubs if needed.CfWorkerJsonSchemaValidator from client/src/validators/cfWorker.ts instead.experimental/ paths has no semver stability guarantees; pin the exact package version when using these.module: NodeNext vs bundler: If your bundler uses module: "bundler" in tsconfig, the .js extension imports from core/client may conflict; configure moduleResolution: "bundler" consistently across all packages.auth() does not persist tokens itself; your OAuthClientProvider implementation must handle storage (localStorage, secure cookie, database, etc.) or tokens will be lost on page reload.I have an MCP TypeScript SDK source drop at `source/` and a usage guide at `USAGE.md`.
The upstream package is `@modelcontextprotocol/sdk@2.0.0-alpha.0` (split into
`@modelcontextprotocol/client` and `@modelcontextprotocol/core`).
My project is a Node.js/TypeScript Express application. Please help me integrate
the MCP client into my project step by step:
1. Read `USAGE.md` and `source/client/src/index.ts` to understand all available exports.
2. Add an MCP client singleton that connects to `MCP_SERVER_URL` via Streamable HTTP transport.
3. Add an OAuth flow using the `auth()` function and `OAuthClientProvider` interface,
storing tokens in-memory for now.
4. Expose an Express route `POST /mcp/tool/:name` that calls the named MCP tool with
the request body as arguments and returns the result as JSON.
5. Handle `OAuthError` and `SdkError` with appropriate HTTP status codes (401 vs 500).
6. Use only exports visible in `source/client/src/index.ts` and `source/core/src/exports/public/index.ts`.
Do not invent any APIs.
Show the complete TypeScript files you create or modify.
The upstream project is licensed under the MIT License (see source/LICENSE if present, or refer to the GitHub repository). Upstream package: @modelcontextprotocol/sdk by the Model Context Protocol authors.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完全なインストールガイドと統合プロンプトは購入後に解放されます。
SaaS, AI & Subscription Products
無料