This commit is contained in:
2026-03-03 23:49:13 +01:00
parent 1946f96bf8
commit 0ae7f9963f
6446 changed files with 1032754 additions and 34 deletions

21
node_modules/@modelcontextprotocol/sdk/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Anthropic, PBC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

170
node_modules/@modelcontextprotocol/sdk/README.md generated vendored Normal file
View File

@@ -0,0 +1,170 @@
# MCP TypeScript SDK [![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk)](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/LICENSE)
<details>
<summary>Table of Contents</summary>
- [Overview](#overview)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
- [Examples](#examples)
- [Documentation](#documentation)
- [Contributing](#contributing)
- [License](#license)
</details>
## Overview
The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements
[the full MCP specification](https://modelcontextprotocol.io/specification/draft), making it easy to:
- Create MCP servers that expose resources, prompts and tools
- Build MCP clients that can connect to any MCP server
- Use standard transports like stdio and Streamable HTTP
## Installation
```bash
npm install @modelcontextprotocol/sdk zod
```
This SDK has a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from `zod/v3` or `zod/v4`:
## Quick Start
To see the SDK in action end-to-end, start from the runnable examples in `src/examples`:
1. **Install dependencies** (from the SDK repo root):
```bash
npm install
```
2. **Run the example Streamable HTTP server**:
```bash
npx tsx src/examples/server/simpleStreamableHttp.ts
```
3. **Run the interactive client in another terminal**:
```bash
npx tsx src/examples/client/simpleStreamableHttp.ts
```
This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see [docs/server.md](docs/server.md) and
[docs/client.md](docs/client.md).
## Core Concepts
### Servers and transports
An MCP server is typically created with `McpServer` and connected to a transport such as Streamable HTTP or stdio. The SDK supports:
- **Streamable HTTP** for remote servers (recommended).
- **HTTP + SSE** for backwards compatibility only.
- **stdio** for local, process-spawned integrations.
Runnable server examples live under `src/examples/server` and are documented in [docs/server.md](docs/server.md).
### Tools, resources, prompts
- **Tools** let LLMs ask your server to take actions (computation, side effects, network calls).
- **Resources** expose read-only data that clients can surface to users or models.
- **Prompts** are reusable templates that help users talk to models in a consistent way.
The detailed APIs, including `ResourceTemplate`, completions, and display-name metadata, are covered in [docs/server.md](docs/server.md#tools-resources-and-prompts), with runnable implementations in [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts).
### Capabilities: sampling, elicitation, and tasks
The SDK includes higher-level capabilities for richer workflows:
- **Sampling**: server-side tools can ask connected clients to run LLM completions.
- **Form elicitation**: tools can request non-sensitive input via structured forms.
- **URL elicitation**: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth).
- **Tasks (experimental)**: long-running tool calls can be turned into tasks that you poll or resume later.
Conceptual overviews and links to runnable examples are in:
- [docs/capabilities.md](docs/capabilities.md)
Key example servers include:
- [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts)
- [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts)
- [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts)
### Clients
The high-level `Client` class connects to MCP servers over different transports and exposes helpers like `listTools`, `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`.
Runnable clients live under `src/examples/client` and are described in [docs/client.md](docs/client.md), including:
- Interactive Streamable HTTP client ([`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts))
- Streamable HTTP client with SSE fallback ([`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts))
- OAuth-enabled clients and polling/parallel examples
### Node.js Web Crypto (globalThis.crypto) compatibility
Some parts of the SDK (for example, JWT-based client authentication in `auth-extensions.ts` via `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`.
See [docs/faq.md](docs/faq.md) for details on supported Node.js versions and how to polyfill `globalThis.crypto` when running on older Node.js runtimes.
## Examples
The SDK ships runnable examples under `src/examples`. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs.
### Server examples
| Scenario | Description | Example file(s) | Related docs |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Streamable HTTP server (stateful) | Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth. | [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts) | [`server.md`](docs/server.md), [`capabilities.md`](docs/capabilities.md) |
| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`simpleStatelessStreamableHttp.ts`](src/examples/server/simpleStatelessStreamableHttp.ts) | [`server.md`](docs/server.md) |
| JSON response mode (no SSE) | Streamable HTTP with JSON responses only and limited notifications. | [`jsonResponseStreamableHttp.ts`](src/examples/server/jsonResponseStreamableHttp.ts) | [`server.md`](docs/server.md) |
| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications using SSE with Streamable HTTP. | [`standaloneSseWithGetStreamableHttp.ts`](src/examples/server/standaloneSseWithGetStreamableHttp.ts) | [`server.md`](docs/server.md) |
| Deprecated HTTP+SSE server | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`simpleSseServer.ts`](src/examples/server/simpleSseServer.ts) | [`server.md`](docs/server.md) |
| Backwards-compatible server (Streamable HTTP + SSE) | Single server that supports both Streamable HTTP and legacy SSE clients. | [`sseAndStreamableHttpCompatibleServer.ts`](src/examples/server/sseAndStreamableHttpCompatibleServer.ts) | [`server.md`](docs/server.md) |
| Form elicitation server | Uses form elicitation to collect non-sensitive user input. | [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
| URL elicitation server | Demonstrates URL-mode elicitation in an OAuth-protected server. | [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
| Sampling and tasks server | Combines tools, logging, sampling, and experimental task-based execution. | [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) | [`capabilities.md`](docs/capabilities.md) |
| OAuth demo authorization server | In-memory OAuth provider used with the example servers. | [`demoInMemoryOAuthProvider.ts`](src/examples/server/demoInMemoryOAuthProvider.ts) | [`server.md`](docs/server.md) |
### Client examples
| Scenario | Description | Example file(s) | Related docs |
| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| Interactive Streamable HTTP client | CLI client that exercises tools, resources, prompts, elicitation, and tasks. | [`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts) | [`client.md`](docs/client.md) |
| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, then falls back to SSE on 4xx responses. | [`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts) | [`client.md`](docs/client.md), [`server.md`](docs/server.md) |
| SSE polling client | Polls a legacy SSE server and demonstrates notification handling. | [`ssePollingClient.ts`](src/examples/client/ssePollingClient.ts) | [`client.md`](docs/client.md) |
| Parallel tool calls client | Shows how to run multiple tool calls in parallel. | [`parallelToolCallsClient.ts`](src/examples/client/parallelToolCallsClient.ts) | [`client.md`](docs/client.md) |
| Multiple clients in parallel | Demonstrates connecting multiple clients concurrently to the same server. | [`multipleClientsParallel.ts`](src/examples/client/multipleClientsParallel.ts) | [`client.md`](docs/client.md) |
| OAuth clients | Examples of client_credentials (basic and private_key_jwt) and reusable providers. | [`simpleOAuthClient.ts`](src/examples/client/simpleOAuthClient.ts), [`simpleOAuthClientProvider.ts`](src/examples/client/simpleOAuthClientProvider.ts), [`simpleClientCredentials.ts`](src/examples/client/simpleClientCredentials.ts) | [`client.md`](docs/client.md) |
| URL elicitation client | Works with the URL elicitation server to drive secure browser flows. | [`elicitationUrlExample.ts`](src/examples/client/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
Shared utilities:
- In-memory event store for resumability: [`inMemoryEventStore.ts`](src/examples/shared/inMemoryEventStore.ts) (see [`server.md`](docs/server.md)).
For more details on how to run these examples (including recommended commands and deployment diagrams), see `src/examples/README.md`.
## Documentation
- Local SDK docs:
- [docs/server.md](docs/server.md) building and running MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and multi-node deployment.
- [docs/client.md](docs/client.md) using the high-level client, transports, backwards compatibility, and OAuth helpers.
- [docs/capabilities.md](docs/capabilities.md) sampling, elicitation (form and URL), and experimental task-based execution.
- [docs/protocol.md](docs/protocol.md) protocol features: ping, progress, cancellation, pagination, capability negotiation, and JSON Schema.
- [docs/faq.md](docs/faq.md) environment and troubleshooting FAQs (including Node.js Web Crypto support).
- External references:
- [Model Context Protocol documentation](https://modelcontextprotocol.io)
- [MCP Specification](https://spec.modelcontextprotocol.io)
- [Example Servers](https://github.com/modelcontextprotocol/servers)
## Contributing
Issues and pull requests are welcome on GitHub at <https://github.com/modelcontextprotocol/typescript-sdk>.
## License
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details.

View File

@@ -0,0 +1,190 @@
/**
* OAuth provider extensions for specialized authentication flows.
*
* This module provides ready-to-use OAuthClientProvider implementations
* for common machine-to-machine authentication scenarios.
*/
import { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '../shared/auth.js';
import { AddClientAuthentication, OAuthClientProvider } from './auth.js';
/**
* Helper to produce a private_key_jwt client authentication function.
*
* Usage:
* const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? });
* // pass addClientAuth as provider.addClientAuthentication implementation
*/
export declare function createPrivateKeyJwtAuth(options: {
issuer: string;
subject: string;
privateKey: string | Uint8Array | Record<string, unknown>;
alg: string;
audience?: string | URL;
lifetimeSeconds?: number;
claims?: Record<string, unknown>;
}): AddClientAuthentication;
/**
* Options for creating a ClientCredentialsProvider.
*/
export interface ClientCredentialsProviderOptions {
/**
* The client_id for this OAuth client.
*/
clientId: string;
/**
* The client_secret for client_secret_basic authentication.
*/
clientSecret: string;
/**
* Optional client name for metadata.
*/
clientName?: string;
/**
* Space-separated scopes values requested by the client.
*/
scope?: string;
}
/**
* OAuth provider for client_credentials grant with client_secret_basic authentication.
*
* This provider is designed for machine-to-machine authentication where
* the client authenticates using a client_id and client_secret.
*
* @example
* const provider = new ClientCredentialsProvider({
* clientId: 'my-client',
* clientSecret: 'my-secret'
* });
*
* const transport = new StreamableHTTPClientTransport(serverUrl, {
* authProvider: provider
* });
*/
export declare class ClientCredentialsProvider implements OAuthClientProvider {
private _tokens?;
private _clientInfo;
private _clientMetadata;
constructor(options: ClientCredentialsProviderOptions);
get redirectUrl(): undefined;
get clientMetadata(): OAuthClientMetadata;
clientInformation(): OAuthClientInformation;
saveClientInformation(info: OAuthClientInformation): void;
tokens(): OAuthTokens | undefined;
saveTokens(tokens: OAuthTokens): void;
redirectToAuthorization(): void;
saveCodeVerifier(): void;
codeVerifier(): string;
prepareTokenRequest(scope?: string): URLSearchParams;
}
/**
* Options for creating a PrivateKeyJwtProvider.
*/
export interface PrivateKeyJwtProviderOptions {
/**
* The client_id for this OAuth client.
*/
clientId: string;
/**
* The private key for signing JWT assertions.
* Can be a PEM string, Uint8Array, or JWK object.
*/
privateKey: string | Uint8Array | Record<string, unknown>;
/**
* The algorithm to use for signing (e.g., 'RS256', 'ES256').
*/
algorithm: string;
/**
* Optional client name for metadata.
*/
clientName?: string;
/**
* Optional JWT lifetime in seconds (default: 300).
*/
jwtLifetimeSeconds?: number;
/**
* Space-separated scopes values requested by the client.
*/
scope?: string;
}
/**
* OAuth provider for client_credentials grant with private_key_jwt authentication.
*
* This provider is designed for machine-to-machine authentication where
* the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2).
*
* @example
* const provider = new PrivateKeyJwtProvider({
* clientId: 'my-client',
* privateKey: pemEncodedPrivateKey,
* algorithm: 'RS256'
* });
*
* const transport = new StreamableHTTPClientTransport(serverUrl, {
* authProvider: provider
* });
*/
export declare class PrivateKeyJwtProvider implements OAuthClientProvider {
private _tokens?;
private _clientInfo;
private _clientMetadata;
addClientAuthentication: AddClientAuthentication;
constructor(options: PrivateKeyJwtProviderOptions);
get redirectUrl(): undefined;
get clientMetadata(): OAuthClientMetadata;
clientInformation(): OAuthClientInformation;
saveClientInformation(info: OAuthClientInformation): void;
tokens(): OAuthTokens | undefined;
saveTokens(tokens: OAuthTokens): void;
redirectToAuthorization(): void;
saveCodeVerifier(): void;
codeVerifier(): string;
prepareTokenRequest(scope?: string): URLSearchParams;
}
/**
* Options for creating a StaticPrivateKeyJwtProvider.
*/
export interface StaticPrivateKeyJwtProviderOptions {
/**
* The client_id for this OAuth client.
*/
clientId: string;
/**
* A pre-built JWT client assertion to use for authentication.
*
* This token should already contain the appropriate claims
* (iss, sub, aud, exp, etc.) and be signed by the client's key.
*/
jwtBearerAssertion: string;
/**
* Optional client name for metadata.
*/
clientName?: string;
/**
* Space-separated scopes values requested by the client.
*/
scope?: string;
}
/**
* OAuth provider for client_credentials grant with a static private_key_jwt assertion.
*
* This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and
* signing a JWT on each request, it accepts a pre-built JWT assertion string and
* uses it directly for authentication.
*/
export declare class StaticPrivateKeyJwtProvider implements OAuthClientProvider {
private _tokens?;
private _clientInfo;
private _clientMetadata;
addClientAuthentication: AddClientAuthentication;
constructor(options: StaticPrivateKeyJwtProviderOptions);
get redirectUrl(): undefined;
get clientMetadata(): OAuthClientMetadata;
clientInformation(): OAuthClientInformation;
saveClientInformation(info: OAuthClientInformation): void;
tokens(): OAuthTokens | undefined;
saveTokens(tokens: OAuthTokens): void;
redirectToAuthorization(): void;
saveCodeVerifier(): void;
codeVerifier(): string;
prepareTokenRequest(scope?: string): URLSearchParams;
}
//# sourceMappingURL=auth-extensions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"auth-extensions.d.ts","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CA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AC,IAAI,EAAE,sBAAsB,GAAG,IAAI;IAIzD,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,IAAI,IAAI;IAI/B,gBAAgB,IAAI,IAAI;IAIxB,YAAY,IAAI,MAAM;IAItB,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,eAAe;CAKvD"}

View File

@@ -0,0 +1,299 @@
"use strict";
/**
* OAuth provider extensions for specialized authentication flows.
*
* This module provides ready-to-use OAuthClientProvider implementations
* for common machine-to-machine authentication scenarios.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticPrivateKeyJwtProvider = exports.PrivateKeyJwtProvider = exports.ClientCredentialsProvider = void 0;
exports.createPrivateKeyJwtAuth = createPrivateKeyJwtAuth;
/**
* Helper to produce a private_key_jwt client authentication function.
*
* Usage:
* const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? });
* // pass addClientAuth as provider.addClientAuthentication implementation
*/
function createPrivateKeyJwtAuth(options) {
return async (_headers, params, url, metadata) => {
// Lazy import to avoid heavy dependency unless used
if (typeof globalThis.crypto === 'undefined') {
throw new TypeError('crypto is not available, please ensure you add have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)');
}
const jose = await Promise.resolve().then(() => __importStar(require('jose')));
const audience = String(options.audience ?? metadata?.issuer ?? url);
const lifetimeSeconds = options.lifetimeSeconds ?? 300;
const now = Math.floor(Date.now() / 1000);
const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
const baseClaims = {
iss: options.issuer,
sub: options.subject,
aud: audience,
exp: now + lifetimeSeconds,
iat: now,
jti
};
const claims = options.claims ? { ...baseClaims, ...options.claims } : baseClaims;
// Import key for the requested algorithm
const alg = options.alg;
let key;
if (typeof options.privateKey === 'string') {
if (alg.startsWith('RS') || alg.startsWith('ES') || alg.startsWith('PS')) {
key = await jose.importPKCS8(options.privateKey, alg);
}
else if (alg.startsWith('HS')) {
key = new TextEncoder().encode(options.privateKey);
}
else {
throw new Error(`Unsupported algorithm ${alg}`);
}
}
else if (options.privateKey instanceof Uint8Array) {
if (alg.startsWith('HS')) {
key = options.privateKey;
}
else {
// Assume PKCS#8 DER in Uint8Array for asymmetric algorithms
key = await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg);
}
}
else {
// Treat as JWK
key = await jose.importJWK(options.privateKey, alg);
}
// Sign JWT
const assertion = await new jose.SignJWT(claims)
.setProtectedHeader({ alg, typ: 'JWT' })
.setIssuer(options.issuer)
.setSubject(options.subject)
.setAudience(audience)
.setIssuedAt(now)
.setExpirationTime(now + lifetimeSeconds)
.setJti(jti)
.sign(key);
params.set('client_assertion', assertion);
params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
};
}
/**
* OAuth provider for client_credentials grant with client_secret_basic authentication.
*
* This provider is designed for machine-to-machine authentication where
* the client authenticates using a client_id and client_secret.
*
* @example
* const provider = new ClientCredentialsProvider({
* clientId: 'my-client',
* clientSecret: 'my-secret'
* });
*
* const transport = new StreamableHTTPClientTransport(serverUrl, {
* authProvider: provider
* });
*/
class ClientCredentialsProvider {
constructor(options) {
this._clientInfo = {
client_id: options.clientId,
client_secret: options.clientSecret
};
this._clientMetadata = {
client_name: options.clientName ?? 'client-credentials-client',
redirect_uris: [],
grant_types: ['client_credentials'],
token_endpoint_auth_method: 'client_secret_basic',
scope: options.scope
};
}
get redirectUrl() {
return undefined;
}
get clientMetadata() {
return this._clientMetadata;
}
clientInformation() {
return this._clientInfo;
}
saveClientInformation(info) {
this._clientInfo = info;
}
tokens() {
return this._tokens;
}
saveTokens(tokens) {
this._tokens = tokens;
}
redirectToAuthorization() {
throw new Error('redirectToAuthorization is not used for client_credentials flow');
}
saveCodeVerifier() {
// Not used for client_credentials
}
codeVerifier() {
throw new Error('codeVerifier is not used for client_credentials flow');
}
prepareTokenRequest(scope) {
const params = new URLSearchParams({ grant_type: 'client_credentials' });
if (scope)
params.set('scope', scope);
return params;
}
}
exports.ClientCredentialsProvider = ClientCredentialsProvider;
/**
* OAuth provider for client_credentials grant with private_key_jwt authentication.
*
* This provider is designed for machine-to-machine authentication where
* the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2).
*
* @example
* const provider = new PrivateKeyJwtProvider({
* clientId: 'my-client',
* privateKey: pemEncodedPrivateKey,
* algorithm: 'RS256'
* });
*
* const transport = new StreamableHTTPClientTransport(serverUrl, {
* authProvider: provider
* });
*/
class PrivateKeyJwtProvider {
constructor(options) {
this._clientInfo = {
client_id: options.clientId
};
this._clientMetadata = {
client_name: options.clientName ?? 'private-key-jwt-client',
redirect_uris: [],
grant_types: ['client_credentials'],
token_endpoint_auth_method: 'private_key_jwt',
scope: options.scope
};
this.addClientAuthentication = createPrivateKeyJwtAuth({
issuer: options.clientId,
subject: options.clientId,
privateKey: options.privateKey,
alg: options.algorithm,
lifetimeSeconds: options.jwtLifetimeSeconds
});
}
get redirectUrl() {
return undefined;
}
get clientMetadata() {
return this._clientMetadata;
}
clientInformation() {
return this._clientInfo;
}
saveClientInformation(info) {
this._clientInfo = info;
}
tokens() {
return this._tokens;
}
saveTokens(tokens) {
this._tokens = tokens;
}
redirectToAuthorization() {
throw new Error('redirectToAuthorization is not used for client_credentials flow');
}
saveCodeVerifier() {
// Not used for client_credentials
}
codeVerifier() {
throw new Error('codeVerifier is not used for client_credentials flow');
}
prepareTokenRequest(scope) {
const params = new URLSearchParams({ grant_type: 'client_credentials' });
if (scope)
params.set('scope', scope);
return params;
}
}
exports.PrivateKeyJwtProvider = PrivateKeyJwtProvider;
/**
* OAuth provider for client_credentials grant with a static private_key_jwt assertion.
*
* This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and
* signing a JWT on each request, it accepts a pre-built JWT assertion string and
* uses it directly for authentication.
*/
class StaticPrivateKeyJwtProvider {
constructor(options) {
this._clientInfo = {
client_id: options.clientId
};
this._clientMetadata = {
client_name: options.clientName ?? 'static-private-key-jwt-client',
redirect_uris: [],
grant_types: ['client_credentials'],
token_endpoint_auth_method: 'private_key_jwt',
scope: options.scope
};
const assertion = options.jwtBearerAssertion;
this.addClientAuthentication = async (_headers, params) => {
params.set('client_assertion', assertion);
params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
};
}
get redirectUrl() {
return undefined;
}
get clientMetadata() {
return this._clientMetadata;
}
clientInformation() {
return this._clientInfo;
}
saveClientInformation(info) {
this._clientInfo = info;
}
tokens() {
return this._tokens;
}
saveTokens(tokens) {
this._tokens = tokens;
}
redirectToAuthorization() {
throw new Error('redirectToAuthorization is not used for client_credentials flow');
}
saveCodeVerifier() {
// Not used for client_credentials
}
codeVerifier() {
throw new Error('codeVerifier is not used for client_credentials flow');
}
prepareTokenRequest(scope) {
const params = new URLSearchParams({ grant_type: 'client_credentials' });
if (scope)
params.set('scope', scope);
return params;
}
}
exports.StaticPrivateKeyJwtProvider = StaticPrivateKeyJwtProvider;
//# sourceMappingURL=auth-extensions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,446 @@
import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js';
import { OAuthError } from '../server/auth/errors.js';
import { FetchLike } from '../shared/transport.js';
/**
* Function type for adding client authentication to token requests.
*/
export type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise<void>;
/**
* Implements an end-to-end OAuth client to be used with one MCP server.
*
* This client relies upon a concept of an authorized "session," the exact
* meaning of which is application-defined. Tokens, authorization codes, and
* code verifiers should not cross different sessions.
*/
export interface OAuthClientProvider {
/**
* The URL to redirect the user agent to after authorization.
* Return undefined for non-interactive flows that don't require user interaction
* (e.g., client_credentials, jwt-bearer).
*/
get redirectUrl(): string | URL | undefined;
/**
* External URL the server should use to fetch client metadata document
*/
clientMetadataUrl?: string;
/**
* Metadata about this OAuth client.
*/
get clientMetadata(): OAuthClientMetadata;
/**
* Returns a OAuth2 state parameter.
*/
state?(): string | Promise<string>;
/**
* Loads information about this OAuth client, as registered already with the
* server, or returns `undefined` if the client is not registered with the
* server.
*/
clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;
/**
* If implemented, this permits the OAuth client to dynamically register with
* the server. Client information saved this way should later be read via
* `clientInformation()`.
*
* This method is not required to be implemented if client information is
* statically known (e.g., pre-registered).
*/
saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise<void>;
/**
* Loads any existing OAuth tokens for the current session, or returns
* `undefined` if there are no saved tokens.
*/
tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;
/**
* Stores new OAuth tokens for the current session, after a successful
* authorization.
*/
saveTokens(tokens: OAuthTokens): void | Promise<void>;
/**
* Invoked to redirect the user agent to the given URL to begin the authorization flow.
*/
redirectToAuthorization(authorizationUrl: URL): void | Promise<void>;
/**
* Saves a PKCE code verifier for the current session, before redirecting to
* the authorization flow.
*/
saveCodeVerifier(codeVerifier: string): void | Promise<void>;
/**
* Loads the PKCE code verifier for the current session, necessary to validate
* the authorization result.
*/
codeVerifier(): string | Promise<string>;
/**
* Adds custom client authentication to OAuth token requests.
*
* This optional method allows implementations to customize how client credentials
* are included in token exchange and refresh requests. When provided, this method
* is called instead of the default authentication logic, giving full control over
* the authentication mechanism.
*
* Common use cases include:
* - Supporting authentication methods beyond the standard OAuth 2.0 methods
* - Adding custom headers for proprietary authentication schemes
* - Implementing client assertion-based authentication (e.g., JWT bearer tokens)
*
* @param headers - The request headers (can be modified to add authentication)
* @param params - The request body parameters (can be modified to add credentials)
* @param url - The token endpoint URL being called
* @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods
*/
addClientAuthentication?: AddClientAuthentication;
/**
* If defined, overrides the selection and validation of the
* RFC 8707 Resource Indicator. If left undefined, default
* validation behavior will be used.
*
* Implementations must verify the returned resource matches the MCP server.
*/
validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;
/**
* If implemented, provides a way for the client to invalidate (e.g. delete) the specified
* credentials, in the case where the server has indicated that they are no longer valid.
* This avoids requiring the user to intervene manually.
*/
invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): void | Promise<void>;
/**
* Prepares grant-specific parameters for a token request.
*
* This optional method allows providers to customize the token request based on
* the grant type they support. When implemented, it returns the grant type and
* any grant-specific parameters needed for the token exchange.
*
* If not implemented, the default behavior depends on the flow:
* - For authorization code flow: uses code, code_verifier, and redirect_uri
* - For client_credentials: detected via grant_types in clientMetadata
*
* @param scope - Optional scope to request
* @returns Grant type and parameters, or undefined to use default behavior
*
* @example
* // For client_credentials grant:
* prepareTokenRequest(scope) {
* return {
* grantType: 'client_credentials',
* params: scope ? { scope } : {}
* };
* }
*
* @example
* // For authorization_code grant (default behavior):
* async prepareTokenRequest() {
* return {
* grantType: 'authorization_code',
* params: {
* code: this.authorizationCode,
* code_verifier: await this.codeVerifier(),
* redirect_uri: String(this.redirectUrl)
* }
* };
* }
*/
prepareTokenRequest?(scope?: string): URLSearchParams | Promise<URLSearchParams | undefined> | undefined;
/**
* Saves the OAuth discovery state after RFC 9728 and authorization server metadata
* discovery. Providers can persist this state to avoid redundant discovery requests
* on subsequent {@linkcode auth} calls.
*
* This state can also be provided out-of-band (e.g., from a previous session or
* external configuration) to bootstrap the OAuth flow without discovery.
*
* Called by {@linkcode auth} after successful discovery.
*/
saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;
/**
* Returns previously saved discovery state, or `undefined` if none is cached.
*
* When available, {@linkcode auth} restores the discovery state (authorization server
* URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing
* latency on subsequent calls.
*
* Providers should clear cached discovery state on repeated authentication failures
* (via {@linkcode invalidateCredentials} with scope `'discovery'` or `'all'`) to allow
* re-discovery in case the authorization server has changed.
*/
discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;
}
/**
* Discovery state that can be persisted across sessions by an {@linkcode OAuthClientProvider}.
*
* Contains the results of RFC 9728 protected resource metadata discovery and
* authorization server metadata discovery. Persisting this state avoids
* redundant discovery HTTP requests on subsequent {@linkcode auth} calls.
*/
export interface OAuthDiscoveryState extends OAuthServerInfo {
/** The URL at which the protected resource metadata was found, if available. */
resourceMetadataUrl?: string;
}
export type AuthResult = 'AUTHORIZED' | 'REDIRECT';
export declare class UnauthorizedError extends Error {
constructor(message?: string);
}
type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';
/**
* Determines the best client authentication method to use based on server support and client configuration.
*
* Priority order (highest to lowest):
* 1. client_secret_basic (if client secret is available)
* 2. client_secret_post (if client secret is available)
* 3. none (for public clients)
*
* @param clientInformation - OAuth client information containing credentials
* @param supportedMethods - Authentication methods supported by the authorization server
* @returns The selected authentication method
*/
export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod;
/**
* Parses an OAuth error response from a string or Response object.
*
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
* and an instance of the appropriate OAuthError subclass will be returned.
* If parsing fails, it falls back to a generic ServerError that includes
* the response status (if available) and original content.
*
* @param input - A Response object or string containing the error response
* @returns A Promise that resolves to an OAuthError instance
*/
export declare function parseErrorResponse(input: Response | string): Promise<OAuthError>;
/**
* Orchestrates the full auth flow with a server.
*
* This can be used as a single entry point for all authorization functionality,
* instead of linking together the other lower-level functions in this module.
*/
export declare function auth(provider: OAuthClientProvider, options: {
serverUrl: string | URL;
authorizationCode?: string;
scope?: string;
resourceMetadataUrl?: URL;
fetchFn?: FetchLike;
}): Promise<AuthResult>;
/**
* SEP-991: URL-based Client IDs
* Validate that the client_id is a valid URL with https scheme
*/
export declare function isHttpsUrl(value?: string): boolean;
export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise<URL | undefined>;
/**
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
*/
export declare function extractWWWAuthenticateParams(res: Response): {
resourceMetadataUrl?: URL;
scope?: string;
error?: string;
};
/**
* Extract resource_metadata from response header.
* @deprecated Use `extractWWWAuthenticateParams` instead.
*/
export declare function extractResourceMetadataUrl(res: Response): URL | undefined;
/**
* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*/
export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: {
protocolVersion?: string;
resourceMetadataUrl?: string | URL;
}, fetchFn?: FetchLike): Promise<OAuthProtectedResourceMetadata>;
/**
* Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*
* @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.
*/
export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: {
authorizationServerUrl?: string | URL;
protocolVersion?: string;
}, fetchFn?: FetchLike): Promise<OAuthMetadata | undefined>;
/**
* Builds a list of discovery URLs to try for authorization server metadata.
* URLs are returned in priority order:
* 1. OAuth metadata at the given URL
* 2. OIDC metadata endpoints at the given URL
*/
export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): {
url: URL;
type: 'oauth' | 'oidc';
}[];
/**
* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
* and OpenID Connect Discovery 1.0 specifications.
*
* This function implements a fallback strategy for authorization server discovery:
* 1. Attempts RFC 8414 OAuth metadata discovery first
* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
*
* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
* protected resource metadata, or the MCP server's URL if the
* metadata was not found.
* @param options - Configuration options
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
*/
export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: {
fetchFn?: FetchLike;
protocolVersion?: string;
}): Promise<AuthorizationServerMetadata | undefined>;
/**
* Result of {@linkcode discoverOAuthServerInfo}.
*/
export interface OAuthServerInfo {
/**
* The authorization server URL, either discovered via RFC 9728
* or derived from the MCP server URL as a fallback.
*/
authorizationServerUrl: string;
/**
* The authorization server metadata (endpoints, capabilities),
* or `undefined` if metadata discovery failed.
*/
authorizationServerMetadata?: AuthorizationServerMetadata;
/**
* The OAuth 2.0 Protected Resource Metadata from RFC 9728,
* or `undefined` if the server does not support it.
*/
resourceMetadata?: OAuthProtectedResourceMetadata;
}
/**
* Discovers the authorization server for an MCP server following
* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
* Resource Metadata), with fallback to treating the server URL as the
* authorization server.
*
* This function combines two discovery steps into one call:
* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
* authorization server URL (RFC 9728).
* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
*
* Use this when you need the authorization server metadata for operations outside the
* {@linkcode auth} orchestrator, such as token refresh or token revocation.
*
* @param serverUrl - The MCP resource server URL
* @param opts - Optional configuration
* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
* @param opts.fetchFn - Custom fetch function for HTTP requests
* @returns Authorization server URL, metadata, and resource metadata (if available)
*/
export declare function discoverOAuthServerInfo(serverUrl: string | URL, opts?: {
resourceMetadataUrl?: URL;
fetchFn?: FetchLike;
}): Promise<OAuthServerInfo>;
/**
* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
*/
export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: {
metadata?: AuthorizationServerMetadata;
clientInformation: OAuthClientInformationMixed;
redirectUrl: string | URL;
scope?: string;
state?: string;
resource?: URL;
}): Promise<{
authorizationUrl: URL;
codeVerifier: string;
}>;
/**
* Prepares token request parameters for an authorization code exchange.
*
* This is the default implementation used by fetchToken when the provider
* doesn't implement prepareTokenRequest.
*
* @param authorizationCode - The authorization code received from the authorization endpoint
* @param codeVerifier - The PKCE code verifier
* @param redirectUri - The redirect URI used in the authorization request
* @returns URLSearchParams for the authorization_code grant
*/
export declare function prepareAuthorizationCodeRequest(authorizationCode: string, codeVerifier: string, redirectUri: string | URL): URLSearchParams;
/**
* Exchanges an authorization code for an access token with the given server.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Falls back to appropriate defaults when server metadata is unavailable
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, auth code, etc.
* @returns Promise resolving to OAuth tokens
* @throws {Error} When token exchange fails or authentication is invalid
*/
export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: {
metadata?: AuthorizationServerMetadata;
clientInformation: OAuthClientInformationMixed;
authorizationCode: string;
codeVerifier: string;
redirectUri: string | URL;
resource?: URL;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}): Promise<OAuthTokens>;
/**
* Exchange a refresh token for an updated access token.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Preserves the original refresh token if a new one is not returned
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, refresh token, etc.
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
* @throws {Error} When token refresh fails or authentication is invalid
*/
export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: {
metadata?: AuthorizationServerMetadata;
clientInformation: OAuthClientInformationMixed;
refreshToken: string;
resource?: URL;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}): Promise<OAuthTokens>;
/**
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
*
* This function provides a single entry point for obtaining tokens regardless of the
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
* to use and supplies the grant-specific parameters.
*
* @param provider - OAuth client provider that implements prepareTokenRequest()
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration for the token request
* @returns Promise resolving to OAuth tokens
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
*
* @example
* // Provider for client_credentials:
* class MyProvider implements OAuthClientProvider {
* prepareTokenRequest(scope) {
* const params = new URLSearchParams({ grant_type: 'client_credentials' });
* if (scope) params.set('scope', scope);
* return params;
* }
* // ... other methods
* }
*
* const tokens = await fetchToken(provider, authServerUrl, { metadata });
*/
export declare function fetchToken(provider: OAuthClientProvider, authorizationServerUrl: string | URL, { metadata, resource, authorizationCode, fetchFn }?: {
metadata?: AuthorizationServerMetadata;
resource?: URL;
/** Authorization code for the default authorization_code grant flow */
authorizationCode?: string;
fetchFn?: FetchLike;
}): Promise<OAuthTokens>;
/**
* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
*/
export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: {
metadata?: AuthorizationServerMetadata;
clientMetadata: OAuthClientMetadata;
fetchFn?: FetchLike;
}): Promise<OAuthClientInformationFull>;
export {};
//# sourceMappingURL=auth.d.ts.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,925 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnauthorizedError = void 0;
exports.selectClientAuthMethod = selectClientAuthMethod;
exports.parseErrorResponse = parseErrorResponse;
exports.auth = auth;
exports.isHttpsUrl = isHttpsUrl;
exports.selectResourceURL = selectResourceURL;
exports.extractWWWAuthenticateParams = extractWWWAuthenticateParams;
exports.extractResourceMetadataUrl = extractResourceMetadataUrl;
exports.discoverOAuthProtectedResourceMetadata = discoverOAuthProtectedResourceMetadata;
exports.discoverOAuthMetadata = discoverOAuthMetadata;
exports.buildDiscoveryUrls = buildDiscoveryUrls;
exports.discoverAuthorizationServerMetadata = discoverAuthorizationServerMetadata;
exports.discoverOAuthServerInfo = discoverOAuthServerInfo;
exports.startAuthorization = startAuthorization;
exports.prepareAuthorizationCodeRequest = prepareAuthorizationCodeRequest;
exports.exchangeAuthorization = exchangeAuthorization;
exports.refreshAuthorization = refreshAuthorization;
exports.fetchToken = fetchToken;
exports.registerClient = registerClient;
const pkce_challenge_1 = __importDefault(require("pkce-challenge"));
const types_js_1 = require("../types.js");
const auth_js_1 = require("../shared/auth.js");
const auth_js_2 = require("../shared/auth.js");
const auth_utils_js_1 = require("../shared/auth-utils.js");
const errors_js_1 = require("../server/auth/errors.js");
class UnauthorizedError extends Error {
constructor(message) {
super(message ?? 'Unauthorized');
}
}
exports.UnauthorizedError = UnauthorizedError;
function isClientAuthMethod(method) {
return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);
}
const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
/**
* Determines the best client authentication method to use based on server support and client configuration.
*
* Priority order (highest to lowest):
* 1. client_secret_basic (if client secret is available)
* 2. client_secret_post (if client secret is available)
* 3. none (for public clients)
*
* @param clientInformation - OAuth client information containing credentials
* @param supportedMethods - Authentication methods supported by the authorization server
* @returns The selected authentication method
*/
function selectClientAuthMethod(clientInformation, supportedMethods) {
const hasClientSecret = clientInformation.client_secret !== undefined;
// If server doesn't specify supported methods, use RFC 6749 defaults
if (supportedMethods.length === 0) {
return hasClientSecret ? 'client_secret_post' : 'none';
}
// Prefer the method returned by the server during client registration if valid and supported
if ('token_endpoint_auth_method' in clientInformation &&
clientInformation.token_endpoint_auth_method &&
isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&
supportedMethods.includes(clientInformation.token_endpoint_auth_method)) {
return clientInformation.token_endpoint_auth_method;
}
// Try methods in priority order (most secure first)
if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {
return 'client_secret_basic';
}
if (hasClientSecret && supportedMethods.includes('client_secret_post')) {
return 'client_secret_post';
}
if (supportedMethods.includes('none')) {
return 'none';
}
// Fallback: use what we have
return hasClientSecret ? 'client_secret_post' : 'none';
}
/**
* Applies client authentication to the request based on the specified method.
*
* Implements OAuth 2.1 client authentication methods:
* - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
* - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
* - none: Public client authentication (RFC 6749 Section 2.1)
*
* @param method - The authentication method to use
* @param clientInformation - OAuth client information containing credentials
* @param headers - HTTP headers object to modify
* @param params - URL search parameters to modify
* @throws {Error} When required credentials are missing
*/
function applyClientAuthentication(method, clientInformation, headers, params) {
const { client_id, client_secret } = clientInformation;
switch (method) {
case 'client_secret_basic':
applyBasicAuth(client_id, client_secret, headers);
return;
case 'client_secret_post':
applyPostAuth(client_id, client_secret, params);
return;
case 'none':
applyPublicAuth(client_id, params);
return;
default:
throw new Error(`Unsupported client authentication method: ${method}`);
}
}
/**
* Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
*/
function applyBasicAuth(clientId, clientSecret, headers) {
if (!clientSecret) {
throw new Error('client_secret_basic authentication requires a client_secret');
}
const credentials = btoa(`${clientId}:${clientSecret}`);
headers.set('Authorization', `Basic ${credentials}`);
}
/**
* Applies POST body authentication (RFC 6749 Section 2.3.1)
*/
function applyPostAuth(clientId, clientSecret, params) {
params.set('client_id', clientId);
if (clientSecret) {
params.set('client_secret', clientSecret);
}
}
/**
* Applies public client authentication (RFC 6749 Section 2.1)
*/
function applyPublicAuth(clientId, params) {
params.set('client_id', clientId);
}
/**
* Parses an OAuth error response from a string or Response object.
*
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
* and an instance of the appropriate OAuthError subclass will be returned.
* If parsing fails, it falls back to a generic ServerError that includes
* the response status (if available) and original content.
*
* @param input - A Response object or string containing the error response
* @returns A Promise that resolves to an OAuthError instance
*/
async function parseErrorResponse(input) {
const statusCode = input instanceof Response ? input.status : undefined;
const body = input instanceof Response ? await input.text() : input;
try {
const result = auth_js_1.OAuthErrorResponseSchema.parse(JSON.parse(body));
const { error, error_description, error_uri } = result;
const errorClass = errors_js_1.OAUTH_ERRORS[error] || errors_js_1.ServerError;
return new errorClass(error_description || '', error_uri);
}
catch (error) {
// Not a valid OAuth error response, but try to inform the user of the raw data anyway
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;
return new errors_js_1.ServerError(errorMessage);
}
}
/**
* Orchestrates the full auth flow with a server.
*
* This can be used as a single entry point for all authorization functionality,
* instead of linking together the other lower-level functions in this module.
*/
async function auth(provider, options) {
try {
return await authInternal(provider, options);
}
catch (error) {
// Handle recoverable error types by invalidating credentials and retrying
if (error instanceof errors_js_1.InvalidClientError || error instanceof errors_js_1.UnauthorizedClientError) {
await provider.invalidateCredentials?.('all');
return await authInternal(provider, options);
}
else if (error instanceof errors_js_1.InvalidGrantError) {
await provider.invalidateCredentials?.('tokens');
return await authInternal(provider, options);
}
// Throw otherwise
throw error;
}
}
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
// Check if the provider has cached discovery state to skip discovery
const cachedState = await provider.discoveryState?.();
let resourceMetadata;
let authorizationServerUrl;
let metadata;
// If resourceMetadataUrl is not provided, try to load it from cached state
// This handles browser redirects where the URL was saved before navigation
let effectiveResourceMetadataUrl = resourceMetadataUrl;
if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
}
if (cachedState?.authorizationServerUrl) {
// Restore discovery state from cache
authorizationServerUrl = cachedState.authorizationServerUrl;
resourceMetadata = cachedState.resourceMetadata;
metadata =
cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }));
// If resource metadata wasn't cached, try to fetch it for selectResourceURL
if (!resourceMetadata) {
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
}
catch {
// RFC 9728 not available — selectResourceURL will handle undefined
}
}
// Re-save if we enriched the cached state with missing metadata
if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
await provider.saveDiscoveryState?.({
authorizationServerUrl: String(authorizationServerUrl),
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
resourceMetadata,
authorizationServerMetadata: metadata
});
}
}
else {
// Full discovery via RFC 9728
const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
authorizationServerUrl = serverInfo.authorizationServerUrl;
metadata = serverInfo.authorizationServerMetadata;
resourceMetadata = serverInfo.resourceMetadata;
// Persist discovery state for future use
// TODO: resourceMetadataUrl is only populated when explicitly provided via options
// or loaded from cached state. The URL derived internally by
// discoverOAuthProtectedResourceMetadata() is not captured back here.
await provider.saveDiscoveryState?.({
authorizationServerUrl: String(authorizationServerUrl),
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
resourceMetadata,
authorizationServerMetadata: metadata
});
}
const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
// Handle client registration if needed
let clientInformation = await Promise.resolve(provider.clientInformation());
if (!clientInformation) {
if (authorizationCode !== undefined) {
throw new Error('Existing OAuth client information is required when exchanging an authorization code');
}
const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
const clientMetadataUrl = provider.clientMetadataUrl;
if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
throw new errors_js_1.InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
}
const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
if (shouldUseUrlBasedClientId) {
// SEP-991: URL-based Client IDs
clientInformation = {
client_id: clientMetadataUrl
};
await provider.saveClientInformation?.(clientInformation);
}
else {
// Fallback to dynamic registration
if (!provider.saveClientInformation) {
throw new Error('OAuth client information must be saveable for dynamic registration');
}
const fullInformation = await registerClient(authorizationServerUrl, {
metadata,
clientMetadata: provider.clientMetadata,
fetchFn
});
await provider.saveClientInformation(fullInformation);
clientInformation = fullInformation;
}
}
// Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL
const nonInteractiveFlow = !provider.redirectUrl;
// Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows
if (authorizationCode !== undefined || nonInteractiveFlow) {
const tokens = await fetchToken(provider, authorizationServerUrl, {
metadata,
resource,
authorizationCode,
fetchFn
});
await provider.saveTokens(tokens);
return 'AUTHORIZED';
}
const tokens = await provider.tokens();
// Handle token refresh or new authorization
if (tokens?.refresh_token) {
try {
// Attempt to refresh the token
const newTokens = await refreshAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
refreshToken: tokens.refresh_token,
resource,
addClientAuthentication: provider.addClientAuthentication,
fetchFn
});
await provider.saveTokens(newTokens);
return 'AUTHORIZED';
}
catch (error) {
// If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
if (!(error instanceof errors_js_1.OAuthError) || error instanceof errors_js_1.ServerError) {
// Could not refresh OAuth tokens
}
else {
// Refresh failed for another reason, re-throw
throw error;
}
}
}
const state = provider.state ? await provider.state() : undefined;
// Start new authorization flow
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
state,
redirectUrl: provider.redirectUrl,
scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope,
resource
});
await provider.saveCodeVerifier(codeVerifier);
await provider.redirectToAuthorization(authorizationUrl);
return 'REDIRECT';
}
/**
* SEP-991: URL-based Client IDs
* Validate that the client_id is a valid URL with https scheme
*/
function isHttpsUrl(value) {
if (!value)
return false;
try {
const url = new URL(value);
return url.protocol === 'https:' && url.pathname !== '/';
}
catch {
return false;
}
}
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
const defaultResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(serverUrl);
// If provider has custom validation, delegate to it
if (provider.validateResourceURL) {
return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
}
// Only include resource parameter when Protected Resource Metadata is present
if (!resourceMetadata) {
return undefined;
}
// Validate that the metadata's resource is compatible with our request
if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
}
// Prefer the resource from metadata since it's what the server is telling us to request
return new URL(resourceMetadata.resource);
}
/**
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
*/
function extractWWWAuthenticateParams(res) {
const authenticateHeader = res.headers.get('WWW-Authenticate');
if (!authenticateHeader) {
return {};
}
const [type, scheme] = authenticateHeader.split(' ');
if (type.toLowerCase() !== 'bearer' || !scheme) {
return {};
}
const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;
let resourceMetadataUrl;
if (resourceMetadataMatch) {
try {
resourceMetadataUrl = new URL(resourceMetadataMatch);
}
catch {
// Ignore invalid URL
}
}
const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;
const error = extractFieldFromWwwAuth(res, 'error') || undefined;
return {
resourceMetadataUrl,
scope,
error
};
}
/**
* Extracts a specific field's value from the WWW-Authenticate header string.
*
* @param response The HTTP response object containing the headers.
* @param fieldName The name of the field to extract (e.g., "realm", "nonce").
* @returns The field value
*/
function extractFieldFromWwwAuth(response, fieldName) {
const wwwAuthHeader = response.headers.get('WWW-Authenticate');
if (!wwwAuthHeader) {
return null;
}
const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
const match = wwwAuthHeader.match(pattern);
if (match) {
// Pattern matches: field_name="value" or field_name=value (unquoted)
return match[1] || match[2];
}
return null;
}
/**
* Extract resource_metadata from response header.
* @deprecated Use `extractWWWAuthenticateParams` instead.
*/
function extractResourceMetadataUrl(res) {
const authenticateHeader = res.headers.get('WWW-Authenticate');
if (!authenticateHeader) {
return undefined;
}
const [type, scheme] = authenticateHeader.split(' ');
if (type.toLowerCase() !== 'bearer' || !scheme) {
return undefined;
}
const regex = /resource_metadata="([^"]*)"/;
const match = regex.exec(authenticateHeader);
if (!match) {
return undefined;
}
try {
return new URL(match[1]);
}
catch {
return undefined;
}
}
/**
* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*/
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {
protocolVersion: opts?.protocolVersion,
metadataUrl: opts?.resourceMetadataUrl
});
if (!response || response.status === 404) {
await response?.body?.cancel();
throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
}
return auth_js_2.OAuthProtectedResourceMetadataSchema.parse(await response.json());
}
/**
* Helper function to handle fetch with CORS retry logic
*/
async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
try {
return await fetchFn(url, { headers });
}
catch (error) {
if (error instanceof TypeError) {
if (headers) {
// CORS errors come back as TypeError, retry without headers
return fetchWithCorsRetry(url, undefined, fetchFn);
}
else {
// We're getting CORS errors on retry too, return undefined
return undefined;
}
}
throw error;
}
}
/**
* Constructs the well-known path for auth-related metadata discovery
*/
function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {
// Strip trailing slash from pathname to avoid double slashes
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
}
/**
* Tries to discover OAuth metadata at a specific URL
*/
async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
const headers = {
'MCP-Protocol-Version': protocolVersion
};
return await fetchWithCorsRetry(url, headers, fetchFn);
}
/**
* Determines if fallback to root discovery should be attempted
*/
function shouldAttemptFallback(response, pathname) {
return !response || (response.status >= 400 && response.status < 500 && pathname !== '/');
}
/**
* Generic function for discovering OAuth metadata with fallback support
*/
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
const issuer = new URL(serverUrl);
const protocolVersion = opts?.protocolVersion ?? types_js_1.LATEST_PROTOCOL_VERSION;
let url;
if (opts?.metadataUrl) {
url = new URL(opts.metadataUrl);
}
else {
// Try path-aware discovery first
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
url.search = issuer.search;
}
let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
// If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery
if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
}
return response;
}
/**
* Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*
* @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.
*/
async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {
if (typeof issuer === 'string') {
issuer = new URL(issuer);
}
if (!authorizationServerUrl) {
authorizationServerUrl = issuer;
}
if (typeof authorizationServerUrl === 'string') {
authorizationServerUrl = new URL(authorizationServerUrl);
}
protocolVersion ?? (protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION);
const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {
protocolVersion,
metadataServerUrl: authorizationServerUrl
});
if (!response || response.status === 404) {
await response?.body?.cancel();
return undefined;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);
}
return auth_js_2.OAuthMetadataSchema.parse(await response.json());
}
/**
* Builds a list of discovery URLs to try for authorization server metadata.
* URLs are returned in priority order:
* 1. OAuth metadata at the given URL
* 2. OIDC metadata endpoints at the given URL
*/
function buildDiscoveryUrls(authorizationServerUrl) {
const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;
const hasPath = url.pathname !== '/';
const urlsToTry = [];
if (!hasPath) {
// Root path: https://example.com/.well-known/oauth-authorization-server
urlsToTry.push({
url: new URL('/.well-known/oauth-authorization-server', url.origin),
type: 'oauth'
});
// OIDC: https://example.com/.well-known/openid-configuration
urlsToTry.push({
url: new URL(`/.well-known/openid-configuration`, url.origin),
type: 'oidc'
});
return urlsToTry;
}
// Strip trailing slash from pathname to avoid double slashes
let pathname = url.pathname;
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
// 1. OAuth metadata at the given URL
// Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1
urlsToTry.push({
url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
type: 'oauth'
});
// 2. OIDC metadata endpoints
// RFC 8414 style: Insert /.well-known/openid-configuration before the path
urlsToTry.push({
url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
type: 'oidc'
});
// OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path
urlsToTry.push({
url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
type: 'oidc'
});
return urlsToTry;
}
/**
* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
* and OpenID Connect Discovery 1.0 specifications.
*
* This function implements a fallback strategy for authorization server discovery:
* 1. Attempts RFC 8414 OAuth metadata discovery first
* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
*
* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
* protected resource metadata, or the MCP server's URL if the
* metadata was not found.
* @param options - Configuration options
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
*/
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION } = {}) {
const headers = {
'MCP-Protocol-Version': protocolVersion,
Accept: 'application/json'
};
// Get the list of URLs to try
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
// Try each URL in order
for (const { url: endpointUrl, type } of urlsToTry) {
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
if (!response) {
/**
* CORS error occurred - don't throw as the endpoint may not allow CORS,
* continue trying other possible endpoints
*/
continue;
}
if (!response.ok) {
await response.body?.cancel();
// Continue looking for any 4xx response code.
if (response.status >= 400 && response.status < 500) {
continue; // Try next URL
}
throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);
}
// Parse and validate based on type
if (type === 'oauth') {
return auth_js_2.OAuthMetadataSchema.parse(await response.json());
}
else {
return auth_js_1.OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
}
}
return undefined;
}
/**
* Discovers the authorization server for an MCP server following
* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
* Resource Metadata), with fallback to treating the server URL as the
* authorization server.
*
* This function combines two discovery steps into one call:
* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
* authorization server URL (RFC 9728).
* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
*
* Use this when you need the authorization server metadata for operations outside the
* {@linkcode auth} orchestrator, such as token refresh or token revocation.
*
* @param serverUrl - The MCP resource server URL
* @param opts - Optional configuration
* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
* @param opts.fetchFn - Custom fetch function for HTTP requests
* @returns Authorization server URL, metadata, and resource metadata (if available)
*/
async function discoverOAuthServerInfo(serverUrl, opts) {
let resourceMetadata;
let authorizationServerUrl;
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
authorizationServerUrl = resourceMetadata.authorization_servers[0];
}
}
catch {
// RFC 9728 not supported -- fall back to treating the server URL as the authorization server
}
// If we don't get a valid authorization server from protected resource metadata,
// fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server
if (!authorizationServerUrl) {
authorizationServerUrl = String(new URL('/', serverUrl));
}
const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
return {
authorizationServerUrl,
authorizationServerMetadata,
resourceMetadata
};
}
/**
* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
*/
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
let authorizationUrl;
if (metadata) {
authorizationUrl = new URL(metadata.authorization_endpoint);
if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
}
if (metadata.code_challenge_methods_supported &&
!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
}
}
else {
authorizationUrl = new URL('/authorize', authorizationServerUrl);
}
// Generate PKCE challenge
const challenge = await (0, pkce_challenge_1.default)();
const codeVerifier = challenge.code_verifier;
const codeChallenge = challenge.code_challenge;
authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);
authorizationUrl.searchParams.set('client_id', clientInformation.client_id);
authorizationUrl.searchParams.set('code_challenge', codeChallenge);
authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);
authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));
if (state) {
authorizationUrl.searchParams.set('state', state);
}
if (scope) {
authorizationUrl.searchParams.set('scope', scope);
}
if (scope?.includes('offline_access')) {
// if the request includes the OIDC-only "offline_access" scope,
// we need to set the prompt to "consent" to ensure the user is prompted to grant offline access
// https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
authorizationUrl.searchParams.append('prompt', 'consent');
}
if (resource) {
authorizationUrl.searchParams.set('resource', resource.href);
}
return { authorizationUrl, codeVerifier };
}
/**
* Prepares token request parameters for an authorization code exchange.
*
* This is the default implementation used by fetchToken when the provider
* doesn't implement prepareTokenRequest.
*
* @param authorizationCode - The authorization code received from the authorization endpoint
* @param codeVerifier - The PKCE code verifier
* @param redirectUri - The redirect URI used in the authorization request
* @returns URLSearchParams for the authorization_code grant
*/
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
return new URLSearchParams({
grant_type: 'authorization_code',
code: authorizationCode,
code_verifier: codeVerifier,
redirect_uri: String(redirectUri)
});
}
/**
* Internal helper to execute a token request with the given parameters.
* Used by exchangeAuthorization, refreshAuthorization, and fetchToken.
*/
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
});
if (resource) {
tokenRequestParams.set('resource', resource.href);
}
if (addClientAuthentication) {
await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
}
else if (clientInformation) {
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
}
const response = await (fetchFn ?? fetch)(tokenUrl, {
method: 'POST',
headers,
body: tokenRequestParams
});
if (!response.ok) {
throw await parseErrorResponse(response);
}
return auth_js_2.OAuthTokensSchema.parse(await response.json());
}
/**
* Exchanges an authorization code for an access token with the given server.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Falls back to appropriate defaults when server metadata is unavailable
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, auth code, etc.
* @returns Promise resolving to OAuth tokens
* @throws {Error} When token exchange fails or authentication is invalid
*/
async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);
return executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation,
addClientAuthentication,
resource,
fetchFn
});
}
/**
* Exchange a refresh token for an updated access token.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Preserves the original refresh token if a new one is not returned
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, refresh token, etc.
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
* @throws {Error} When token refresh fails or authentication is invalid
*/
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
const tokenRequestParams = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken
});
const tokens = await executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation,
addClientAuthentication,
resource,
fetchFn
});
// Preserve original refresh token if server didn't return a new one
return { refresh_token: refreshToken, ...tokens };
}
/**
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
*
* This function provides a single entry point for obtaining tokens regardless of the
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
* to use and supplies the grant-specific parameters.
*
* @param provider - OAuth client provider that implements prepareTokenRequest()
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration for the token request
* @returns Promise resolving to OAuth tokens
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
*
* @example
* // Provider for client_credentials:
* class MyProvider implements OAuthClientProvider {
* prepareTokenRequest(scope) {
* const params = new URLSearchParams({ grant_type: 'client_credentials' });
* if (scope) params.set('scope', scope);
* return params;
* }
* // ... other methods
* }
*
* const tokens = await fetchToken(provider, authServerUrl, { metadata });
*/
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
const scope = provider.clientMetadata.scope;
// Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code
let tokenRequestParams;
if (provider.prepareTokenRequest) {
tokenRequestParams = await provider.prepareTokenRequest(scope);
}
// Default to authorization_code grant if no custom prepareTokenRequest
if (!tokenRequestParams) {
if (!authorizationCode) {
throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');
}
if (!provider.redirectUrl) {
throw new Error('redirectUrl is required for authorization_code flow');
}
const codeVerifier = await provider.codeVerifier();
tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
}
const clientInformation = await provider.clientInformation();
return executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation: clientInformation ?? undefined,
addClientAuthentication: provider.addClientAuthentication,
resource,
fetchFn
});
}
/**
* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
*/
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {
let registrationUrl;
if (metadata) {
if (!metadata.registration_endpoint) {
throw new Error('Incompatible auth server: does not support dynamic client registration');
}
registrationUrl = new URL(metadata.registration_endpoint);
}
else {
registrationUrl = new URL('/register', authorizationServerUrl);
}
const response = await (fetchFn ?? fetch)(registrationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(clientMetadata)
});
if (!response.ok) {
throw await parseErrorResponse(response);
}
return auth_js_2.OAuthClientInformationFullSchema.parse(await response.json());
}
//# sourceMappingURL=auth.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,588 @@
import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js';
import type { Transport } from '../shared/transport.js';
import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type ReadResourceRequest, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest, type ListChangedHandlers, type Request, type Notification, type Result } from '../types.js';
import type { jsonSchemaValidator } from '../validation/types.js';
import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js';
import type { RequestHandlerExtra } from '../shared/protocol.js';
import { ExperimentalClientTasks } from '../experimental/tasks/client.js';
/**
* Determines which elicitation modes are supported based on declared client capabilities.
*
* According to the spec:
* - An empty elicitation capability object defaults to form mode support (backwards compatibility)
* - URL mode is only supported if explicitly declared
*
* @param capabilities - The client's elicitation capabilities
* @returns An object indicating which modes are supported
*/
export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): {
supportsFormMode: boolean;
supportsUrlMode: boolean;
};
export type ClientOptions = ProtocolOptions & {
/**
* Capabilities to advertise as being supported by this client.
*/
capabilities?: ClientCapabilities;
/**
* JSON Schema validator for tool output validation.
*
* The validator is used to validate structured content returned by tools
* against their declared output schemas.
*
* @default AjvJsonSchemaValidator
*
* @example
* ```typescript
* // ajv
* const client = new Client(
* { name: 'my-client', version: '1.0.0' },
* {
* capabilities: {},
* jsonSchemaValidator: new AjvJsonSchemaValidator()
* }
* );
*
* // @cfworker/json-schema
* const client = new Client(
* { name: 'my-client', version: '1.0.0' },
* {
* capabilities: {},
* jsonSchemaValidator: new CfWorkerJsonSchemaValidator()
* }
* );
* ```
*/
jsonSchemaValidator?: jsonSchemaValidator;
/**
* Configure handlers for list changed notifications (tools, prompts, resources).
*
* @example
* ```typescript
* const client = new Client(
* { name: 'my-client', version: '1.0.0' },
* {
* listChanged: {
* tools: {
* onChanged: (error, tools) => {
* if (error) {
* console.error('Failed to refresh tools:', error);
* return;
* }
* console.log('Tools updated:', tools);
* }
* },
* prompts: {
* onChanged: (error, prompts) => console.log('Prompts updated:', prompts)
* }
* }
* }
* );
* ```
*/
listChanged?: ListChangedHandlers;
};
/**
* An MCP client on top of a pluggable transport.
*
* The client will automatically begin the initialization flow with the server when connect() is called.
*
* To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
*
* ```typescript
* // Custom schemas
* const CustomRequestSchema = RequestSchema.extend({...})
* const CustomNotificationSchema = NotificationSchema.extend({...})
* const CustomResultSchema = ResultSchema.extend({...})
*
* // Type aliases
* type CustomRequest = z.infer<typeof CustomRequestSchema>
* type CustomNotification = z.infer<typeof CustomNotificationSchema>
* type CustomResult = z.infer<typeof CustomResultSchema>
*
* // Create typed client
* const client = new Client<CustomRequest, CustomNotification, CustomResult>({
* name: "CustomClient",
* version: "1.0.0"
* })
* ```
*/
export declare class Client<RequestT extends Request = Request, NotificationT extends Notification = Notification, ResultT extends Result = Result> extends Protocol<ClientRequest | RequestT, ClientNotification | NotificationT, ClientResult | ResultT> {
private _clientInfo;
private _serverCapabilities?;
private _serverVersion?;
private _capabilities;
private _instructions?;
private _jsonSchemaValidator;
private _cachedToolOutputValidators;
private _cachedKnownTaskTools;
private _cachedRequiredTaskTools;
private _experimental?;
private _listChangedDebounceTimers;
private _pendingListChangedConfig?;
/**
* Initializes this client with the given name and version information.
*/
constructor(_clientInfo: Implementation, options?: ClientOptions);
/**
* Set up handlers for list changed notifications based on config and server capabilities.
* This should only be called after initialization when server capabilities are known.
* Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
* @internal
*/
private _setupListChangedHandlers;
/**
* Access experimental features.
*
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
get experimental(): {
tasks: ExperimentalClientTasks<RequestT, NotificationT, ResultT>;
};
/**
* Registers new capabilities. This can only be called before connecting to a transport.
*
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
*/
registerCapabilities(capabilities: ClientCapabilities): void;
/**
* Override request handler registration to enforce client-side validation for elicitation.
*/
setRequestHandler<T extends AnyObjectSchema>(requestSchema: T, handler: (request: SchemaOutput<T>, extra: RequestHandlerExtra<ClientRequest | RequestT, ClientNotification | NotificationT>) => ClientResult | ResultT | Promise<ClientResult | ResultT>): void;
protected assertCapability(capability: keyof ServerCapabilities, method: string): void;
connect(transport: Transport, options?: RequestOptions): Promise<void>;
/**
* After initialization has completed, this will be populated with the server's reported capabilities.
*/
getServerCapabilities(): ServerCapabilities | undefined;
/**
* After initialization has completed, this will be populated with information about the server's name and version.
*/
getServerVersion(): Implementation | undefined;
/**
* After initialization has completed, this may be populated with information about the server's instructions.
*/
getInstructions(): string | undefined;
protected assertCapabilityForMethod(method: RequestT['method']): void;
protected assertNotificationCapability(method: NotificationT['method']): void;
protected assertRequestHandlerCapability(method: string): void;
protected assertTaskCapability(method: string): void;
protected assertTaskHandlerCapability(method: string): void;
ping(options?: RequestOptions): Promise<{
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
completion: {
[x: string]: unknown;
values: string[];
total?: number | undefined;
hasMore?: boolean | undefined;
};
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
messages: {
role: "user" | "assistant";
content: {
type: "text";
text: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "image";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "audio";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "resource";
resource: {
uri: string;
text: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
blob: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
};
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
name: string;
type: "resource_link";
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[x: string]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
};
}[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
description?: string | undefined;
}>;
listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
prompts: {
name: string;
description?: string | undefined;
arguments?: {
name: string;
description?: string | undefined;
required?: boolean | undefined;
}[] | undefined;
_meta?: {
[x: string]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
resources: {
uri: string;
name: string;
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[x: string]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
resourceTemplates: {
uriTemplate: string;
name: string;
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[x: string]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
contents: ({
uri: string;
text: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
blob: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
})[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
/**
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
*
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
*/
callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{
[x: string]: unknown;
content: ({
type: "text";
text: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "image";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "audio";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "resource";
resource: {
uri: string;
text: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
blob: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
};
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
name: string;
type: "resource_link";
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[x: string]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
})[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
structuredContent?: Record<string, unknown> | undefined;
isError?: boolean | undefined;
} | {
[x: string]: unknown;
toolResult: unknown;
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
private isToolTask;
/**
* Check if a tool requires task-based execution.
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
*/
private isToolTaskRequired;
/**
* Cache validators for tool output schemas.
* Called after listTools() to pre-compile validators for better performance.
*/
private cacheToolMetadata;
/**
* Get cached validator for a tool
*/
private getToolOutputValidator;
listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{
[x: string]: unknown;
tools: {
inputSchema: {
[x: string]: unknown;
type: "object";
properties?: Record<string, object> | undefined;
required?: string[] | undefined;
};
name: string;
description?: string | undefined;
outputSchema?: {
[x: string]: unknown;
type: "object";
properties?: Record<string, object> | undefined;
required?: string[] | undefined;
} | undefined;
annotations?: {
title?: string | undefined;
readOnlyHint?: boolean | undefined;
destructiveHint?: boolean | undefined;
idempotentHint?: boolean | undefined;
openWorldHint?: boolean | undefined;
} | undefined;
execution?: {
taskSupport?: "optional" | "required" | "forbidden" | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[x: string]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
/**
* Set up a single list changed handler.
* @internal
*/
private _setupListChangedHandler;
sendRootsListChanged(): Promise<void>;
}
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,iCAAiC,EACtC,KAAK,eAAe,EAIpB,KAAK,gBAAgB,EAErB,KAAK,cAAc,EAGnB,KAAK,kBAAkB,EAEvB,KAAK,oBAAoB,EAEzB,KAAK,4BAA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AAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAI/F,YAAY,CAAC,MAAM,EAAE,mBAAmB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;IAI5E,iBAAiB,CAAC,MAAM,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI9E,mBAAmB,CAAC,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAIxF;;;;OAIG;IACG,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkD5B,OAAO,CAAC,UAAU;IAQlB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAI1B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAuBzB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAS7E;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAwD1B,oBAAoB;CAG7B"}

View File

@@ -0,0 +1,629 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
exports.getSupportedElicitationModes = getSupportedElicitationModes;
const protocol_js_1 = require("../shared/protocol.js");
const types_js_1 = require("../types.js");
const ajv_provider_js_1 = require("../validation/ajv-provider.js");
const zod_compat_js_1 = require("../server/zod-compat.js");
const client_js_1 = require("../experimental/tasks/client.js");
const helpers_js_1 = require("../experimental/tasks/helpers.js");
/**
* Elicitation default application helper. Applies defaults to the data based on the schema.
*
* @param schema - The schema to apply defaults to.
* @param data - The data to apply defaults to.
*/
function applyElicitationDefaults(schema, data) {
if (!schema || data === null || typeof data !== 'object')
return;
// Handle object properties
if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {
const obj = data;
const props = schema.properties;
for (const key of Object.keys(props)) {
const propSchema = props[key];
// If missing or explicitly undefined, apply default if present
if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {
obj[key] = propSchema.default;
}
// Recurse into existing nested objects/arrays
if (obj[key] !== undefined) {
applyElicitationDefaults(propSchema, obj[key]);
}
}
}
if (Array.isArray(schema.anyOf)) {
for (const sub of schema.anyOf) {
// Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)
if (typeof sub !== 'boolean') {
applyElicitationDefaults(sub, data);
}
}
}
// Combine schemas
if (Array.isArray(schema.oneOf)) {
for (const sub of schema.oneOf) {
// Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)
if (typeof sub !== 'boolean') {
applyElicitationDefaults(sub, data);
}
}
}
}
/**
* Determines which elicitation modes are supported based on declared client capabilities.
*
* According to the spec:
* - An empty elicitation capability object defaults to form mode support (backwards compatibility)
* - URL mode is only supported if explicitly declared
*
* @param capabilities - The client's elicitation capabilities
* @returns An object indicating which modes are supported
*/
function getSupportedElicitationModes(capabilities) {
if (!capabilities) {
return { supportsFormMode: false, supportsUrlMode: false };
}
const hasFormCapability = capabilities.form !== undefined;
const hasUrlCapability = capabilities.url !== undefined;
// If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)
const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);
const supportsUrlMode = hasUrlCapability;
return { supportsFormMode, supportsUrlMode };
}
/**
* An MCP client on top of a pluggable transport.
*
* The client will automatically begin the initialization flow with the server when connect() is called.
*
* To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
*
* ```typescript
* // Custom schemas
* const CustomRequestSchema = RequestSchema.extend({...})
* const CustomNotificationSchema = NotificationSchema.extend({...})
* const CustomResultSchema = ResultSchema.extend({...})
*
* // Type aliases
* type CustomRequest = z.infer<typeof CustomRequestSchema>
* type CustomNotification = z.infer<typeof CustomNotificationSchema>
* type CustomResult = z.infer<typeof CustomResultSchema>
*
* // Create typed client
* const client = new Client<CustomRequest, CustomNotification, CustomResult>({
* name: "CustomClient",
* version: "1.0.0"
* })
* ```
*/
class Client extends protocol_js_1.Protocol {
/**
* Initializes this client with the given name and version information.
*/
constructor(_clientInfo, options) {
super(options);
this._clientInfo = _clientInfo;
this._cachedToolOutputValidators = new Map();
this._cachedKnownTaskTools = new Set();
this._cachedRequiredTaskTools = new Set();
this._listChangedDebounceTimers = new Map();
this._capabilities = options?.capabilities ?? {};
this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new ajv_provider_js_1.AjvJsonSchemaValidator();
// Store list changed config for setup after connection (when we know server capabilities)
if (options?.listChanged) {
this._pendingListChangedConfig = options.listChanged;
}
}
/**
* Set up handlers for list changed notifications based on config and server capabilities.
* This should only be called after initialization when server capabilities are known.
* Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
* @internal
*/
_setupListChangedHandlers(config) {
if (config.tools && this._serverCapabilities?.tools?.listChanged) {
this._setupListChangedHandler('tools', types_js_1.ToolListChangedNotificationSchema, config.tools, async () => {
const result = await this.listTools();
return result.tools;
});
}
if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
this._setupListChangedHandler('prompts', types_js_1.PromptListChangedNotificationSchema, config.prompts, async () => {
const result = await this.listPrompts();
return result.prompts;
});
}
if (config.resources && this._serverCapabilities?.resources?.listChanged) {
this._setupListChangedHandler('resources', types_js_1.ResourceListChangedNotificationSchema, config.resources, async () => {
const result = await this.listResources();
return result.resources;
});
}
}
/**
* Access experimental features.
*
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
get experimental() {
if (!this._experimental) {
this._experimental = {
tasks: new client_js_1.ExperimentalClientTasks(this)
};
}
return this._experimental;
}
/**
* Registers new capabilities. This can only be called before connecting to a transport.
*
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
*/
registerCapabilities(capabilities) {
if (this.transport) {
throw new Error('Cannot register capabilities after connecting to transport');
}
this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities);
}
/**
* Override request handler registration to enforce client-side validation for elicitation.
*/
setRequestHandler(requestSchema, handler) {
const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema);
const methodSchema = shape?.method;
if (!methodSchema) {
throw new Error('Schema is missing a method literal');
}
// Extract literal value using type-safe property access
let methodValue;
if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) {
const v4Schema = methodSchema;
const v4Def = v4Schema._zod?.def;
methodValue = v4Def?.value ?? v4Schema.value;
}
else {
const v3Schema = methodSchema;
const legacyDef = v3Schema._def;
methodValue = legacyDef?.value ?? v3Schema.value;
}
if (typeof methodValue !== 'string') {
throw new Error('Schema method literal must be a string');
}
const method = methodValue;
if (method === 'elicitation/create') {
const wrappedHandler = async (request, extra) => {
const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitRequestSchema, request);
if (!validatedRequest.success) {
// Type guard: if success is false, error is guaranteed to exist
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
}
const { params } = validatedRequest.data;
params.mode = params.mode ?? 'form';
const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
if (params.mode === 'form' && !supportsFormMode) {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');
}
if (params.mode === 'url' && !supportsUrlMode) {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');
}
const result = await Promise.resolve(handler(request, extra));
// When task creation is requested, validate and return CreateTaskResult
if (params.task) {
const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result);
if (!taskValidationResult.success) {
const errorMessage = taskValidationResult.error instanceof Error
? taskValidationResult.error.message
: String(taskValidationResult.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
}
return taskValidationResult.data;
}
// For non-task requests, validate against ElicitResultSchema
const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitResultSchema, result);
if (!validationResult.success) {
// Type guard: if success is false, error is guaranteed to exist
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
}
const validatedResult = validationResult.data;
const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;
if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {
if (this._capabilities.elicitation?.form?.applyDefaults) {
try {
applyElicitationDefaults(requestedSchema, validatedResult.content);
}
catch {
// gracefully ignore errors in default application
}
}
}
return validatedResult;
};
// Install the wrapped handler
return super.setRequestHandler(requestSchema, wrappedHandler);
}
if (method === 'sampling/createMessage') {
const wrappedHandler = async (request, extra) => {
const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.CreateMessageRequestSchema, request);
if (!validatedRequest.success) {
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
}
const { params } = validatedRequest.data;
const result = await Promise.resolve(handler(request, extra));
// When task creation is requested, validate and return CreateTaskResult
if (params.task) {
const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result);
if (!taskValidationResult.success) {
const errorMessage = taskValidationResult.error instanceof Error
? taskValidationResult.error.message
: String(taskValidationResult.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
}
return taskValidationResult.data;
}
// For non-task requests, validate against appropriate schema based on tools presence
const hasTools = params.tools || params.toolChoice;
const resultSchema = hasTools ? types_js_1.CreateMessageResultWithToolsSchema : types_js_1.CreateMessageResultSchema;
const validationResult = (0, zod_compat_js_1.safeParse)(resultSchema, result);
if (!validationResult.success) {
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
}
return validationResult.data;
};
// Install the wrapped handler
return super.setRequestHandler(requestSchema, wrappedHandler);
}
// Other handlers use default behavior
return super.setRequestHandler(requestSchema, handler);
}
assertCapability(capability, method) {
if (!this._serverCapabilities?.[capability]) {
throw new Error(`Server does not support ${capability} (required for ${method})`);
}
}
async connect(transport, options) {
await super.connect(transport);
// When transport sessionId is already set this means we are trying to reconnect.
// In this case we don't need to initialize again.
if (transport.sessionId !== undefined) {
return;
}
try {
const result = await this.request({
method: 'initialize',
params: {
protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION,
capabilities: this._capabilities,
clientInfo: this._clientInfo
}
}, types_js_1.InitializeResultSchema, options);
if (result === undefined) {
throw new Error(`Server sent invalid initialize result: ${result}`);
}
if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
}
this._serverCapabilities = result.capabilities;
this._serverVersion = result.serverInfo;
// HTTP transports must set the protocol version in each header after initialization.
if (transport.setProtocolVersion) {
transport.setProtocolVersion(result.protocolVersion);
}
this._instructions = result.instructions;
await this.notification({
method: 'notifications/initialized'
});
// Set up list changed handlers now that we know server capabilities
if (this._pendingListChangedConfig) {
this._setupListChangedHandlers(this._pendingListChangedConfig);
this._pendingListChangedConfig = undefined;
}
}
catch (error) {
// Disconnect if initialization fails.
void this.close();
throw error;
}
}
/**
* After initialization has completed, this will be populated with the server's reported capabilities.
*/
getServerCapabilities() {
return this._serverCapabilities;
}
/**
* After initialization has completed, this will be populated with information about the server's name and version.
*/
getServerVersion() {
return this._serverVersion;
}
/**
* After initialization has completed, this may be populated with information about the server's instructions.
*/
getInstructions() {
return this._instructions;
}
assertCapabilityForMethod(method) {
switch (method) {
case 'logging/setLevel':
if (!this._serverCapabilities?.logging) {
throw new Error(`Server does not support logging (required for ${method})`);
}
break;
case 'prompts/get':
case 'prompts/list':
if (!this._serverCapabilities?.prompts) {
throw new Error(`Server does not support prompts (required for ${method})`);
}
break;
case 'resources/list':
case 'resources/templates/list':
case 'resources/read':
case 'resources/subscribe':
case 'resources/unsubscribe':
if (!this._serverCapabilities?.resources) {
throw new Error(`Server does not support resources (required for ${method})`);
}
if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {
throw new Error(`Server does not support resource subscriptions (required for ${method})`);
}
break;
case 'tools/call':
case 'tools/list':
if (!this._serverCapabilities?.tools) {
throw new Error(`Server does not support tools (required for ${method})`);
}
break;
case 'completion/complete':
if (!this._serverCapabilities?.completions) {
throw new Error(`Server does not support completions (required for ${method})`);
}
break;
case 'initialize':
// No specific capability required for initialize
break;
case 'ping':
// No specific capability required for ping
break;
}
}
assertNotificationCapability(method) {
switch (method) {
case 'notifications/roots/list_changed':
if (!this._capabilities.roots?.listChanged) {
throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
}
break;
case 'notifications/initialized':
// No specific capability required for initialized
break;
case 'notifications/cancelled':
// Cancellation notifications are always allowed
break;
case 'notifications/progress':
// Progress notifications are always allowed
break;
}
}
assertRequestHandlerCapability(method) {
// Task handlers are registered in Protocol constructor before _capabilities is initialized
// Skip capability check for task methods during initialization
if (!this._capabilities) {
return;
}
switch (method) {
case 'sampling/createMessage':
if (!this._capabilities.sampling) {
throw new Error(`Client does not support sampling capability (required for ${method})`);
}
break;
case 'elicitation/create':
if (!this._capabilities.elicitation) {
throw new Error(`Client does not support elicitation capability (required for ${method})`);
}
break;
case 'roots/list':
if (!this._capabilities.roots) {
throw new Error(`Client does not support roots capability (required for ${method})`);
}
break;
case 'tasks/get':
case 'tasks/list':
case 'tasks/result':
case 'tasks/cancel':
if (!this._capabilities.tasks) {
throw new Error(`Client does not support tasks capability (required for ${method})`);
}
break;
case 'ping':
// No specific capability required for ping
break;
}
}
assertTaskCapability(method) {
(0, helpers_js_1.assertToolsCallTaskCapability)(this._serverCapabilities?.tasks?.requests, method, 'Server');
}
assertTaskHandlerCapability(method) {
// Task handlers are registered in Protocol constructor before _capabilities is initialized
// Skip capability check for task methods during initialization
if (!this._capabilities) {
return;
}
(0, helpers_js_1.assertClientRequestTaskCapability)(this._capabilities.tasks?.requests, method, 'Client');
}
async ping(options) {
return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema, options);
}
async complete(params, options) {
return this.request({ method: 'completion/complete', params }, types_js_1.CompleteResultSchema, options);
}
async setLoggingLevel(level, options) {
return this.request({ method: 'logging/setLevel', params: { level } }, types_js_1.EmptyResultSchema, options);
}
async getPrompt(params, options) {
return this.request({ method: 'prompts/get', params }, types_js_1.GetPromptResultSchema, options);
}
async listPrompts(params, options) {
return this.request({ method: 'prompts/list', params }, types_js_1.ListPromptsResultSchema, options);
}
async listResources(params, options) {
return this.request({ method: 'resources/list', params }, types_js_1.ListResourcesResultSchema, options);
}
async listResourceTemplates(params, options) {
return this.request({ method: 'resources/templates/list', params }, types_js_1.ListResourceTemplatesResultSchema, options);
}
async readResource(params, options) {
return this.request({ method: 'resources/read', params }, types_js_1.ReadResourceResultSchema, options);
}
async subscribeResource(params, options) {
return this.request({ method: 'resources/subscribe', params }, types_js_1.EmptyResultSchema, options);
}
async unsubscribeResource(params, options) {
return this.request({ method: 'resources/unsubscribe', params }, types_js_1.EmptyResultSchema, options);
}
/**
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
*
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
*/
async callTool(params, resultSchema = types_js_1.CallToolResultSchema, options) {
// Guard: required-task tools need experimental API
if (this.isToolTaskRequired(params.name)) {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
}
const result = await this.request({ method: 'tools/call', params }, resultSchema, options);
// Check if the tool has an outputSchema
const validator = this.getToolOutputValidator(params.name);
if (validator) {
// If tool has outputSchema, it MUST return structuredContent (unless it's an error)
if (!result.structuredContent && !result.isError) {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
}
// Only validate structured content if present (not when there's an error)
if (result.structuredContent) {
try {
// Validate the structured content against the schema
const validationResult = validator(result.structuredContent);
if (!validationResult.valid) {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
}
}
catch (error) {
if (error instanceof types_js_1.McpError) {
throw error;
}
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
return result;
}
isToolTask(toolName) {
if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
return false;
}
return this._cachedKnownTaskTools.has(toolName);
}
/**
* Check if a tool requires task-based execution.
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
*/
isToolTaskRequired(toolName) {
return this._cachedRequiredTaskTools.has(toolName);
}
/**
* Cache validators for tool output schemas.
* Called after listTools() to pre-compile validators for better performance.
*/
cacheToolMetadata(tools) {
this._cachedToolOutputValidators.clear();
this._cachedKnownTaskTools.clear();
this._cachedRequiredTaskTools.clear();
for (const tool of tools) {
// If the tool has an outputSchema, create and cache the validator
if (tool.outputSchema) {
const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
this._cachedToolOutputValidators.set(tool.name, toolValidator);
}
// If the tool supports task-based execution, cache that information
const taskSupport = tool.execution?.taskSupport;
if (taskSupport === 'required' || taskSupport === 'optional') {
this._cachedKnownTaskTools.add(tool.name);
}
if (taskSupport === 'required') {
this._cachedRequiredTaskTools.add(tool.name);
}
}
}
/**
* Get cached validator for a tool
*/
getToolOutputValidator(toolName) {
return this._cachedToolOutputValidators.get(toolName);
}
async listTools(params, options) {
const result = await this.request({ method: 'tools/list', params }, types_js_1.ListToolsResultSchema, options);
// Cache the tools and their output schemas for future validation
this.cacheToolMetadata(result.tools);
return result;
}
/**
* Set up a single list changed handler.
* @internal
*/
_setupListChangedHandler(listType, notificationSchema, options, fetcher) {
// Validate options using Zod schema (validates autoRefresh and debounceMs)
const parseResult = types_js_1.ListChangedOptionsBaseSchema.safeParse(options);
if (!parseResult.success) {
throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
}
// Validate callback
if (typeof options.onChanged !== 'function') {
throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
}
const { autoRefresh, debounceMs } = parseResult.data;
const { onChanged } = options;
const refresh = async () => {
if (!autoRefresh) {
onChanged(null, null);
return;
}
try {
const items = await fetcher();
onChanged(null, items);
}
catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
onChanged(error, null);
}
};
const handler = () => {
if (debounceMs) {
// Clear any pending debounce timer for this list type
const existingTimer = this._listChangedDebounceTimers.get(listType);
if (existingTimer) {
clearTimeout(existingTimer);
}
// Set up debounced refresh
const timer = setTimeout(refresh, debounceMs);
this._listChangedDebounceTimers.set(listType, timer);
}
else {
// No debounce, refresh immediately
refresh();
}
};
// Register notification handler
this.setNotificationHandler(notificationSchema, handler);
}
async sendRootsListChanged() {
return this.notification({ method: 'notifications/roots/list_changed' });
}
}
exports.Client = Client;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,169 @@
import { OAuthClientProvider } from './auth.js';
import { FetchLike } from '../shared/transport.js';
/**
* Middleware function that wraps and enhances fetch functionality.
* Takes a fetch handler and returns an enhanced fetch handler.
*/
export type Middleware = (next: FetchLike) => FetchLike;
/**
* Creates a fetch wrapper that handles OAuth authentication automatically.
*
* This wrapper will:
* - Add Authorization headers with access tokens
* - Handle 401 responses by attempting re-authentication
* - Retry the original request after successful auth
* - Handle OAuth errors appropriately (InvalidClientError, etc.)
*
* The baseUrl parameter is optional and defaults to using the domain from the request URL.
* However, you should explicitly provide baseUrl when:
* - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com)
* - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /)
* - The OAuth server is on a different domain than your API requests
* - You want to ensure consistent OAuth behavior regardless of request URLs
*
* For MCP transports, set baseUrl to the same URL you pass to the transport constructor.
*
* Note: This wrapper is designed for general-purpose fetch operations.
* MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling
* and should not need this wrapper.
*
* @param provider - OAuth client provider for authentication
* @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain)
* @returns A fetch middleware function
*/
export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware;
/**
* Logger function type for HTTP requests
*/
export type RequestLogger = (input: {
method: string;
url: string | URL;
status: number;
statusText: string;
duration: number;
requestHeaders?: Headers;
responseHeaders?: Headers;
error?: Error;
}) => void;
/**
* Configuration options for the logging middleware
*/
export type LoggingOptions = {
/**
* Custom logger function, defaults to console logging
*/
logger?: RequestLogger;
/**
* Whether to include request headers in logs
* @default false
*/
includeRequestHeaders?: boolean;
/**
* Whether to include response headers in logs
* @default false
*/
includeResponseHeaders?: boolean;
/**
* Status level filter - only log requests with status >= this value
* Set to 0 to log all requests, 400 to log only errors
* @default 0
*/
statusLevel?: number;
};
/**
* Creates a fetch middleware that logs HTTP requests and responses.
*
* When called without arguments `withLogging()`, it uses the default logger that:
* - Logs successful requests (2xx) to `console.log`
* - Logs error responses (4xx/5xx) and network errors to `console.error`
* - Logs all requests regardless of status (statusLevel: 0)
* - Does not include request or response headers in logs
* - Measures and displays request duration in milliseconds
*
* Important: the default logger uses both `console.log` and `console.error` so it should not be used with
* `stdio` transports and applications.
*
* @param options - Logging configuration options
* @returns A fetch middleware function
*/
export declare const withLogging: (options?: LoggingOptions) => Middleware;
/**
* Composes multiple fetch middleware functions into a single middleware pipeline.
* Middleware are applied in the order they appear, creating a chain of handlers.
*
* @example
* ```typescript
* // Create a middleware pipeline that handles both OAuth and logging
* const enhancedFetch = applyMiddlewares(
* withOAuth(oauthProvider, 'https://api.example.com'),
* withLogging({ statusLevel: 400 })
* )(fetch);
*
* // Use the enhanced fetch - it will handle auth and log errors
* const response = await enhancedFetch('https://api.example.com/data');
* ```
*
* @param middleware - Array of fetch middleware to compose into a pipeline
* @returns A single composed middleware function
*/
export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware;
/**
* Helper function to create custom fetch middleware with cleaner syntax.
* Provides the next handler and request details as separate parameters for easier access.
*
* @example
* ```typescript
* // Create custom authentication middleware
* const customAuthMiddleware = createMiddleware(async (next, input, init) => {
* const headers = new Headers(init?.headers);
* headers.set('X-Custom-Auth', 'my-token');
*
* const response = await next(input, { ...init, headers });
*
* if (response.status === 401) {
* console.log('Authentication failed');
* }
*
* return response;
* });
*
* // Create conditional middleware
* const conditionalMiddleware = createMiddleware(async (next, input, init) => {
* const url = typeof input === 'string' ? input : input.toString();
*
* // Only add headers for API routes
* if (url.includes('/api/')) {
* const headers = new Headers(init?.headers);
* headers.set('X-API-Version', 'v2');
* return next(input, { ...init, headers });
* }
*
* // Pass through for non-API routes
* return next(input, init);
* });
*
* // Create caching middleware
* const cacheMiddleware = createMiddleware(async (next, input, init) => {
* const cacheKey = typeof input === 'string' ? input : input.toString();
*
* // Check cache first
* const cached = await getFromCache(cacheKey);
* if (cached) {
* return new Response(cached, { status: 200 });
* }
*
* // Make request and cache result
* const response = await next(input, init);
* if (response.ok) {
* await saveToCache(cacheKey, await response.clone().text());
* }
*
* return response;
* });
* ```
*
* @param handler - Function that receives the next handler and request parameters
* @returns A fetch middleware function
*/
export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise<Response>) => Middleware;
//# sourceMappingURL=middleware.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,aACP,mBAAmB,YAAY,MAAM,GAAG,GAAG,KAAG,UA0DxD,CAAC;AAEN;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAC;CACjB,KAAK,IAAI,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,aAAa,cAAc,KAAQ,UA6E1D,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,kBAAmB,UAAU,EAAE,KAAG,UAI9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,eAAO,MAAM,gBAAgB,YAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"}

View File

@@ -0,0 +1,252 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMiddleware = exports.applyMiddlewares = exports.withLogging = exports.withOAuth = void 0;
const auth_js_1 = require("./auth.js");
/**
* Creates a fetch wrapper that handles OAuth authentication automatically.
*
* This wrapper will:
* - Add Authorization headers with access tokens
* - Handle 401 responses by attempting re-authentication
* - Retry the original request after successful auth
* - Handle OAuth errors appropriately (InvalidClientError, etc.)
*
* The baseUrl parameter is optional and defaults to using the domain from the request URL.
* However, you should explicitly provide baseUrl when:
* - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com)
* - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /)
* - The OAuth server is on a different domain than your API requests
* - You want to ensure consistent OAuth behavior regardless of request URLs
*
* For MCP transports, set baseUrl to the same URL you pass to the transport constructor.
*
* Note: This wrapper is designed for general-purpose fetch operations.
* MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling
* and should not need this wrapper.
*
* @param provider - OAuth client provider for authentication
* @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain)
* @returns A fetch middleware function
*/
const withOAuth = (provider, baseUrl) => next => {
return async (input, init) => {
const makeRequest = async () => {
const headers = new Headers(init?.headers);
// Add authorization header if tokens are available
const tokens = await provider.tokens();
if (tokens) {
headers.set('Authorization', `Bearer ${tokens.access_token}`);
}
return await next(input, { ...init, headers });
};
let response = await makeRequest();
// Handle 401 responses by attempting re-authentication
if (response.status === 401) {
try {
const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
// Use provided baseUrl or extract from request URL
const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin);
const result = await (0, auth_js_1.auth)(provider, {
serverUrl,
resourceMetadataUrl,
scope,
fetchFn: next
});
if (result === 'REDIRECT') {
throw new auth_js_1.UnauthorizedError('Authentication requires user authorization - redirect initiated');
}
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError(`Authentication failed with result: ${result}`);
}
// Retry the request with fresh tokens
response = await makeRequest();
}
catch (error) {
if (error instanceof auth_js_1.UnauthorizedError) {
throw error;
}
throw new auth_js_1.UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`);
}
}
// If we still have a 401 after re-auth attempt, throw an error
if (response.status === 401) {
const url = typeof input === 'string' ? input : input.toString();
throw new auth_js_1.UnauthorizedError(`Authentication failed for ${url}`);
}
return response;
};
};
exports.withOAuth = withOAuth;
/**
* Creates a fetch middleware that logs HTTP requests and responses.
*
* When called without arguments `withLogging()`, it uses the default logger that:
* - Logs successful requests (2xx) to `console.log`
* - Logs error responses (4xx/5xx) and network errors to `console.error`
* - Logs all requests regardless of status (statusLevel: 0)
* - Does not include request or response headers in logs
* - Measures and displays request duration in milliseconds
*
* Important: the default logger uses both `console.log` and `console.error` so it should not be used with
* `stdio` transports and applications.
*
* @param options - Logging configuration options
* @returns A fetch middleware function
*/
const withLogging = (options = {}) => {
const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options;
const defaultLogger = input => {
const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input;
let message = error
? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)`
: `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`;
// Add headers to message if requested
if (includeRequestHeaders && requestHeaders) {
const reqHeaders = Array.from(requestHeaders.entries())
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
message += `\n Request Headers: {${reqHeaders}}`;
}
if (includeResponseHeaders && responseHeaders) {
const resHeaders = Array.from(responseHeaders.entries())
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
message += `\n Response Headers: {${resHeaders}}`;
}
if (error || status >= 400) {
// eslint-disable-next-line no-console
console.error(message);
}
else {
// eslint-disable-next-line no-console
console.log(message);
}
};
const logFn = logger || defaultLogger;
return next => async (input, init) => {
const startTime = performance.now();
const method = init?.method || 'GET';
const url = typeof input === 'string' ? input : input.toString();
const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : undefined;
try {
const response = await next(input, init);
const duration = performance.now() - startTime;
// Only log if status meets the log level threshold
if (response.status >= statusLevel) {
logFn({
method,
url,
status: response.status,
statusText: response.statusText,
duration,
requestHeaders,
responseHeaders: includeResponseHeaders ? response.headers : undefined
});
}
return response;
}
catch (error) {
const duration = performance.now() - startTime;
// Always log errors regardless of log level
logFn({
method,
url,
status: 0,
statusText: 'Network Error',
duration,
requestHeaders,
error: error
});
throw error;
}
};
};
exports.withLogging = withLogging;
/**
* Composes multiple fetch middleware functions into a single middleware pipeline.
* Middleware are applied in the order they appear, creating a chain of handlers.
*
* @example
* ```typescript
* // Create a middleware pipeline that handles both OAuth and logging
* const enhancedFetch = applyMiddlewares(
* withOAuth(oauthProvider, 'https://api.example.com'),
* withLogging({ statusLevel: 400 })
* )(fetch);
*
* // Use the enhanced fetch - it will handle auth and log errors
* const response = await enhancedFetch('https://api.example.com/data');
* ```
*
* @param middleware - Array of fetch middleware to compose into a pipeline
* @returns A single composed middleware function
*/
const applyMiddlewares = (...middleware) => {
return next => {
return middleware.reduce((handler, mw) => mw(handler), next);
};
};
exports.applyMiddlewares = applyMiddlewares;
/**
* Helper function to create custom fetch middleware with cleaner syntax.
* Provides the next handler and request details as separate parameters for easier access.
*
* @example
* ```typescript
* // Create custom authentication middleware
* const customAuthMiddleware = createMiddleware(async (next, input, init) => {
* const headers = new Headers(init?.headers);
* headers.set('X-Custom-Auth', 'my-token');
*
* const response = await next(input, { ...init, headers });
*
* if (response.status === 401) {
* console.log('Authentication failed');
* }
*
* return response;
* });
*
* // Create conditional middleware
* const conditionalMiddleware = createMiddleware(async (next, input, init) => {
* const url = typeof input === 'string' ? input : input.toString();
*
* // Only add headers for API routes
* if (url.includes('/api/')) {
* const headers = new Headers(init?.headers);
* headers.set('X-API-Version', 'v2');
* return next(input, { ...init, headers });
* }
*
* // Pass through for non-API routes
* return next(input, init);
* });
*
* // Create caching middleware
* const cacheMiddleware = createMiddleware(async (next, input, init) => {
* const cacheKey = typeof input === 'string' ? input : input.toString();
*
* // Check cache first
* const cached = await getFromCache(cacheKey);
* if (cached) {
* return new Response(cached, { status: 200 });
* }
*
* // Make request and cache result
* const response = await next(input, init);
* if (response.ok) {
* await saveToCache(cacheKey, await response.clone().text());
* }
*
* return response;
* });
* ```
*
* @param handler - Function that receives the next handler and request parameters
* @returns A fetch middleware function
*/
const createMiddleware = (handler) => {
return next => (input, init) => handler(next, input, init);
};
exports.createMiddleware = createMiddleware;
//# sourceMappingURL=middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":";;;AAAA,uCAAuG;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACI,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,KAAK,IAAuB,EAAE;YAC9C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE3C,mDAAmD;YACnD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvC,IAAI,MAAM,EAAE,CAAC;gBACT,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;YAClE,CAAC;YAED,OAAO,MAAM,IAAI,CAAC,KAAK,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,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B"}

View File

@@ -0,0 +1,81 @@
import { type ErrorEvent, type EventSourceInit } from 'eventsource';
import { Transport, FetchLike } from '../shared/transport.js';
import { JSONRPCMessage } from '../types.js';
import { OAuthClientProvider } from './auth.js';
export declare class SseError extends Error {
readonly code: number | undefined;
readonly event: ErrorEvent;
constructor(code: number | undefined, message: string | undefined, event: ErrorEvent);
}
/**
* Configuration options for the `SSEClientTransport`.
*/
export type SSEClientTransportOptions = {
/**
* An OAuth client provider to use for authentication.
*
* When an `authProvider` is specified and the SSE connection is started:
* 1. The connection is attempted with any existing access token from the `authProvider`.
* 2. If the access token has expired, the `authProvider` is used to refresh the token.
* 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`.
*
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection.
*
* If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown.
*
* `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected.
*/
authProvider?: OAuthClientProvider;
/**
* Customizes the initial SSE request to the server (the request that begins the stream).
*
* NOTE: Setting this property will prevent an `Authorization` header from
* being automatically attached to the SSE request, if an `authProvider` is
* also given. This can be worked around by setting the `Authorization` header
* manually.
*/
eventSourceInit?: EventSourceInit;
/**
* Customizes recurring POST requests to the server.
*/
requestInit?: RequestInit;
/**
* Custom fetch implementation used for all network requests.
*/
fetch?: FetchLike;
};
/**
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
* messages and make separate POST requests for sending messages.
* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
*/
export declare class SSEClientTransport implements Transport {
private _eventSource?;
private _endpoint?;
private _abortController?;
private _url;
private _resourceMetadataUrl?;
private _scope?;
private _eventSourceInit?;
private _requestInit?;
private _authProvider?;
private _fetch?;
private _fetchWithInit;
private _protocolVersion?;
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
constructor(url: URL, opts?: SSEClientTransportOptions);
private _authThenStart;
private _commonHeaders;
private _startOrAuth;
start(): Promise<void>;
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
finishAuth(authorizationCode: string): Promise<void>;
close(): Promise<void>;
send(message: JSONRPCMessage): Promise<void>;
setProtocolVersion(version: string): void;
}
//# sourceMappingURL=sse.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAEnH,qBAAa,QAAS,SAAQ,KAAK;aAEX,IAAI,EAAE,MAAM,GAAG,SAAS;aAExB,KAAK,EAAE,UAAU;gBAFjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS,EACX,KAAK,EAAE,UAAU;CAIxC;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACpC;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mBAAmB,CAAC;IAEnC;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,eAAe,C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SseError = void 0;
const eventsource_1 = require("eventsource");
const transport_js_1 = require("../shared/transport.js");
const types_js_1 = require("../types.js");
const auth_js_1 = require("./auth.js");
class SseError extends Error {
constructor(code, message, event) {
super(`SSE error: ${message}`);
this.code = code;
this.event = event;
}
}
exports.SseError = SseError;
/**
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
* messages and make separate POST requests for sending messages.
* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
*/
class SSEClientTransport {
constructor(url, opts) {
this._url = url;
this._resourceMetadataUrl = undefined;
this._scope = undefined;
this._eventSourceInit = opts?.eventSourceInit;
this._requestInit = opts?.requestInit;
this._authProvider = opts?.authProvider;
this._fetch = opts?.fetch;
this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts?.fetch, opts?.requestInit);
}
async _authThenStart() {
if (!this._authProvider) {
throw new auth_js_1.UnauthorizedError('No auth provider');
}
let result;
try {
result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
}
catch (error) {
this.onerror?.(error);
throw error;
}
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError();
}
return await this._startOrAuth();
}
async _commonHeaders() {
const headers = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
headers['Authorization'] = `Bearer ${tokens.access_token}`;
}
}
if (this._protocolVersion) {
headers['mcp-protocol-version'] = this._protocolVersion;
}
const extraHeaders = (0, transport_js_1.normalizeHeaders)(this._requestInit?.headers);
return new Headers({
...headers,
...extraHeaders
});
}
_startOrAuth() {
const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch);
return new Promise((resolve, reject) => {
this._eventSource = new eventsource_1.EventSource(this._url.href, {
...this._eventSourceInit,
fetch: async (url, init) => {
const headers = await this._commonHeaders();
headers.set('Accept', 'text/event-stream');
const response = await fetchImpl(url, {
...init,
headers
});
if (response.status === 401 && response.headers.has('www-authenticate')) {
const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
}
return response;
}
});
this._abortController = new AbortController();
this._eventSource.onerror = event => {
if (event.code === 401 && this._authProvider) {
this._authThenStart().then(resolve, reject);
return;
}
const error = new SseError(event.code, event.message, event);
reject(error);
this.onerror?.(error);
};
this._eventSource.onopen = () => {
// The connection is open, but we need to wait for the endpoint to be received.
};
this._eventSource.addEventListener('endpoint', (event) => {
const messageEvent = event;
try {
this._endpoint = new URL(messageEvent.data, this._url);
if (this._endpoint.origin !== this._url.origin) {
throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
}
}
catch (error) {
reject(error);
this.onerror?.(error);
void this.close();
return;
}
resolve();
});
this._eventSource.onmessage = (event) => {
const messageEvent = event;
let message;
try {
message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
}
catch (error) {
this.onerror?.(error);
return;
}
this.onmessage?.(message);
};
});
}
async start() {
if (this._eventSource) {
throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
return await this._startOrAuth();
}
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
async finishAuth(authorizationCode) {
if (!this._authProvider) {
throw new auth_js_1.UnauthorizedError('No auth provider');
}
const result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
authorizationCode,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError('Failed to authorize');
}
}
async close() {
this._abortController?.abort();
this._eventSource?.close();
this.onclose?.();
}
async send(message) {
if (!this._endpoint) {
throw new Error('Not connected');
}
try {
const headers = await this._commonHeaders();
headers.set('content-type', 'application/json');
const init = {
...this._requestInit,
method: 'POST',
headers,
body: JSON.stringify(message),
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._endpoint, init);
if (!response.ok) {
const text = await response.text().catch(() => null);
if (response.status === 401 && this._authProvider) {
const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
const result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError();
}
// Purposely _not_ awaited, so we don't call onerror twice
return this.send(message);
}
throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
}
// Release connection - POST responses don't have content we need
await response.body?.cancel();
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
setProtocolVersion(version) {
this._protocolVersion = version;
}
}
exports.SSEClientTransport = SSEClientTransport;
//# sourceMappingURL=sse.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,77 @@
import { IOType } from 'node:child_process';
import { Stream } from 'node:stream';
import { Transport } from '../shared/transport.js';
import { JSONRPCMessage } from '../types.js';
export type StdioServerParameters = {
/**
* The executable to run to start the server.
*/
command: string;
/**
* Command line arguments to pass to the executable.
*/
args?: string[];
/**
* The environment to use when spawning the process.
*
* If not specified, the result of getDefaultEnvironment() will be used.
*/
env?: Record<string, string>;
/**
* How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.
*
* The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr.
*/
stderr?: IOType | Stream | number;
/**
* The working directory to use when spawning the process.
*
* If not specified, the current working directory will be inherited.
*/
cwd?: string;
};
/**
* Environment variables to inherit by default, if an environment is not explicitly given.
*/
export declare const DEFAULT_INHERITED_ENV_VARS: string[];
/**
* Returns a default environment object including only environment variables deemed safe to inherit.
*/
export declare function getDefaultEnvironment(): Record<string, string>;
/**
* Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
*
* This transport is only available in Node.js environments.
*/
export declare class StdioClientTransport implements Transport {
private _process?;
private _readBuffer;
private _serverParams;
private _stderrStream;
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
constructor(server: StdioServerParameters);
/**
* Starts the server process and prepares to communicate with it.
*/
start(): Promise<void>;
/**
* The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
*
* If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
* attach listeners before the start method is invoked. This prevents loss of any early
* error output emitted by the child process.
*/
get stderr(): Stream | null;
/**
* The child process pid spawned by this transport.
*
* This is only available after the transport has been started.
*/
get pid(): number | null;
private processReadBuffer;
close(): Promise<void>;
send(message: JSONRPCMessage): Promise<void>;
}
//# sourceMappingURL=stdio.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAqD5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"}

View File

@@ -0,0 +1,199 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StdioClientTransport = exports.DEFAULT_INHERITED_ENV_VARS = void 0;
exports.getDefaultEnvironment = getDefaultEnvironment;
const cross_spawn_1 = __importDefault(require("cross-spawn"));
const node_process_1 = __importDefault(require("node:process"));
const node_stream_1 = require("node:stream");
const stdio_js_1 = require("../shared/stdio.js");
/**
* Environment variables to inherit by default, if an environment is not explicitly given.
*/
exports.DEFAULT_INHERITED_ENV_VARS = node_process_1.default.platform === 'win32'
? [
'APPDATA',
'HOMEDRIVE',
'HOMEPATH',
'LOCALAPPDATA',
'PATH',
'PROCESSOR_ARCHITECTURE',
'SYSTEMDRIVE',
'SYSTEMROOT',
'TEMP',
'USERNAME',
'USERPROFILE',
'PROGRAMFILES'
]
: /* list inspired by the default env inheritance of sudo */
['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];
/**
* Returns a default environment object including only environment variables deemed safe to inherit.
*/
function getDefaultEnvironment() {
const env = {};
for (const key of exports.DEFAULT_INHERITED_ENV_VARS) {
const value = node_process_1.default.env[key];
if (value === undefined) {
continue;
}
if (value.startsWith('()')) {
// Skip functions, which are a security risk.
continue;
}
env[key] = value;
}
return env;
}
/**
* Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
*
* This transport is only available in Node.js environments.
*/
class StdioClientTransport {
constructor(server) {
this._readBuffer = new stdio_js_1.ReadBuffer();
this._stderrStream = null;
this._serverParams = server;
if (server.stderr === 'pipe' || server.stderr === 'overlapped') {
this._stderrStream = new node_stream_1.PassThrough();
}
}
/**
* Starts the server process and prepares to communicate with it.
*/
async start() {
if (this._process) {
throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
return new Promise((resolve, reject) => {
this._process = (0, cross_spawn_1.default)(this._serverParams.command, this._serverParams.args ?? [], {
// merge default env with server env because mcp server needs some env vars
env: {
...getDefaultEnvironment(),
...this._serverParams.env
},
stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],
shell: false,
windowsHide: node_process_1.default.platform === 'win32' && isElectron(),
cwd: this._serverParams.cwd
});
this._process.on('error', error => {
reject(error);
this.onerror?.(error);
});
this._process.on('spawn', () => {
resolve();
});
this._process.on('close', _code => {
this._process = undefined;
this.onclose?.();
});
this._process.stdin?.on('error', error => {
this.onerror?.(error);
});
this._process.stdout?.on('data', chunk => {
this._readBuffer.append(chunk);
this.processReadBuffer();
});
this._process.stdout?.on('error', error => {
this.onerror?.(error);
});
if (this._stderrStream && this._process.stderr) {
this._process.stderr.pipe(this._stderrStream);
}
});
}
/**
* The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
*
* If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
* attach listeners before the start method is invoked. This prevents loss of any early
* error output emitted by the child process.
*/
get stderr() {
if (this._stderrStream) {
return this._stderrStream;
}
return this._process?.stderr ?? null;
}
/**
* The child process pid spawned by this transport.
*
* This is only available after the transport has been started.
*/
get pid() {
return this._process?.pid ?? null;
}
processReadBuffer() {
while (true) {
try {
const message = this._readBuffer.readMessage();
if (message === null) {
break;
}
this.onmessage?.(message);
}
catch (error) {
this.onerror?.(error);
}
}
}
async close() {
if (this._process) {
const processToClose = this._process;
this._process = undefined;
const closePromise = new Promise(resolve => {
processToClose.once('close', () => {
resolve();
});
});
try {
processToClose.stdin?.end();
}
catch {
// ignore
}
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
if (processToClose.exitCode === null) {
try {
processToClose.kill('SIGTERM');
}
catch {
// ignore
}
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
}
if (processToClose.exitCode === null) {
try {
processToClose.kill('SIGKILL');
}
catch {
// ignore
}
}
}
this._readBuffer.clear();
}
send(message) {
return new Promise(resolve => {
if (!this._process?.stdin) {
throw new Error('Not connected');
}
const json = (0, stdio_js_1.serializeMessage)(message);
if (this._process.stdin.write(json)) {
resolve();
}
else {
this._process.stdin.once('drain', resolve);
}
});
}
}
exports.StdioClientTransport = StdioClientTransport;
function isElectron() {
return 'type' in node_process_1.default;
}
//# sourceMappingURL=stdio.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":";;;;;;AAkEA,sDAkBC;AAnFD,8DAAgC;AAChC,gEAAmC;AACnC,6CAAkD;AAClD,iDAAkE;AAqClE;;GAEG;AACU,QAAA,0BAA0B,GACnC,sBAAO,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CAAC;YACL,CAAC;QACL,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;YACrC,CAAC;YAED,MAAM,IAAI,GAAG,IAAA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAvKD,oDAuKC;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,sBAAO,CAAC;AAC7B,CAAC"}

View File

@@ -0,0 +1,171 @@
import { Transport, FetchLike } from '../shared/transport.js';
import { JSONRPCMessage } from '../types.js';
import { OAuthClientProvider } from './auth.js';
export declare class StreamableHTTPError extends Error {
readonly code: number | undefined;
constructor(code: number | undefined, message: string | undefined);
}
/**
* Options for starting or authenticating an SSE connection
*/
export interface StartSSEOptions {
/**
* The resumption token used to continue long-running requests that were interrupted.
*
* This allows clients to reconnect and continue from where they left off.
*/
resumptionToken?: string;
/**
* A callback that is invoked when the resumption token changes.
*
* This allows clients to persist the latest token for potential reconnection.
*/
onresumptiontoken?: (token: string) => void;
/**
* Override Message ID to associate with the replay message
* so that response can be associate with the new resumed request.
*/
replayMessageId?: string | number;
}
/**
* Configuration options for reconnection behavior of the StreamableHTTPClientTransport.
*/
export interface StreamableHTTPReconnectionOptions {
/**
* Maximum backoff time between reconnection attempts in milliseconds.
* Default is 30000 (30 seconds).
*/
maxReconnectionDelay: number;
/**
* Initial backoff time between reconnection attempts in milliseconds.
* Default is 1000 (1 second).
*/
initialReconnectionDelay: number;
/**
* The factor by which the reconnection delay increases after each attempt.
* Default is 1.5.
*/
reconnectionDelayGrowFactor: number;
/**
* Maximum number of reconnection attempts before giving up.
* Default is 2.
*/
maxRetries: number;
}
/**
* Configuration options for the `StreamableHTTPClientTransport`.
*/
export type StreamableHTTPClientTransportOptions = {
/**
* An OAuth client provider to use for authentication.
*
* When an `authProvider` is specified and the connection is started:
* 1. The connection is attempted with any existing access token from the `authProvider`.
* 2. If the access token has expired, the `authProvider` is used to refresh the token.
* 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`.
*
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection.
*
* If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown.
*
* `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected.
*/
authProvider?: OAuthClientProvider;
/**
* Customizes HTTP requests to the server.
*/
requestInit?: RequestInit;
/**
* Custom fetch implementation used for all network requests.
*/
fetch?: FetchLike;
/**
* Options to configure the reconnection behavior.
*/
reconnectionOptions?: StreamableHTTPReconnectionOptions;
/**
* Session ID for the connection. This is used to identify the session on the server.
* When not provided and connecting to a server that supports session IDs, the server will generate a new session ID.
*/
sessionId?: string;
};
/**
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
* for receiving messages.
*/
export declare class StreamableHTTPClientTransport implements Transport {
private _abortController?;
private _url;
private _resourceMetadataUrl?;
private _scope?;
private _requestInit?;
private _authProvider?;
private _fetch?;
private _fetchWithInit;
private _sessionId?;
private _reconnectionOptions;
private _protocolVersion?;
private _hasCompletedAuthFlow;
private _lastUpscopingHeader?;
private _serverRetryMs?;
private _reconnectionTimeout?;
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
constructor(url: URL, opts?: StreamableHTTPClientTransportOptions);
private _authThenStart;
private _commonHeaders;
private _startOrAuthSse;
/**
* Calculates the next reconnection delay using backoff algorithm
*
* @param attempt Current reconnection attempt count for the specific stream
* @returns Time to wait in milliseconds before next reconnection attempt
*/
private _getNextReconnectionDelay;
/**
* Schedule a reconnection attempt using server-provided retry interval or backoff
*
* @param lastEventId The ID of the last received event for resumability
* @param attemptCount Current reconnection attempt count for this specific stream
*/
private _scheduleReconnection;
private _handleSseStream;
start(): Promise<void>;
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
finishAuth(authorizationCode: string): Promise<void>;
close(): Promise<void>;
send(message: JSONRPCMessage | JSONRPCMessage[], options?: {
resumptionToken?: string;
onresumptiontoken?: (token: string) => void;
}): Promise<void>;
get sessionId(): string | undefined;
/**
* Terminates the current session by sending a DELETE request to the server.
*
* Clients that no longer need a particular session
* (e.g., because the user is leaving the client application) SHOULD send an
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
* terminate the session.
*
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
* the server does not allow clients to terminate sessions.
*/
terminateSession(): Promise<void>;
setProtocolVersion(version: string): void;
get protocolVersion(): string | undefined;
/**
* Resume an SSE stream from a previous event ID.
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
*
* @param lastEventId The event ID to resume from
* @param options Optional callback to receive new resumption tokens
*/
resumeStream(lastEventId: string, options?: {
onresumptiontoken?: (token: string) => void;
}): Promise<void>;
}
//# sourceMappingURL=streamableHttp.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,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S,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA+BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;IAED;;;;;;OAMG;IACG,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAMpH"}

View File

@@ -0,0 +1,482 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamableHTTPClientTransport = exports.StreamableHTTPError = void 0;
const transport_js_1 = require("../shared/transport.js");
const types_js_1 = require("../types.js");
const auth_js_1 = require("./auth.js");
const stream_1 = require("eventsource-parser/stream");
// Default reconnection options for StreamableHTTP connections
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
initialReconnectionDelay: 1000,
maxReconnectionDelay: 30000,
reconnectionDelayGrowFactor: 1.5,
maxRetries: 2
};
class StreamableHTTPError extends Error {
constructor(code, message) {
super(`Streamable HTTP error: ${message}`);
this.code = code;
}
}
exports.StreamableHTTPError = StreamableHTTPError;
/**
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
* for receiving messages.
*/
class StreamableHTTPClientTransport {
constructor(url, opts) {
this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401
this._url = url;
this._resourceMetadataUrl = undefined;
this._scope = undefined;
this._requestInit = opts?.requestInit;
this._authProvider = opts?.authProvider;
this._fetch = opts?.fetch;
this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts?.fetch, opts?.requestInit);
this._sessionId = opts?.sessionId;
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
}
async _authThenStart() {
if (!this._authProvider) {
throw new auth_js_1.UnauthorizedError('No auth provider');
}
let result;
try {
result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
}
catch (error) {
this.onerror?.(error);
throw error;
}
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError();
}
return await this._startOrAuthSse({ resumptionToken: undefined });
}
async _commonHeaders() {
const headers = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
headers['Authorization'] = `Bearer ${tokens.access_token}`;
}
}
if (this._sessionId) {
headers['mcp-session-id'] = this._sessionId;
}
if (this._protocolVersion) {
headers['mcp-protocol-version'] = this._protocolVersion;
}
const extraHeaders = (0, transport_js_1.normalizeHeaders)(this._requestInit?.headers);
return new Headers({
...headers,
...extraHeaders
});
}
async _startOrAuthSse(options) {
const { resumptionToken } = options;
try {
// Try to open an initial SSE stream with GET to listen for server messages
// This is optional according to the spec - server may not support it
const headers = await this._commonHeaders();
headers.set('Accept', 'text/event-stream');
// Include Last-Event-ID header for resumable streams if provided
if (resumptionToken) {
headers.set('last-event-id', resumptionToken);
}
const response = await (this._fetch ?? fetch)(this._url, {
method: 'GET',
headers,
signal: this._abortController?.signal
});
if (!response.ok) {
await response.body?.cancel();
if (response.status === 401 && this._authProvider) {
// Need to authenticate
return await this._authThenStart();
}
// 405 indicates that the server does not offer an SSE stream at GET endpoint
// This is an expected case that should not trigger an error
if (response.status === 405) {
return;
}
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
}
this._handleSseStream(response.body, options, true);
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
/**
* Calculates the next reconnection delay using backoff algorithm
*
* @param attempt Current reconnection attempt count for the specific stream
* @returns Time to wait in milliseconds before next reconnection attempt
*/
_getNextReconnectionDelay(attempt) {
// Use server-provided retry value if available
if (this._serverRetryMs !== undefined) {
return this._serverRetryMs;
}
// Fall back to exponential backoff
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
// Cap at maximum delay
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
}
/**
* Schedule a reconnection attempt using server-provided retry interval or backoff
*
* @param lastEventId The ID of the last received event for resumability
* @param attemptCount Current reconnection attempt count for this specific stream
*/
_scheduleReconnection(options, attemptCount = 0) {
// Use provided options or default options
const maxRetries = this._reconnectionOptions.maxRetries;
// Check if we've exceeded maximum retry attempts
if (attemptCount >= maxRetries) {
this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
return;
}
// Calculate next delay based on current attempt count
const delay = this._getNextReconnectionDelay(attemptCount);
// Schedule the reconnection
this._reconnectionTimeout = setTimeout(() => {
// Use the last event ID to resume where we left off
this._startOrAuthSse(options).catch(error => {
this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
// Schedule another attempt if this one failed, incrementing the attempt counter
this._scheduleReconnection(options, attemptCount + 1);
});
}, delay);
}
_handleSseStream(stream, options, isReconnectable) {
if (!stream) {
return;
}
const { onresumptiontoken, replayMessageId } = options;
let lastEventId;
// Track whether we've received a priming event (event with ID)
// Per spec, server SHOULD send a priming event with ID before closing
let hasPrimingEvent = false;
// Track whether we've received a response - if so, no need to reconnect
// Reconnection is for when server disconnects BEFORE sending response
let receivedResponse = false;
const processStream = async () => {
// this is the closest we can get to trying to catch network errors
// if something happens reader will throw
try {
// Create a pipeline: binary stream -> text decoder -> SSE parser
const reader = stream
.pipeThrough(new TextDecoderStream())
.pipeThrough(new stream_1.EventSourceParserStream({
onRetry: (retryMs) => {
// Capture server-provided retry value for reconnection timing
this._serverRetryMs = retryMs;
}
}))
.getReader();
while (true) {
const { value: event, done } = await reader.read();
if (done) {
break;
}
// Update last event ID if provided
if (event.id) {
lastEventId = event.id;
// Mark that we've received a priming event - stream is now resumable
hasPrimingEvent = true;
onresumptiontoken?.(event.id);
}
// Skip events with no data (priming events, keep-alives)
if (!event.data) {
continue;
}
if (!event.event || event.event === 'message') {
try {
const message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data));
if ((0, types_js_1.isJSONRPCResultResponse)(message)) {
// Mark that we received a response - no need to reconnect for this request
receivedResponse = true;
if (replayMessageId !== undefined) {
message.id = replayMessageId;
}
}
this.onmessage?.(message);
}
catch (error) {
this.onerror?.(error);
}
}
}
// Handle graceful server-side disconnect
// Server may close connection after sending event ID and retry field
// Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)
// BUT don't reconnect if we already received a response - the request is complete
const canResume = isReconnectable || hasPrimingEvent;
const needsReconnect = canResume && !receivedResponse;
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
this._scheduleReconnection({
resumptionToken: lastEventId,
onresumptiontoken,
replayMessageId
}, 0);
}
}
catch (error) {
// Handle stream errors - likely a network disconnect
this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
// Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing
// Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)
// BUT don't reconnect if we already received a response - the request is complete
const canResume = isReconnectable || hasPrimingEvent;
const needsReconnect = canResume && !receivedResponse;
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
// Use the exponential backoff reconnection strategy
try {
this._scheduleReconnection({
resumptionToken: lastEventId,
onresumptiontoken,
replayMessageId
}, 0);
}
catch (error) {
this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));
}
}
}
};
processStream();
}
async start() {
if (this._abortController) {
throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
this._abortController = new AbortController();
}
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
async finishAuth(authorizationCode) {
if (!this._authProvider) {
throw new auth_js_1.UnauthorizedError('No auth provider');
}
const result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
authorizationCode,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError('Failed to authorize');
}
}
async close() {
if (this._reconnectionTimeout) {
clearTimeout(this._reconnectionTimeout);
this._reconnectionTimeout = undefined;
}
this._abortController?.abort();
this.onclose?.();
}
async send(message, options) {
try {
const { resumptionToken, onresumptiontoken } = options || {};
if (resumptionToken) {
// If we have at last event ID, we need to reconnect the SSE stream
this._startOrAuthSse({ resumptionToken, replayMessageId: (0, types_js_1.isJSONRPCRequest)(message) ? message.id : undefined }).catch(err => this.onerror?.(err));
return;
}
const headers = await this._commonHeaders();
headers.set('content-type', 'application/json');
headers.set('accept', 'application/json, text/event-stream');
const init = {
...this._requestInit,
method: 'POST',
headers,
body: JSON.stringify(message),
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._url, init);
// Handle session ID received during initialization
const sessionId = response.headers.get('mcp-session-id');
if (sessionId) {
this._sessionId = sessionId;
}
if (!response.ok) {
const text = await response.text().catch(() => null);
if (response.status === 401 && this._authProvider) {
// Prevent infinite recursion when server returns 401 after successful auth
if (this._hasCompletedAuthFlow) {
throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');
}
const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
const result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError();
}
// Mark that we completed auth flow
this._hasCompletedAuthFlow = true;
// Purposely _not_ awaited, so we don't call onerror twice
return this.send(message);
}
if (response.status === 403 && this._authProvider) {
const { resourceMetadataUrl, scope, error } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
if (error === 'insufficient_scope') {
const wwwAuthHeader = response.headers.get('WWW-Authenticate');
// Check if we've already tried upscoping with this header to prevent infinite loops.
if (this._lastUpscopingHeader === wwwAuthHeader) {
throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');
}
if (scope) {
this._scope = scope;
}
if (resourceMetadataUrl) {
this._resourceMetadataUrl = resourceMetadataUrl;
}
// Mark that upscoping was tried.
this._lastUpscopingHeader = wwwAuthHeader ?? undefined;
const result = await (0, auth_js_1.auth)(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetch
});
if (result !== 'AUTHORIZED') {
throw new auth_js_1.UnauthorizedError();
}
return this.send(message);
}
}
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
}
// Reset auth loop flag on successful response
this._hasCompletedAuthFlow = false;
this._lastUpscopingHeader = undefined;
// If the response is 202 Accepted, there's no body to process
if (response.status === 202) {
await response.body?.cancel();
// if the accepted notification is initialized, we start the SSE stream
// if it's supported by the server
if ((0, types_js_1.isInitializedNotification)(message)) {
// Start without a lastEventId since this is a fresh connection
this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));
}
return;
}
// Get original message(s) for detecting request IDs
const messages = Array.isArray(message) ? message : [message];
const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;
// Check the response type
const contentType = response.headers.get('content-type');
if (hasRequests) {
if (contentType?.includes('text/event-stream')) {
// Handle SSE stream responses for requests
// We use the same handler as standalone streams, which now supports
// reconnection with the last event ID
this._handleSseStream(response.body, { onresumptiontoken }, false);
}
else if (contentType?.includes('application/json')) {
// For non-streaming servers, we might get direct JSON responses
const data = await response.json();
const responseMessages = Array.isArray(data)
? data.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg))
: [types_js_1.JSONRPCMessageSchema.parse(data)];
for (const msg of responseMessages) {
this.onmessage?.(msg);
}
}
else {
await response.body?.cancel();
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
}
}
else {
// No requests in message but got 200 OK - still need to release connection
await response.body?.cancel();
}
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
get sessionId() {
return this._sessionId;
}
/**
* Terminates the current session by sending a DELETE request to the server.
*
* Clients that no longer need a particular session
* (e.g., because the user is leaving the client application) SHOULD send an
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
* terminate the session.
*
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
* the server does not allow clients to terminate sessions.
*/
async terminateSession() {
if (!this._sessionId) {
return; // No session to terminate
}
try {
const headers = await this._commonHeaders();
const init = {
...this._requestInit,
method: 'DELETE',
headers,
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._url, init);
await response.body?.cancel();
// We specifically handle 405 as a valid response according to the spec,
// meaning the server does not support explicit session termination
if (!response.ok && response.status !== 405) {
throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
}
this._sessionId = undefined;
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
setProtocolVersion(version) {
this._protocolVersion = version;
}
get protocolVersion() {
return this._protocolVersion;
}
/**
* Resume an SSE stream from a previous event ID.
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
*
* @param lastEventId The event ID to resume from
* @param options Optional callback to receive new resumption tokens
*/
async resumeStream(lastEventId, options) {
await this._startOrAuthSse({
resumptionToken: lastEventId,
onresumptiontoken: options?.onresumptiontoken
});
}
}
exports.StreamableHTTPClientTransport = StreamableHTTPClientTransport;
//# sourceMappingURL=streamableHttp.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
import { Transport } from '../shared/transport.js';
import { JSONRPCMessage } from '../types.js';
/**
* Client transport for WebSocket: this will connect to a server over the WebSocket protocol.
*/
export declare class WebSocketClientTransport implements Transport {
private _socket?;
private _url;
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
constructor(url: URL);
start(): Promise<void>;
close(): Promise<void>;
send(message: JSONRPCMessage): Promise<void>;
}
//# sourceMappingURL=websocket.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"}

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketClientTransport = void 0;
const types_js_1 = require("../types.js");
const SUBPROTOCOL = 'mcp';
/**
* Client transport for WebSocket: this will connect to a server over the WebSocket protocol.
*/
class WebSocketClientTransport {
constructor(url) {
this._url = url;
}
start() {
if (this._socket) {
throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
return new Promise((resolve, reject) => {
this._socket = new WebSocket(this._url, SUBPROTOCOL);
this._socket.onerror = event => {
const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`);
reject(error);
this.onerror?.(error);
};
this._socket.onopen = () => {
resolve();
};
this._socket.onclose = () => {
this.onclose?.();
};
this._socket.onmessage = (event) => {
let message;
try {
message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data));
}
catch (error) {
this.onerror?.(error);
return;
}
this.onmessage?.(message);
};
});
}
async close() {
this._socket?.close();
}
send(message) {
return new Promise((resolve, reject) => {
if (!this._socket) {
reject(new Error('Not connected'));
return;
}
this._socket?.send(JSON.stringify(message));
resolve();
});
}
}
exports.WebSocketClientTransport = WebSocketClientTransport;
//# sourceMappingURL=websocket.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":";;;AACA,0CAAmE;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAa,wBAAwB;IAQjC,YAAY,GAAQ;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IACpB,CAAC;IAED,KAAK;QACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CACX,mHAAmH,CACtH,CAAC;QACN,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACnC,IAAI,CAAC,OAAO,GAAG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;YAErD,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;gBAC3B,MAAM,KAAK,GAAG,OAAO,IAAI,KAAK,CAAC,CAAC,CAAE,KAAK,CAAC,KAAe,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACjH,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;YAC1B,CAAC,CAAC;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file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,680 @@
"use strict";
// Run with: npx tsx src/examples/client/elicitationUrlExample.ts
//
// This example demonstrates how to use URL elicitation to securely
// collect user input in a remote (HTTP) server.
// URL elicitation allows servers to prompt the end-user to open a URL in their browser
// to collect sensitive information.
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const node_readline_1 = require("node:readline");
const types_js_1 = require("../../types.js");
const metadataUtils_js_1 = require("../../shared/metadataUtils.js");
const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js");
const auth_js_1 = require("../../client/auth.js");
const node_http_1 = require("node:http");
// Set up OAuth (required for this example)
const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001)
const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`;
let oauthProvider = undefined;
console.log('Getting OAuth token...');
const clientMetadata = {
client_name: 'Elicitation MCP Client',
redirect_uris: [OAUTH_CALLBACK_URL],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'client_secret_post',
scope: 'mcp:tools'
};
oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => {
console.log(`\n🔗 Please open this URL in your browser to authorize:\n ${redirectUrl.toString()}`);
});
// Create readline interface for user input
const readline = (0, node_readline_1.createInterface)({
input: process.stdin,
output: process.stdout
});
let abortCommand = new AbortController();
// Global client and transport for interactive commands
let client = null;
let transport = null;
let serverUrl = 'http://localhost:3000/mcp';
let sessionId = undefined;
let isProcessingCommand = false;
let isProcessingElicitations = false;
const elicitationQueue = [];
let elicitationQueueSignal = null;
let elicitationsCompleteSignal = null;
// Map to track pending URL elicitations waiting for completion notifications
const pendingURLElicitations = new Map();
async function main() {
console.log('MCP Interactive Client');
console.log('=====================');
// Connect to server immediately with default settings
await connect();
// Start the elicitation loop in the background
elicitationLoop().catch(error => {
console.error('Unexpected error in elicitation loop:', error);
process.exit(1);
});
// Short delay allowing the server to send any SSE elicitations on connection
await new Promise(resolve => setTimeout(resolve, 200));
// Wait until we are done processing any initial elicitations
await waitForElicitationsToComplete();
// Print help and start the command loop
printHelp();
await commandLoop();
}
async function waitForElicitationsToComplete() {
// Wait until the queue is empty and nothing is being processed
while (elicitationQueue.length > 0 || isProcessingElicitations) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
function printHelp() {
console.log('\nAvailable commands:');
console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)');
console.log(' disconnect - Disconnect from server');
console.log(' terminate-session - Terminate the current session');
console.log(' reconnect - Reconnect to the server');
console.log(' list-tools - List available tools');
console.log(' call-tool <name> [args] - Call a tool with optional JSON arguments');
console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool');
console.log(' third-party-auth - Test tool that requires third-party OAuth credentials');
console.log(' help - Show this help');
console.log(' quit - Exit the program');
}
async function commandLoop() {
await new Promise(resolve => {
if (!isProcessingElicitations) {
resolve();
}
else {
elicitationsCompleteSignal = resolve;
}
});
readline.question('\n> ', { signal: abortCommand.signal }, async (input) => {
isProcessingCommand = true;
const args = input.trim().split(/\s+/);
const command = args[0]?.toLowerCase();
try {
switch (command) {
case 'connect':
await connect(args[1]);
break;
case 'disconnect':
await disconnect();
break;
case 'terminate-session':
await terminateSession();
break;
case 'reconnect':
await reconnect();
break;
case 'list-tools':
await listTools();
break;
case 'call-tool':
if (args.length < 2) {
console.log('Usage: call-tool <name> [args]');
}
else {
const toolName = args[1];
let toolArgs = {};
if (args.length > 2) {
try {
toolArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await callTool(toolName, toolArgs);
}
break;
case 'payment-confirm':
await callPaymentConfirmTool();
break;
case 'third-party-auth':
await callThirdPartyAuthTool();
break;
case 'help':
printHelp();
break;
case 'quit':
case 'exit':
await cleanup();
return;
default:
if (command) {
console.log(`Unknown command: ${command}`);
}
break;
}
}
catch (error) {
console.error(`Error executing command: ${error}`);
}
finally {
isProcessingCommand = false;
}
// Process another command after we've processed the this one
await commandLoop();
});
}
async function elicitationLoop() {
while (true) {
// Wait until we have elicitations to process
await new Promise(resolve => {
if (elicitationQueue.length > 0) {
resolve();
}
else {
elicitationQueueSignal = resolve;
}
});
isProcessingElicitations = true;
abortCommand.abort(); // Abort the command loop if it's running
// Process all queued elicitations
while (elicitationQueue.length > 0) {
const queued = elicitationQueue.shift();
console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`);
try {
const result = await handleElicitationRequest(queued.request);
queued.resolve(result);
}
catch (error) {
queued.reject(error instanceof Error ? error : new Error(String(error)));
}
}
console.log('✅ All queued elicitations processed. Resuming command loop...\n');
isProcessingElicitations = false;
// Reset the abort controller for the next command loop
abortCommand = new AbortController();
// Resume the command loop
if (elicitationsCompleteSignal) {
elicitationsCompleteSignal();
elicitationsCompleteSignal = null;
}
}
}
/**
* Enqueues an elicitation request and returns the result.
*
* This function is used so that our CLI (which can only handle one input request at a time)
* can handle elicitation requests and the command loop.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function elicitationRequestHandler(request) {
// If we are processing a command, handle this elicitation immediately
if (isProcessingCommand) {
console.log('📋 Processing elicitation immediately (during command execution)');
return await handleElicitationRequest(request);
}
// Otherwise, queue the request to be handled by the elicitation loop
console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`);
return new Promise((resolve, reject) => {
elicitationQueue.push({
request,
resolve,
reject
});
// Signal the elicitation loop that there's work to do
if (elicitationQueueSignal) {
elicitationQueueSignal();
elicitationQueueSignal = null;
}
});
}
/**
* Handles an elicitation request.
*
* This function is used to handle the elicitation request and return the result.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function handleElicitationRequest(request) {
const mode = request.params.mode;
console.log('\n🔔 Elicitation Request Received:');
console.log(`Mode: ${mode}`);
if (mode === 'url') {
return {
action: await handleURLElicitation(request.params)
};
}
else {
// Should not happen because the client declares its capabilities to the server,
// but being defensive is a good practice:
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`);
}
}
/**
* Handles a URL elicitation by opening the URL in the browser.
*
* Note: This is a shared code for both request handlers and error handlers.
* As a result of sharing schema, there is no big forking of logic for the client.
*
* @param params - The URL elicitation request parameters
* @returns The action to take (accept, cancel, or decline)
*/
async function handleURLElicitation(params) {
const url = params.url;
const elicitationId = params.elicitationId;
const message = params.message;
console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration
// Parse URL to show domain for security
let domain = 'unknown domain';
try {
const parsedUrl = new URL(url);
domain = parsedUrl.hostname;
}
catch {
console.error('Invalid URL provided by server');
return 'decline';
}
// Example security warning to help prevent phishing attacks
console.log('\n⚠ \x1b[33mSECURITY WARNING\x1b[0m ⚠️');
console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m');
console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n');
console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`);
console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`);
console.log(`\n Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`);
// 1. Ask for user consent to open the URL
const consent = await new Promise(resolve => {
readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => {
resolve(input.trim().toLowerCase());
});
});
// 2. If user did not consent, return appropriate result
if (consent === 'no' || consent === 'n') {
console.log('❌ URL navigation declined.');
return 'decline';
}
else if (consent !== 'yes' && consent !== 'y') {
console.log('🚫 Invalid response. Cancelling elicitation.');
return 'cancel';
}
// 3. Wait for completion notification in the background
const completionPromise = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`);
reject(new Error('Elicitation completion timeout'));
}, 5 * 60 * 1000); // 5 minute timeout
pendingURLElicitations.set(elicitationId, {
resolve: () => {
clearTimeout(timeout);
resolve();
},
reject,
timeout
});
});
completionPromise.catch(error => {
console.error('Background completion wait failed:', error);
});
// 4. Direct user to open the URL in their browser
console.log(`\n🔗 Please open this URL in your browser:\n ${url}`);
console.log('\n⏳ Waiting for you to complete the interaction in your browser...');
console.log(' The server will send a notification once you complete the action.');
// 5. Acknowledge the user accepted the elicitation
return 'accept';
}
/**
* Example OAuth callback handler - in production, use a more robust approach
* for handling callbacks and storing tokens
*/
/**
* Starts a temporary HTTP server to receive the OAuth callback
*/
async function waitForOAuthCallback() {
return new Promise((resolve, reject) => {
const server = (0, node_http_1.createServer)((req, res) => {
// Ignore favicon requests
if (req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
return;
}
console.log(`📥 Received callback: ${req.url}`);
const parsedUrl = new URL(req.url || '', 'http://localhost');
const code = parsedUrl.searchParams.get('code');
const error = parsedUrl.searchParams.get('error');
if (code) {
console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Successful!</h1>
<p>This simulates successful authorization of the MCP client, which now has an access token for the MCP server.</p>
<p>This window will close automatically in 10 seconds.</p>
<script>setTimeout(() => window.close(), 10000);</script>
</body>
</html>
`);
resolve(code);
setTimeout(() => server.close(), 15000);
}
else if (error) {
console.log(`❌ Authorization error: ${error}`);
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Failed</h1>
<p>Error: ${error}</p>
</body>
</html>
`);
reject(new Error(`OAuth authorization failed: ${error}`));
}
else {
console.log(`❌ No authorization code or error in callback`);
res.writeHead(400);
res.end('Bad request');
reject(new Error('No authorization code provided'));
}
});
server.listen(OAUTH_CALLBACK_PORT, () => {
console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`);
});
});
}
/**
* Attempts to connect to the MCP server with OAuth authentication.
* Handles OAuth flow recursively if authorization is required.
*/
async function attemptConnection(oauthProvider) {
console.log('🚢 Creating transport with OAuth provider...');
const baseUrl = new URL(serverUrl);
transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, {
sessionId: sessionId,
authProvider: oauthProvider
});
console.log('🚢 Transport created');
try {
console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...');
await client.connect(transport);
sessionId = transport.sessionId;
console.log('Transport created with session ID:', sessionId);
console.log('✅ Connected successfully');
}
catch (error) {
if (error instanceof auth_js_1.UnauthorizedError) {
console.log('🔐 OAuth required - waiting for authorization...');
const callbackPromise = waitForOAuthCallback();
const authCode = await callbackPromise;
await transport.finishAuth(authCode);
console.log('🔐 Authorization code received:', authCode);
console.log('🔌 Reconnecting with authenticated transport...');
// Recursively retry connection after OAuth completion
await attemptConnection(oauthProvider);
}
else {
console.error('❌ Connection failed with non-auth error:', error);
throw error;
}
}
}
async function connect(url) {
if (client) {
console.log('Already connected. Disconnect first.');
return;
}
if (url) {
serverUrl = url;
}
console.log(`🔗 Attempting to connect to ${serverUrl}...`);
// Create a new client with elicitation capability
console.log('👤 Creating MCP client...');
client = new index_js_1.Client({
name: 'example-client',
version: '1.0.0'
}, {
capabilities: {
elicitation: {
// Only URL elicitation is supported in this demo
// (see server/elicitationExample.ts for a demo of form mode elicitation)
url: {}
}
}
});
console.log('👤 Client created');
// Set up elicitation request handler with proper validation
client.setRequestHandler(types_js_1.ElicitRequestSchema, elicitationRequestHandler);
// Set up notification handler for elicitation completion
client.setNotificationHandler(types_js_1.ElicitationCompleteNotificationSchema, notification => {
const { elicitationId } = notification.params;
const pending = pendingURLElicitations.get(elicitationId);
if (pending) {
clearTimeout(pending.timeout);
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`);
pending.resolve();
}
else {
// Shouldn't happen - discard it!
console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`);
}
});
try {
console.log('🔐 Starting OAuth flow...');
await attemptConnection(oauthProvider);
console.log('Connected to MCP server');
// Set up error handler after connection is established so we don't double log errors
client.onerror = error => {
console.error('\x1b[31mClient error:', error, '\x1b[0m');
};
}
catch (error) {
console.error('Failed to connect:', error);
client = null;
transport = null;
return;
}
}
async function disconnect() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
await transport.close();
console.log('Disconnected from MCP server');
client = null;
transport = null;
}
catch (error) {
console.error('Error disconnecting:', error);
}
}
async function terminateSession() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
console.log('Terminating session with ID:', transport.sessionId);
await transport.terminateSession();
console.log('Session terminated successfully');
// Check if sessionId was cleared after termination
if (!transport.sessionId) {
console.log('Session ID has been cleared');
sessionId = undefined;
// Also close the transport and clear client objects
await transport.close();
console.log('Transport closed after session termination');
client = null;
transport = null;
}
else {
console.log('Server responded with 405 Method Not Allowed (session termination not supported)');
console.log('Session ID is still active:', transport.sessionId);
}
}
catch (error) {
console.error('Error terminating session:', error);
}
}
async function reconnect() {
if (client) {
await disconnect();
}
await connect();
}
async function listTools() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server (${error})`);
}
}
async function callTool(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const request = {
method: 'tools/call',
params: {
name,
arguments: args
}
};
console.log(`Calling tool '${name}' with args:`, args);
const result = await client.request(request, types_js_1.CallToolResultSchema);
console.log('Tool result:');
const resourceLinks = [];
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else if (item.type === 'resource_link') {
const resourceLink = item;
resourceLinks.push(resourceLink);
console.log(` 📁 Resource Link: ${resourceLink.name}`);
console.log(` URI: ${resourceLink.uri}`);
if (resourceLink.mimeType) {
console.log(` Type: ${resourceLink.mimeType}`);
}
if (resourceLink.description) {
console.log(` Description: ${resourceLink.description}`);
}
}
else if (item.type === 'resource') {
console.log(` [Embedded Resource: ${item.resource.uri}]`);
}
else if (item.type === 'image') {
console.log(` [Image: ${item.mimeType}]`);
}
else if (item.type === 'audio') {
console.log(` [Audio: ${item.mimeType}]`);
}
else {
console.log(` [Unknown content type]:`, item);
}
});
// Offer to read resource links
if (resourceLinks.length > 0) {
console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource <uri>' to read their content.`);
}
}
catch (error) {
if (error instanceof types_js_1.UrlElicitationRequiredError) {
console.log('\n🔔 Elicitation Required Error Received:');
console.log(`Message: ${error.message}`);
for (const e of error.elicitations) {
await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response
}
return;
}
console.log(`Error calling tool ${name}: ${error}`);
}
}
async function cleanup() {
if (client && transport) {
try {
// First try to terminate the session gracefully
if (transport.sessionId) {
try {
console.log('Terminating session before exit...');
await transport.terminateSession();
console.log('Session terminated successfully');
}
catch (error) {
console.error('Error terminating session:', error);
}
}
// Then close the transport
await transport.close();
}
catch (error) {
console.error('Error closing transport:', error);
}
}
process.stdin.setRawMode(false);
readline.close();
console.log('\nGoodbye!');
process.exit(0);
}
async function callPaymentConfirmTool() {
console.log('Calling payment-confirm tool...');
await callTool('payment-confirm', { cartId: 'cart_123' });
}
async function callThirdPartyAuthTool() {
console.log('Calling third-party-auth tool...');
await callTool('third-party-auth', { param1: 'test' });
}
// Set up raw mode for keyboard input to capture Escape key
process.stdin.setRawMode(true);
process.stdin.on('data', async (data) => {
// Check for Escape key (27)
if (data.length === 1 && data[0] === 27) {
console.log('\nESC key pressed. Disconnecting from server...');
// Abort current operation and disconnect from server
if (client && transport) {
await disconnect();
console.log('Disconnected. Press Enter to continue.');
}
else {
console.log('Not connected to server.');
}
// Re-display the prompt
process.stdout.write('> ');
}
});
// Handle Ctrl+C
process.on('SIGINT', async () => {
console.log('\nReceived SIGINT. Cleaning up...');
await cleanup();
});
// Start the interactive client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=elicitationUrlExample.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=multipleClientsParallel.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const types_js_1 = require("../../types.js");
/**
* Multiple Clients MCP Example
*
* This client demonstrates how to:
* 1. Create multiple MCP clients in parallel
* 2. Each client calls a single tool
* 3. Track notifications from each client independently
*/
// Command line args processing
const args = process.argv.slice(2);
const serverUrl = args[0] || 'http://localhost:3000/mcp';
async function createAndRunClient(config) {
console.log(`[${config.id}] Creating client: ${config.name}`);
const client = new index_js_1.Client({
name: config.name,
version: '1.0.0'
});
const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl));
// Set up client-specific error handler
client.onerror = error => {
console.error(`[${config.id}] Client error:`, error);
};
// Set up client-specific notification handler
client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => {
console.log(`[${config.id}] Notification: ${notification.params.data}`);
});
try {
// Connect to the server
await client.connect(transport);
console.log(`[${config.id}] Connected to MCP server`);
// Call the specified tool
console.log(`[${config.id}] Calling tool: ${config.toolName}`);
const toolRequest = {
method: 'tools/call',
params: {
name: config.toolName,
arguments: {
...config.toolArguments,
// Add client ID to arguments for identification in notifications
caller: config.id
}
}
};
const result = await client.request(toolRequest, types_js_1.CallToolResultSchema);
console.log(`[${config.id}] Tool call completed`);
// Keep the connection open for a bit to receive notifications
await new Promise(resolve => setTimeout(resolve, 5000));
// Disconnect
await transport.close();
console.log(`[${config.id}] Disconnected from MCP server`);
return { id: config.id, result };
}
catch (error) {
console.error(`[${config.id}] Error:`, error);
throw error;
}
}
async function main() {
console.log('MCP Multiple Clients Example');
console.log('============================');
console.log(`Server URL: ${serverUrl}`);
console.log('');
try {
// Define client configurations
const clientConfigs = [
{
id: 'client1',
name: 'basic-client-1',
toolName: 'start-notification-stream',
toolArguments: {
interval: 3, // 1 second between notifications
count: 5 // Send 5 notifications
}
},
{
id: 'client2',
name: 'basic-client-2',
toolName: 'start-notification-stream',
toolArguments: {
interval: 2, // 2 seconds between notifications
count: 3 // Send 3 notifications
}
},
{
id: 'client3',
name: 'basic-client-3',
toolName: 'start-notification-stream',
toolArguments: {
interval: 1, // 0.5 second between notifications
count: 8 // Send 8 notifications
}
}
];
// Start all clients in parallel
console.log(`Starting ${clientConfigs.length} clients in parallel...`);
console.log('');
const clientPromises = clientConfigs.map(config => createAndRunClient(config));
const results = await Promise.all(clientPromises);
// Display results from all clients
console.log('\n=== Final Results ===');
results.forEach(({ id, result }) => {
console.log(`\n[${id}] Tool result:`);
if (Array.isArray(result.content)) {
result.content.forEach((item) => {
if (item.type === 'text' && item.text) {
console.log(` ${item.text}`);
}
else {
console.log(` ${item.type} content:`, item);
}
});
}
else {
console.log(` Unexpected result format:`, result);
}
});
console.log('\n=== All clients completed successfully ===');
}
catch (error) {
console.error('Error running multiple clients:', error);
process.exit(1);
}
}
// Start the example
main().catch((error) => {
console.error('Error running MCP multiple clients example:', error);
process.exit(1);
});
//# sourceMappingURL=multipleClientsParallel.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAAyH;AAEz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I,CAAC,IAAI,EAAE,CAAC;wBACpC,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;oBACjD,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=parallelToolCallsClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,176 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const types_js_1 = require("../../types.js");
/**
* Parallel Tool Calls MCP Client
*
* This client demonstrates how to:
* 1. Start multiple tool calls in parallel
* 2. Track notifications from each tool call using a caller parameter
*/
// Command line args processing
const args = process.argv.slice(2);
const serverUrl = args[0] || 'http://localhost:3000/mcp';
async function main() {
console.log('MCP Parallel Tool Calls Client');
console.log('==============================');
console.log(`Connecting to server at: ${serverUrl}`);
let client;
let transport;
try {
// Create client with streamable HTTP transport
client = new index_js_1.Client({
name: 'parallel-tool-calls-client',
version: '1.0.0'
});
client.onerror = error => {
console.error('Client error:', error);
};
// Connect to the server
transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl));
await client.connect(transport);
console.log('Successfully connected to MCP server');
// Set up notification handler with caller identification
client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => {
console.log(`Notification: ${notification.params.data}`);
});
console.log('List tools');
const toolsRequest = await listTools(client);
console.log('Tools: ', toolsRequest);
// 2. Start multiple notification tools in parallel
console.log('\n=== Starting Multiple Notification Streams in Parallel ===');
const toolResults = await startParallelNotificationTools(client);
// Log the results from each tool call
for (const [caller, result] of Object.entries(toolResults)) {
console.log(`\n=== Tool result for ${caller} ===`);
result.content.forEach((item) => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else {
console.log(` ${item.type} content:`, item);
}
});
}
// 3. Wait for all notifications (10 seconds)
console.log('\n=== Waiting for all notifications ===');
await new Promise(resolve => setTimeout(resolve, 10000));
// 4. Disconnect
console.log('\n=== Disconnecting ===');
await transport.close();
console.log('Disconnected from MCP server');
}
catch (error) {
console.error('Error running client:', error);
process.exit(1);
}
}
/**
* List available tools on the server
*/
async function listTools(client) {
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - ${tool.name}: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server: ${error}`);
}
}
/**
* Start multiple notification tools in parallel with different configurations
* Each tool call includes a caller parameter to identify its notifications
*/
async function startParallelNotificationTools(client) {
try {
// Define multiple tool calls with different configurations
const toolCalls = [
{
caller: 'fast-notifier',
request: {
method: 'tools/call',
params: {
name: 'start-notification-stream',
arguments: {
interval: 2, // 0.5 second between notifications
count: 10, // Send 10 notifications
caller: 'fast-notifier' // Identify this tool call
}
}
}
},
{
caller: 'slow-notifier',
request: {
method: 'tools/call',
params: {
name: 'start-notification-stream',
arguments: {
interval: 5, // 2 seconds between notifications
count: 5, // Send 5 notifications
caller: 'slow-notifier' // Identify this tool call
}
}
}
},
{
caller: 'burst-notifier',
request: {
method: 'tools/call',
params: {
name: 'start-notification-stream',
arguments: {
interval: 1, // 0.1 second between notifications
count: 3, // Send just 3 notifications
caller: 'burst-notifier' // Identify this tool call
}
}
}
}
];
console.log(`Starting ${toolCalls.length} notification tools in parallel...`);
// Start all tool calls in parallel
const toolPromises = toolCalls.map(({ caller, request }) => {
console.log(`Starting tool call for ${caller}...`);
return client
.request(request, types_js_1.CallToolResultSchema)
.then(result => ({ caller, result }))
.catch(error => {
console.error(`Error in tool call for ${caller}:`, error);
throw error;
});
});
// Wait for all tool calls to complete
const results = await Promise.all(toolPromises);
// Organize results by caller
const resultsByTool = {};
results.forEach(({ caller, result }) => {
resultsByTool[caller] = result;
});
return resultsByTool;
}
catch (error) {
console.error(`Error starting parallel notification tools:`, error);
throw error;
}
}
// Start the client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=parallelToolCallsClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAMwB;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU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AAC,CAAC;QACpE,MAAM,KAAK,CAAC;IAChB,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,20 @@
#!/usr/bin/env node
/**
* Example demonstrating client_credentials grant for machine-to-machine authentication.
*
* Supports two authentication methods based on environment variables:
*
* 1. client_secret_basic (default):
* MCP_CLIENT_ID - OAuth client ID (required)
* MCP_CLIENT_SECRET - OAuth client secret (required)
*
* 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set):
* MCP_CLIENT_ID - OAuth client ID (required)
* MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required)
* MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256)
*
* Common:
* MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp)
*/
export {};
//# sourceMappingURL=simpleClientCredentials.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleClientCredentials.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;;;GAgBG"}

View File

@@ -0,0 +1,70 @@
#!/usr/bin/env node
"use strict";
/**
* Example demonstrating client_credentials grant for machine-to-machine authentication.
*
* Supports two authentication methods based on environment variables:
*
* 1. client_secret_basic (default):
* MCP_CLIENT_ID - OAuth client ID (required)
* MCP_CLIENT_SECRET - OAuth client secret (required)
*
* 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set):
* MCP_CLIENT_ID - OAuth client ID (required)
* MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required)
* MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256)
*
* Common:
* MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp)
*/
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const auth_extensions_js_1 = require("../../client/auth-extensions.js");
const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp';
function createProvider() {
const clientId = process.env.MCP_CLIENT_ID;
if (!clientId) {
console.error('MCP_CLIENT_ID environment variable is required');
process.exit(1);
}
// If private key is provided, use private_key_jwt authentication
const privateKeyPem = process.env.MCP_CLIENT_PRIVATE_KEY_PEM;
if (privateKeyPem) {
const algorithm = process.env.MCP_CLIENT_ALGORITHM || 'RS256';
console.log('Using private_key_jwt authentication');
return new auth_extensions_js_1.PrivateKeyJwtProvider({
clientId,
privateKey: privateKeyPem,
algorithm
});
}
// Otherwise, use client_secret_basic authentication
const clientSecret = process.env.MCP_CLIENT_SECRET;
if (!clientSecret) {
console.error('MCP_CLIENT_SECRET or MCP_CLIENT_PRIVATE_KEY_PEM environment variable is required');
process.exit(1);
}
console.log('Using client_secret_basic authentication');
return new auth_extensions_js_1.ClientCredentialsProvider({
clientId,
clientSecret
});
}
async function main() {
const provider = createProvider();
const client = new index_js_1.Client({ name: 'client-credentials-example', version: '1.0.0' }, { capabilities: {} });
const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(DEFAULT_SERVER_URL), {
authProvider: provider
});
await client.connect(transport);
console.log('Connected successfully.');
const tools = await client.listTools();
console.log('Available tools:', tools.tools.map(t => t.name).join(', ') || '(none)');
await transport.close();
}
main().catch(err => {
console.error(err);
process.exit(1);
});
//# sourceMappingURL=simpleClientCredentials.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleClientCredentials.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;GAgBG;;AAEH,oDAA+C;AAC/C,sEAA+E;AAC/E,w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G,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,EAAE;QAC7E,YAAY,EAAE,QAAQ;KACzB,CAAC,CAAC;IAEH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,SAAS,EAAE,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,CAAC;IAErF,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;AAC5B,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;IACf,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
export {};
//# sourceMappingURL=simpleOAuthClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,397 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_http_1 = require("node:http");
const node_readline_1 = require("node:readline");
const node_url_1 = require("node:url");
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const types_js_1 = require("../../types.js");
const auth_js_1 = require("../../client/auth.js");
const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js");
// Configuration
const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp';
const CALLBACK_PORT = 8090; // Use different port than auth server (3001)
const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;
/**
* Interactive MCP client with OAuth authentication
* Demonstrates the complete OAuth flow with browser-based authorization
*/
class InteractiveOAuthClient {
constructor(serverUrl, clientMetadataUrl) {
this.serverUrl = serverUrl;
this.clientMetadataUrl = clientMetadataUrl;
this.client = null;
this.rl = (0, node_readline_1.createInterface)({
input: process.stdin,
output: process.stdout
});
}
/**
* Prompts user for input via readline
*/
async question(query) {
return new Promise(resolve => {
this.rl.question(query, resolve);
});
}
/**
* Example OAuth callback handler - in production, use a more robust approach
* for handling callbacks and storing tokens
*/
/**
* Starts a temporary HTTP server to receive the OAuth callback
*/
async waitForOAuthCallback() {
return new Promise((resolve, reject) => {
const server = (0, node_http_1.createServer)((req, res) => {
// Ignore favicon requests
if (req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
return;
}
console.log(`📥 Received callback: ${req.url}`);
const parsedUrl = new node_url_1.URL(req.url || '', 'http://localhost');
const code = parsedUrl.searchParams.get('code');
const error = parsedUrl.searchParams.get('error');
if (code) {
console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Successful!</h1>
<p>You can close this window and return to the terminal.</p>
<script>setTimeout(() => window.close(), 2000);</script>
</body>
</html>
`);
resolve(code);
setTimeout(() => server.close(), 3000);
}
else if (error) {
console.log(`❌ Authorization error: ${error}`);
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Failed</h1>
<p>Error: ${error}</p>
</body>
</html>
`);
reject(new Error(`OAuth authorization failed: ${error}`));
}
else {
console.log(`❌ No authorization code or error in callback`);
res.writeHead(400);
res.end('Bad request');
reject(new Error('No authorization code provided'));
}
});
server.listen(CALLBACK_PORT, () => {
console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`);
});
});
}
async attemptConnection(oauthProvider) {
console.log('🚢 Creating transport with OAuth provider...');
const baseUrl = new node_url_1.URL(this.serverUrl);
const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, {
authProvider: oauthProvider
});
console.log('🚢 Transport created');
try {
console.log('🔌 Attempting connection (this will trigger OAuth redirect)...');
await this.client.connect(transport);
console.log('✅ Connected successfully');
}
catch (error) {
if (error instanceof auth_js_1.UnauthorizedError) {
console.log('🔐 OAuth required - waiting for authorization...');
const callbackPromise = this.waitForOAuthCallback();
const authCode = await callbackPromise;
await transport.finishAuth(authCode);
console.log('🔐 Authorization code received:', authCode);
console.log('🔌 Reconnecting with authenticated transport...');
await this.attemptConnection(oauthProvider);
}
else {
console.error('❌ Connection failed with non-auth error:', error);
throw error;
}
}
}
/**
* Establishes connection to the MCP server with OAuth authentication
*/
async connect() {
console.log(`🔗 Attempting to connect to ${this.serverUrl}...`);
const clientMetadata = {
client_name: 'Simple OAuth MCP Client',
redirect_uris: [CALLBACK_URL],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'client_secret_post'
};
console.log('🔐 Creating OAuth provider...');
const oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => {
console.log(`\n🔗 Please open this URL in your browser to authorize:\n ${redirectUrl.toString()}`);
}, this.clientMetadataUrl);
console.log('🔐 OAuth provider created');
console.log('👤 Creating MCP client...');
this.client = new index_js_1.Client({
name: 'simple-oauth-client',
version: '1.0.0'
}, { capabilities: {} });
console.log('👤 Client created');
console.log('🔐 Starting OAuth flow...');
await this.attemptConnection(oauthProvider);
// Start interactive loop
await this.interactiveLoop();
}
/**
* Main interactive loop for user commands
*/
async interactiveLoop() {
console.log('\n🎯 Interactive MCP Client with OAuth');
console.log('Commands:');
console.log(' list - List available tools');
console.log(' call <tool_name> [args] - Call a tool');
console.log(' stream <tool_name> [args] - Call a tool with streaming (shows task status)');
console.log(' quit - Exit the client');
console.log();
while (true) {
try {
const command = await this.question('mcp> ');
if (!command.trim()) {
continue;
}
if (command === 'quit') {
console.log('\n👋 Goodbye!');
this.close();
process.exit(0);
}
else if (command === 'list') {
await this.listTools();
}
else if (command.startsWith('call ')) {
await this.handleCallTool(command);
}
else if (command.startsWith('stream ')) {
await this.handleStreamTool(command);
}
else {
console.log("❌ Unknown command. Try 'list', 'call <tool_name>', 'stream <tool_name>', or 'quit'");
}
}
catch (error) {
if (error instanceof Error && error.message === 'SIGINT') {
console.log('\n\n👋 Goodbye!');
break;
}
console.error('❌ Error:', error);
}
}
}
async listTools() {
if (!this.client) {
console.log('❌ Not connected to server');
return;
}
try {
const request = {
method: 'tools/list',
params: {}
};
const result = await this.client.request(request, types_js_1.ListToolsResultSchema);
if (result.tools && result.tools.length > 0) {
console.log('\n📋 Available tools:');
result.tools.forEach((tool, index) => {
console.log(`${index + 1}. ${tool.name}`);
if (tool.description) {
console.log(` Description: ${tool.description}`);
}
console.log();
});
}
else {
console.log('No tools available');
}
}
catch (error) {
console.error('❌ Failed to list tools:', error);
}
}
async handleCallTool(command) {
const parts = command.split(/\s+/);
const toolName = parts[1];
if (!toolName) {
console.log('❌ Please specify a tool name');
return;
}
// Parse arguments (simple JSON-like format)
let toolArgs = {};
if (parts.length > 2) {
const argsString = parts.slice(2).join(' ');
try {
toolArgs = JSON.parse(argsString);
}
catch {
console.log('❌ Invalid arguments format (expected JSON)');
return;
}
}
await this.callTool(toolName, toolArgs);
}
async callTool(toolName, toolArgs) {
if (!this.client) {
console.log('❌ Not connected to server');
return;
}
try {
const request = {
method: 'tools/call',
params: {
name: toolName,
arguments: toolArgs
}
};
const result = await this.client.request(request, types_js_1.CallToolResultSchema);
console.log(`\n🔧 Tool '${toolName}' result:`);
if (result.content) {
result.content.forEach(content => {
if (content.type === 'text') {
console.log(content.text);
}
else {
console.log(content);
}
});
}
else {
console.log(result);
}
}
catch (error) {
console.error(`❌ Failed to call tool '${toolName}':`, error);
}
}
async handleStreamTool(command) {
const parts = command.split(/\s+/);
const toolName = parts[1];
if (!toolName) {
console.log('❌ Please specify a tool name');
return;
}
// Parse arguments (simple JSON-like format)
let toolArgs = {};
if (parts.length > 2) {
const argsString = parts.slice(2).join(' ');
try {
toolArgs = JSON.parse(argsString);
}
catch {
console.log('❌ Invalid arguments format (expected JSON)');
return;
}
}
await this.streamTool(toolName, toolArgs);
}
async streamTool(toolName, toolArgs) {
if (!this.client) {
console.log('❌ Not connected to server');
return;
}
try {
// Using the experimental tasks API - WARNING: may change without notice
console.log(`\n🔧 Streaming tool '${toolName}'...`);
const stream = this.client.experimental.tasks.callToolStream({
name: toolName,
arguments: toolArgs
}, types_js_1.CallToolResultSchema, {
task: {
taskId: `task-${Date.now()}`,
ttl: 60000
}
});
// Iterate through all messages yielded by the generator
for await (const message of stream) {
switch (message.type) {
case 'taskCreated':
console.log(`✓ Task created: ${message.task.taskId}`);
break;
case 'taskStatus':
console.log(`⟳ Status: ${message.task.status}`);
if (message.task.statusMessage) {
console.log(` ${message.task.statusMessage}`);
}
break;
case 'result':
console.log('✓ Completed!');
message.result.content.forEach(content => {
if (content.type === 'text') {
console.log(content.text);
}
else {
console.log(content);
}
});
break;
case 'error':
console.log('✗ Error:');
console.log(` ${message.error.message}`);
break;
}
}
}
catch (error) {
console.error(`❌ Failed to stream tool '${toolName}':`, error);
}
}
close() {
this.rl.close();
if (this.client) {
// Note: Client doesn't have a close method in the current implementation
// This would typically close the transport connection
}
}
}
/**
* Main entry point
*/
async function main() {
const args = process.argv.slice(2);
const serverUrl = args[0] || DEFAULT_SERVER_URL;
const clientMetadataUrl = args[1];
console.log('🚀 Simple MCP OAuth Client');
console.log(`Connecting to: ${serverUrl}`);
if (clientMetadataUrl) {
console.log(`Client Metadata URL: ${clientMetadataUrl}`);
}
console.log();
const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl);
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n\n👋 Goodbye!');
client.close();
process.exit(0);
});
try {
await client.connect();
}
catch (error) {
console.error('Failed to start client:', error);
process.exit(1);
}
finally {
client.close();
}
}
// Run if this file is executed directly
main().catch(error => {
console.error('Unhandled error:', error);
process.exit(1);
});
//# sourceMappingURL=simpleOAuthClient.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
import { OAuthClientProvider } from '../../client/auth.js';
import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js';
/**
* In-memory OAuth client provider for demonstration purposes
* In production, you should persist tokens securely
*/
export declare class InMemoryOAuthClientProvider implements OAuthClientProvider {
private readonly _redirectUrl;
private readonly _clientMetadata;
readonly clientMetadataUrl?: string | undefined;
private _clientInformation?;
private _tokens?;
private _codeVerifier?;
constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined);
private _onRedirect;
get redirectUrl(): string | URL;
get clientMetadata(): OAuthClientMetadata;
clientInformation(): OAuthClientInformationMixed | undefined;
saveClientInformation(clientInformation: OAuthClientInformationMixed): void;
tokens(): OAuthTokens | undefined;
saveTokens(tokens: OAuthTokens): void;
redirectToAuthorization(authorizationUrl: URL): void;
saveCodeVerifier(codeVerifier: string): void;
codeVerifier(): string;
}
//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"}

View File

@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryOAuthClientProvider = void 0;
/**
* In-memory OAuth client provider for demonstration purposes
* In production, you should persist tokens securely
*/
class InMemoryOAuthClientProvider {
constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) {
this._redirectUrl = _redirectUrl;
this._clientMetadata = _clientMetadata;
this.clientMetadataUrl = clientMetadataUrl;
this._onRedirect =
onRedirect ||
(url => {
console.log(`Redirect to: ${url.toString()}`);
});
}
get redirectUrl() {
return this._redirectUrl;
}
get clientMetadata() {
return this._clientMetadata;
}
clientInformation() {
return this._clientInformation;
}
saveClientInformation(clientInformation) {
this._clientInformation = clientInformation;
}
tokens() {
return this._tokens;
}
saveTokens(tokens) {
this._tokens = tokens;
}
redirectToAuthorization(authorizationUrl) {
this._onRedirect(authorizationUrl);
}
saveCodeVerifier(codeVerifier) {
this._codeVerifier = codeVerifier;
}
codeVerifier() {
if (!this._codeVerifier) {
throw new Error('No code verifier saved');
}
return this._codeVerifier;
}
}
exports.InMemoryOAuthClientProvider = InMemoryOAuthClientProvider;
//# sourceMappingURL=simpleOAuthClientProvider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":";;;AAGA;;;GAGG;AACH,MAAa,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ;AA1DD,kEA0DC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=simpleStreamableHttp.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,857 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const node_readline_1 = require("node:readline");
const types_js_1 = require("../../types.js");
const in_memory_js_1 = require("../../experimental/tasks/stores/in-memory.js");
const metadataUtils_js_1 = require("../../shared/metadataUtils.js");
const ajv_1 = require("ajv");
// Create readline interface for user input
const readline = (0, node_readline_1.createInterface)({
input: process.stdin,
output: process.stdout
});
// Track received notifications for debugging resumability
let notificationCount = 0;
// Global client and transport for interactive commands
let client = null;
let transport = null;
let serverUrl = 'http://localhost:3000/mcp';
let notificationsToolLastEventId = undefined;
let sessionId = undefined;
async function main() {
console.log('MCP Interactive Client');
console.log('=====================');
// Connect to server immediately with default settings
await connect();
// Print help and start the command loop
printHelp();
commandLoop();
}
function printHelp() {
console.log('\nAvailable commands:');
console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)');
console.log(' disconnect - Disconnect from server');
console.log(' terminate-session - Terminate the current session');
console.log(' reconnect - Reconnect to the server');
console.log(' list-tools - List available tools');
console.log(' call-tool <name> [args] - Call a tool with optional JSON arguments');
console.log(' call-tool-task <name> [args] - Call a tool with task-based execution (example: call-tool-task delay {"duration":3000})');
console.log(' greet [name] - Call the greet tool');
console.log(' multi-greet [name] - Call the multi-greet tool with notifications');
console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)');
console.log(' collect-info-task [type] - Test bidirectional task support (server+client tasks) with elicitation');
console.log(' start-notifications [interval] [count] - Start periodic notifications');
console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability');
console.log(' list-prompts - List available prompts');
console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments');
console.log(' list-resources - List available resources');
console.log(' read-resource <uri> - Read a specific resource by URI');
console.log(' help - Show this help');
console.log(' quit - Exit the program');
}
function commandLoop() {
readline.question('\n> ', async (input) => {
const args = input.trim().split(/\s+/);
const command = args[0]?.toLowerCase();
try {
switch (command) {
case 'connect':
await connect(args[1]);
break;
case 'disconnect':
await disconnect();
break;
case 'terminate-session':
await terminateSession();
break;
case 'reconnect':
await reconnect();
break;
case 'list-tools':
await listTools();
break;
case 'call-tool':
if (args.length < 2) {
console.log('Usage: call-tool <name> [args]');
}
else {
const toolName = args[1];
let toolArgs = {};
if (args.length > 2) {
try {
toolArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await callTool(toolName, toolArgs);
}
break;
case 'greet':
await callGreetTool(args[1] || 'MCP User');
break;
case 'multi-greet':
await callMultiGreetTool(args[1] || 'MCP User');
break;
case 'collect-info':
await callCollectInfoTool(args[1] || 'contact');
break;
case 'collect-info-task': {
await callCollectInfoWithTask(args[1] || 'contact');
break;
}
case 'start-notifications': {
const interval = args[1] ? parseInt(args[1], 10) : 2000;
const count = args[2] ? parseInt(args[2], 10) : 10;
await startNotifications(interval, count);
break;
}
case 'run-notifications-tool-with-resumability': {
const interval = args[1] ? parseInt(args[1], 10) : 2000;
const count = args[2] ? parseInt(args[2], 10) : 10;
await runNotificationsToolWithResumability(interval, count);
break;
}
case 'call-tool-task':
if (args.length < 2) {
console.log('Usage: call-tool-task <name> [args]');
}
else {
const toolName = args[1];
let toolArgs = {};
if (args.length > 2) {
try {
toolArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await callToolTask(toolName, toolArgs);
}
break;
case 'list-prompts':
await listPrompts();
break;
case 'get-prompt':
if (args.length < 2) {
console.log('Usage: get-prompt <name> [args]');
}
else {
const promptName = args[1];
let promptArgs = {};
if (args.length > 2) {
try {
promptArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await getPrompt(promptName, promptArgs);
}
break;
case 'list-resources':
await listResources();
break;
case 'read-resource':
if (args.length < 2) {
console.log('Usage: read-resource <uri>');
}
else {
await readResource(args[1]);
}
break;
case 'help':
printHelp();
break;
case 'quit':
case 'exit':
await cleanup();
return;
default:
if (command) {
console.log(`Unknown command: ${command}`);
}
break;
}
}
catch (error) {
console.error(`Error executing command: ${error}`);
}
// Continue the command loop
commandLoop();
});
}
async function connect(url) {
if (client) {
console.log('Already connected. Disconnect first.');
return;
}
if (url) {
serverUrl = url;
}
console.log(`Connecting to ${serverUrl}...`);
try {
// Create task store for client-side task support
const clientTaskStore = new in_memory_js_1.InMemoryTaskStore();
// Create a new client with form elicitation capability and task support
client = new index_js_1.Client({
name: 'example-client',
version: '1.0.0'
}, {
capabilities: {
elicitation: {
form: {}
},
tasks: {
requests: {
elicitation: {
create: {}
}
}
}
},
taskStore: clientTaskStore
});
client.onerror = error => {
console.error('\x1b[31mClient error:', error, '\x1b[0m');
};
// Set up elicitation request handler with proper validation and task support
client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request, extra) => {
if (request.params.mode !== 'form') {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`);
}
console.log('\n🔔 Elicitation (form) Request Received:');
console.log(`Message: ${request.params.message}`);
console.log(`Related Task: ${request.params._meta?.[types_js_1.RELATED_TASK_META_KEY]?.taskId}`);
console.log(`Task Creation Requested: ${request.params.task ? 'yes' : 'no'}`);
console.log('Requested Schema:');
console.log(JSON.stringify(request.params.requestedSchema, null, 2));
// Helper to return result, optionally creating a task if requested
const returnResult = async (result) => {
if (request.params.task && extra.taskStore) {
// Create a task and store the result
const task = await extra.taskStore.createTask({ ttl: extra.taskRequestedTtl });
await extra.taskStore.storeTaskResult(task.taskId, 'completed', result);
console.log(`📋 Created client-side task: ${task.taskId}`);
return { task };
}
return result;
};
const schema = request.params.requestedSchema;
const properties = schema.properties;
const required = schema.required || [];
// Set up AJV validator for the requested schema
const ajv = new ajv_1.Ajv();
const validate = ajv.compile(schema);
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
attempts++;
console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`);
const content = {};
let inputCancelled = false;
// Collect input for each field
for (const [fieldName, fieldSchema] of Object.entries(properties)) {
const field = fieldSchema;
const isRequired = required.includes(fieldName);
let prompt = `${field.title || fieldName}`;
// Add helpful information to the prompt
if (field.description) {
prompt += ` (${field.description})`;
}
if (field.enum) {
prompt += ` [options: ${field.enum.join(', ')}]`;
}
if (field.type === 'number' || field.type === 'integer') {
if (field.minimum !== undefined && field.maximum !== undefined) {
prompt += ` [${field.minimum}-${field.maximum}]`;
}
else if (field.minimum !== undefined) {
prompt += ` [min: ${field.minimum}]`;
}
else if (field.maximum !== undefined) {
prompt += ` [max: ${field.maximum}]`;
}
}
if (field.type === 'string' && field.format) {
prompt += ` [format: ${field.format}]`;
}
if (isRequired) {
prompt += ' *required*';
}
if (field.default !== undefined) {
prompt += ` [default: ${field.default}]`;
}
prompt += ': ';
const answer = await new Promise(resolve => {
readline.question(prompt, input => {
resolve(input.trim());
});
});
// Check for cancellation
if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') {
inputCancelled = true;
break;
}
// Parse and validate the input
try {
if (answer === '' && field.default !== undefined) {
content[fieldName] = field.default;
}
else if (answer === '' && !isRequired) {
// Skip optional empty fields
continue;
}
else if (answer === '') {
throw new Error(`${fieldName} is required`);
}
else {
// Parse the value based on type
let parsedValue;
if (field.type === 'boolean') {
parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1';
}
else if (field.type === 'number') {
parsedValue = parseFloat(answer);
if (isNaN(parsedValue)) {
throw new Error(`${fieldName} must be a valid number`);
}
}
else if (field.type === 'integer') {
parsedValue = parseInt(answer, 10);
if (isNaN(parsedValue)) {
throw new Error(`${fieldName} must be a valid integer`);
}
}
else if (field.enum) {
if (!field.enum.includes(answer)) {
throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`);
}
parsedValue = answer;
}
else {
parsedValue = answer;
}
content[fieldName] = parsedValue;
}
}
catch (error) {
console.log(`❌ Error: ${error}`);
// Continue to next attempt
break;
}
}
if (inputCancelled) {
return returnResult({ action: 'cancel' });
}
// If we didn't complete all fields due to an error, try again
if (Object.keys(content).length !==
Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) {
if (attempts < maxAttempts) {
console.log('Please try again...');
continue;
}
else {
console.log('Maximum attempts reached. Declining request.');
return returnResult({ action: 'decline' });
}
}
// Validate the complete object against the schema
const isValid = validate(content);
if (!isValid) {
console.log('❌ Validation errors:');
validate.errors?.forEach(error => {
console.log(` - ${error.instancePath || 'root'}: ${error.message}`);
});
if (attempts < maxAttempts) {
console.log('Please correct the errors and try again...');
continue;
}
else {
console.log('Maximum attempts reached. Declining request.');
return returnResult({ action: 'decline' });
}
}
// Show the collected data and ask for confirmation
console.log('\n✅ Collected data:');
console.log(JSON.stringify(content, null, 2));
const confirmAnswer = await new Promise(resolve => {
readline.question('\nSubmit this information? (yes/no/cancel): ', input => {
resolve(input.trim().toLowerCase());
});
});
switch (confirmAnswer) {
case 'yes':
case 'y': {
return returnResult({
action: 'accept',
content: content
});
}
case 'cancel':
case 'c': {
return returnResult({ action: 'cancel' });
}
case 'no':
case 'n': {
if (attempts < maxAttempts) {
console.log('Please re-enter the information...');
continue;
}
else {
return returnResult({ action: 'decline' });
}
break;
}
}
}
console.log('Maximum attempts reached. Declining request.');
return returnResult({ action: 'decline' });
});
transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl), {
sessionId: sessionId
});
// Set up notification handlers
client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => {
notificationCount++;
console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`);
// Re-display the prompt
process.stdout.write('> ');
});
client.setNotificationHandler(types_js_1.ResourceListChangedNotificationSchema, async (_) => {
console.log(`\nResource list changed notification received!`);
try {
if (!client) {
console.log('Client disconnected, cannot fetch resources');
return;
}
const resourcesResult = await client.request({
method: 'resources/list',
params: {}
}, types_js_1.ListResourcesResultSchema);
console.log('Available resources count:', resourcesResult.resources.length);
}
catch {
console.log('Failed to list resources after change notification');
}
// Re-display the prompt
process.stdout.write('> ');
});
// Connect the client
await client.connect(transport);
sessionId = transport.sessionId;
console.log('Transport created with session ID:', sessionId);
console.log('Connected to MCP server');
}
catch (error) {
console.error('Failed to connect:', error);
client = null;
transport = null;
}
}
async function disconnect() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
await transport.close();
console.log('Disconnected from MCP server');
client = null;
transport = null;
}
catch (error) {
console.error('Error disconnecting:', error);
}
}
async function terminateSession() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
console.log('Terminating session with ID:', transport.sessionId);
await transport.terminateSession();
console.log('Session terminated successfully');
// Check if sessionId was cleared after termination
if (!transport.sessionId) {
console.log('Session ID has been cleared');
sessionId = undefined;
// Also close the transport and clear client objects
await transport.close();
console.log('Transport closed after session termination');
client = null;
transport = null;
}
else {
console.log('Server responded with 405 Method Not Allowed (session termination not supported)');
console.log('Session ID is still active:', transport.sessionId);
}
}
catch (error) {
console.error('Error terminating session:', error);
}
}
async function reconnect() {
if (client) {
await disconnect();
}
await connect();
}
async function listTools() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server (${error})`);
}
}
async function callTool(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const request = {
method: 'tools/call',
params: {
name,
arguments: args
}
};
console.log(`Calling tool '${name}' with args:`, args);
const result = await client.request(request, types_js_1.CallToolResultSchema);
console.log('Tool result:');
const resourceLinks = [];
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else if (item.type === 'resource_link') {
const resourceLink = item;
resourceLinks.push(resourceLink);
console.log(` 📁 Resource Link: ${resourceLink.name}`);
console.log(` URI: ${resourceLink.uri}`);
if (resourceLink.mimeType) {
console.log(` Type: ${resourceLink.mimeType}`);
}
if (resourceLink.description) {
console.log(` Description: ${resourceLink.description}`);
}
}
else if (item.type === 'resource') {
console.log(` [Embedded Resource: ${item.resource.uri}]`);
}
else if (item.type === 'image') {
console.log(` [Image: ${item.mimeType}]`);
}
else if (item.type === 'audio') {
console.log(` [Audio: ${item.mimeType}]`);
}
else {
console.log(` [Unknown content type]:`, item);
}
});
// Offer to read resource links
if (resourceLinks.length > 0) {
console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource <uri>' to read their content.`);
}
}
catch (error) {
console.log(`Error calling tool ${name}: ${error}`);
}
}
async function callGreetTool(name) {
await callTool('greet', { name });
}
async function callMultiGreetTool(name) {
console.log('Calling multi-greet tool with notifications...');
await callTool('multi-greet', { name });
}
async function callCollectInfoTool(infoType) {
console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`);
await callTool('collect-user-info', { infoType });
}
async function callCollectInfoWithTask(infoType) {
console.log(`\n🔄 Testing bidirectional task support with collect-user-info-task tool (${infoType})...`);
console.log('This will create a task on the server, which will elicit input and create a task on the client.\n');
await callToolTask('collect-user-info-task', { infoType });
}
async function startNotifications(interval, count) {
console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`);
await callTool('start-notification-stream', { interval, count });
}
async function runNotificationsToolWithResumability(interval, count) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`);
console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`);
const request = {
method: 'tools/call',
params: {
name: 'start-notification-stream',
arguments: { interval, count }
}
};
const onLastEventIdUpdate = (event) => {
notificationsToolLastEventId = event;
console.log(`Updated resumption token: ${event}`);
};
const result = await client.request(request, types_js_1.CallToolResultSchema, {
resumptionToken: notificationsToolLastEventId,
onresumptiontoken: onLastEventIdUpdate
});
console.log('Tool result:');
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else {
console.log(` ${item.type} content:`, item);
}
});
}
catch (error) {
console.log(`Error starting notification stream: ${error}`);
}
}
async function listPrompts() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const promptsRequest = {
method: 'prompts/list',
params: {}
};
const promptsResult = await client.request(promptsRequest, types_js_1.ListPromptsResultSchema);
console.log('Available prompts:');
if (promptsResult.prompts.length === 0) {
console.log(' No prompts available');
}
else {
for (const prompt of promptsResult.prompts) {
console.log(` - id: ${prompt.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(prompt)}, description: ${prompt.description}`);
}
}
}
catch (error) {
console.log(`Prompts not supported by this server (${error})`);
}
}
async function getPrompt(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const promptRequest = {
method: 'prompts/get',
params: {
name,
arguments: args
}
};
const promptResult = await client.request(promptRequest, types_js_1.GetPromptResultSchema);
console.log('Prompt template:');
promptResult.messages.forEach((msg, index) => {
console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`);
});
}
catch (error) {
console.log(`Error getting prompt ${name}: ${error}`);
}
}
async function listResources() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const resourcesRequest = {
method: 'resources/list',
params: {}
};
const resourcesResult = await client.request(resourcesRequest, types_js_1.ListResourcesResultSchema);
console.log('Available resources:');
if (resourcesResult.resources.length === 0) {
console.log(' No resources available');
}
else {
for (const resource of resourcesResult.resources) {
console.log(` - id: ${resource.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(resource)}, description: ${resource.uri}`);
}
}
}
catch (error) {
console.log(`Resources not supported by this server (${error})`);
}
}
async function readResource(uri) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const request = {
method: 'resources/read',
params: { uri }
};
console.log(`Reading resource: ${uri}`);
const result = await client.request(request, types_js_1.ReadResourceResultSchema);
console.log('Resource contents:');
for (const content of result.contents) {
console.log(` URI: ${content.uri}`);
if (content.mimeType) {
console.log(` Type: ${content.mimeType}`);
}
if ('text' in content && typeof content.text === 'string') {
console.log(' Content:');
console.log(' ---');
console.log(content.text
.split('\n')
.map((line) => ' ' + line)
.join('\n'));
console.log(' ---');
}
else if ('blob' in content && typeof content.blob === 'string') {
console.log(` [Binary data: ${content.blob.length} bytes]`);
}
}
}
catch (error) {
console.log(`Error reading resource ${uri}: ${error}`);
}
}
async function callToolTask(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
console.log(`Calling tool '${name}' with task-based execution...`);
console.log('Arguments:', args);
// Use task-based execution - call now, fetch later
// Using the experimental tasks API - WARNING: may change without notice
console.log('This will return immediately while processing continues in the background...');
try {
// Call the tool with task metadata using streaming API
const stream = client.experimental.tasks.callToolStream({
name,
arguments: args
}, types_js_1.CallToolResultSchema, {
task: {
ttl: 60000 // Keep results for 60 seconds
}
});
console.log('Waiting for task completion...');
let lastStatus = '';
for await (const message of stream) {
switch (message.type) {
case 'taskCreated':
console.log('Task created successfully with ID:', message.task.taskId);
break;
case 'taskStatus':
if (lastStatus !== message.task.status) {
console.log(` ${message.task.status}${message.task.statusMessage ? ` - ${message.task.statusMessage}` : ''}`);
}
lastStatus = message.task.status;
break;
case 'result':
console.log('Task completed!');
console.log('Tool result:');
message.result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
});
break;
case 'error':
throw message.error;
}
}
}
catch (error) {
console.log(`Error with task-based execution: ${error}`);
}
}
async function cleanup() {
if (client && transport) {
try {
// First try to terminate the session gracefully
if (transport.sessionId) {
try {
console.log('Terminating session before exit...');
await transport.terminateSession();
console.log('Session terminated successfully');
}
catch (error) {
console.error('Error terminating session:', error);
}
}
// Then close the transport
await transport.close();
}
catch (error) {
console.error('Error closing transport:', error);
}
}
process.stdin.setRawMode(false);
readline.close();
console.log('\nGoodbye!');
process.exit(0);
}
// Set up raw mode for keyboard input to capture Escape key
process.stdin.setRawMode(true);
process.stdin.on('data', async (data) => {
// Check for Escape key (27)
if (data.length === 1 && data[0] === 27) {
console.log('\nESC key pressed. Disconnecting from server...');
// Abort current operation and disconnect from server
if (client && transport) {
await disconnect();
console.log('Disconnected. Press Enter to continue.');
}
else {
console.log('Not connected to server.');
}
// Re-display the prompt
process.stdout.write('> ');
}
});
// Handle Ctrl+C
process.on('SIGINT', async () => {
console.log('\nReceived SIGINT. Cleaning up...');
await cleanup();
});
// Start the interactive client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=simpleStreamableHttp.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
/**
* Simple interactive task client demonstrating elicitation and sampling responses.
*
* This client connects to simpleTaskInteractive.ts server and demonstrates:
* - Handling elicitation requests (y/n confirmation)
* - Handling sampling requests (returns a hardcoded haiku)
* - Using task-based tool execution with streaming
*/
export {};
//# sourceMappingURL=simpleTaskInteractiveClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"simpleTaskInteractiveClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleTaskInteractiveClient.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}

View File

@@ -0,0 +1,157 @@
"use strict";
/**
* Simple interactive task client demonstrating elicitation and sampling responses.
*
* This client connects to simpleTaskInteractive.ts server and demonstrates:
* - Handling elicitation requests (y/n confirmation)
* - Handling sampling requests (returns a hardcoded haiku)
* - Using task-based tool execution with streaming
*/
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const node_readline_1 = require("node:readline");
const types_js_1 = require("../../types.js");
// Create readline interface for user input
const readline = (0, node_readline_1.createInterface)({
input: process.stdin,
output: process.stdout
});
function question(prompt) {
return new Promise(resolve => {
readline.question(prompt, answer => {
resolve(answer.trim());
});
});
}
function getTextContent(result) {
const textContent = result.content.find((c) => c.type === 'text');
return textContent?.text ?? '(no text)';
}
async function elicitationCallback(params) {
console.log(`\n[Elicitation] Server asks: ${params.message}`);
// Simple terminal prompt for y/n
const response = await question('Your response (y/n): ');
const confirmed = ['y', 'yes', 'true', '1'].includes(response.toLowerCase());
console.log(`[Elicitation] Responding with: confirm=${confirmed}`);
return { action: 'accept', content: { confirm: confirmed } };
}
async function samplingCallback(params) {
// Get the prompt from the first message
let prompt = 'unknown';
if (params.messages && params.messages.length > 0) {
const firstMessage = params.messages[0];
const content = firstMessage.content;
if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) {
prompt = content.text;
}
else if (Array.isArray(content)) {
const textPart = content.find(c => c.type === 'text' && 'text' in c);
if (textPart && 'text' in textPart) {
prompt = textPart.text;
}
}
}
console.log(`\n[Sampling] Server requests LLM completion for: ${prompt}`);
// Return a hardcoded haiku (in real use, call your LLM here)
const haiku = `Cherry blossoms fall
Softly on the quiet pond
Spring whispers goodbye`;
console.log('[Sampling] Responding with haiku');
return {
model: 'mock-haiku-model',
role: 'assistant',
content: { type: 'text', text: haiku }
};
}
async function run(url) {
console.log('Simple Task Interactive Client');
console.log('==============================');
console.log(`Connecting to ${url}...`);
// Create client with elicitation and sampling capabilities
const client = new index_js_1.Client({ name: 'simple-task-interactive-client', version: '1.0.0' }, {
capabilities: {
elicitation: { form: {} },
sampling: {}
}
});
// Set up elicitation request handler
client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request) => {
if (request.params.mode && request.params.mode !== 'form') {
throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`);
}
return elicitationCallback(request.params);
});
// Set up sampling request handler
client.setRequestHandler(types_js_1.CreateMessageRequestSchema, async (request) => {
return samplingCallback(request.params);
});
// Connect to server
const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(url));
await client.connect(transport);
console.log('Connected!\n');
// List tools
const toolsResult = await client.listTools();
console.log(`Available tools: ${toolsResult.tools.map(t => t.name).join(', ')}`);
// Demo 1: Elicitation (confirm_delete)
console.log('\n--- Demo 1: Elicitation ---');
console.log('Calling confirm_delete tool...');
const confirmStream = client.experimental.tasks.callToolStream({ name: 'confirm_delete', arguments: { filename: 'important.txt' } }, types_js_1.CallToolResultSchema, { task: { ttl: 60000 } });
for await (const message of confirmStream) {
switch (message.type) {
case 'taskCreated':
console.log(`Task created: ${message.task.taskId}`);
break;
case 'taskStatus':
console.log(`Task status: ${message.task.status}`);
break;
case 'result':
console.log(`Result: ${getTextContent(message.result)}`);
break;
case 'error':
console.error(`Error: ${message.error}`);
break;
}
}
// Demo 2: Sampling (write_haiku)
console.log('\n--- Demo 2: Sampling ---');
console.log('Calling write_haiku tool...');
const haikuStream = client.experimental.tasks.callToolStream({ name: 'write_haiku', arguments: { topic: 'autumn leaves' } }, types_js_1.CallToolResultSchema, {
task: { ttl: 60000 }
});
for await (const message of haikuStream) {
switch (message.type) {
case 'taskCreated':
console.log(`Task created: ${message.task.taskId}`);
break;
case 'taskStatus':
console.log(`Task status: ${message.task.status}`);
break;
case 'result':
console.log(`Result:\n${getTextContent(message.result)}`);
break;
case 'error':
console.error(`Error: ${message.error}`);
break;
}
}
// Cleanup
console.log('\nDemo complete. Closing connection...');
await transport.close();
readline.close();
}
// Parse command line arguments
const args = process.argv.slice(2);
let url = 'http://localhost:8000/mcp';
for (let i = 0; i < args.length; i++) {
if (args[i] === '--url' && args[i + 1]) {
url = args[i + 1];
i++;
}
}
// Run the client
run(url).catch(error => {
console.error('Error running client:', error);
process.exit(1);
});
//# sourceMappingURL=simpleTaskInteractiveClient.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=ssePollingClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ssePollingClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,95 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* SSE Polling Example Client (SEP-1699)
*
* This example demonstrates client-side behavior during server-initiated
* SSE stream disconnection and automatic reconnection.
*
* Key features demonstrated:
* - Automatic reconnection when server closes SSE stream
* - Event replay via Last-Event-ID header
* - Resumption token tracking via onresumptiontoken callback
*
* Run with: npx tsx src/examples/client/ssePollingClient.ts
* Requires: ssePollingExample.ts server running on port 3001
*/
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const types_js_1 = require("../../types.js");
const SERVER_URL = 'http://localhost:3001/mcp';
async function main() {
console.log('SSE Polling Example Client');
console.log('==========================');
console.log(`Connecting to ${SERVER_URL}...`);
console.log('');
// Create transport with reconnection options
const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(SERVER_URL), {
// Use default reconnection options - SDK handles automatic reconnection
});
// Track the last event ID for debugging
let lastEventId;
// Set up transport error handler to observe disconnections
// Filter out expected errors from SSE reconnection
transport.onerror = error => {
// Skip abort errors during intentional close
if (error.message.includes('AbortError'))
return;
// Show SSE disconnect (expected when server closes stream)
if (error.message.includes('Unexpected end of JSON')) {
console.log('[Transport] SSE stream disconnected - client will auto-reconnect');
return;
}
console.log(`[Transport] Error: ${error.message}`);
};
// Set up transport close handler
transport.onclose = () => {
console.log('[Transport] Connection closed');
};
// Create and connect client
const client = new index_js_1.Client({
name: 'sse-polling-client',
version: '1.0.0'
});
// Set up notification handler to receive progress updates
client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => {
const data = notification.params.data;
console.log(`[Notification] ${data}`);
});
try {
await client.connect(transport);
console.log('[Client] Connected successfully');
console.log('');
// Call the long-task tool
console.log('[Client] Calling long-task tool...');
console.log('[Client] Server will disconnect mid-task to demonstrate polling');
console.log('');
const result = await client.request({
method: 'tools/call',
params: {
name: 'long-task',
arguments: {}
}
}, types_js_1.CallToolResultSchema, {
// Track resumption tokens for debugging
onresumptiontoken: token => {
lastEventId = token;
console.log(`[Event ID] ${token}`);
}
});
console.log('');
console.log('[Client] Tool completed!');
console.log(`[Result] ${JSON.stringify(result.content, null, 2)}`);
console.log('');
console.log(`[Debug] Final event ID: ${lastEventId}`);
}
catch (error) {
console.error('[Error]', error);
}
finally {
await transport.close();
console.log('[Client] Disconnected');
}
}
main().catch(console.error);
//# sourceMappingURL=ssePollingClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ssePollingClient.js","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;GAaG;AACH,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAAwF;AAExF,MAAM,UAAU,GAAG,2BAA2B,CAAC;AAE/C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,iBAAiB,UAAU,KAAK,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAEhB,6CAA6C;IAC7C,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,EAAE;IACrE,wEAAwE;KAC3E,CAAC,C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AC,CAAC;QAC/E,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAEhB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAC/B;YACI,MAAM,EAAE,YAAY;YACpB,MAAM,EAAE;gBACJ,IAAI,EAAE,WAAW;gBACjB,SAAS,EAAE,EAAE;aAChB;SACJ,EACD,+BAAoB,EACpB;YACI,wCAAwC;YACxC,iBAAiB,EAAE,KAAK,CAAC,EAAE;gBACvB,WAAW,GAAG,KAAK,CAAC;gBACpB,OAAO,CAAC,GAAG,CAAC,cAAc,KAAK,EAAE,CAAC,CAAC;YACvC,CAAC;SACJ,CACJ,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,2BAA2B,WAAW,EAAE,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;YAAS,CAAC;QACP,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACzC,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,168 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("../../client/index.js");
const streamableHttp_js_1 = require("../../client/streamableHttp.js");
const sse_js_1 = require("../../client/sse.js");
const types_js_1 = require("../../types.js");
/**
* Simplified Backwards Compatible MCP Client
*
* This client demonstrates backward compatibility with both:
* 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26)
* 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05)
*
* Following the MCP specification for backwards compatibility:
* - Attempts to POST an initialize request to the server URL first (modern transport)
* - If that fails with 4xx status, falls back to GET request for SSE stream (older transport)
*/
// Command line args processing
const args = process.argv.slice(2);
const serverUrl = args[0] || 'http://localhost:3000/mcp';
async function main() {
console.log('MCP Backwards Compatible Client');
console.log('===============================');
console.log(`Connecting to server at: ${serverUrl}`);
let client;
let transport;
try {
// Try connecting with automatic transport detection
const connection = await connectWithBackwardsCompatibility(serverUrl);
client = connection.client;
transport = connection.transport;
// Set up notification handler
client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => {
console.log(`Notification: ${notification.params.level} - ${notification.params.data}`);
});
// DEMO WORKFLOW:
// 1. List available tools
console.log('\n=== Listing Available Tools ===');
await listTools(client);
// 2. Call the notification tool
console.log('\n=== Starting Notification Stream ===');
await startNotificationTool(client);
// 3. Wait for all notifications (5 seconds)
console.log('\n=== Waiting for all notifications ===');
await new Promise(resolve => setTimeout(resolve, 5000));
// 4. Disconnect
console.log('\n=== Disconnecting ===');
await transport.close();
console.log('Disconnected from MCP server');
}
catch (error) {
console.error('Error running client:', error);
process.exit(1);
}
}
/**
* Connect to an MCP server with backwards compatibility
* Following the spec for client backward compatibility
*/
async function connectWithBackwardsCompatibility(url) {
console.log('1. Trying Streamable HTTP transport first...');
// Step 1: Try Streamable HTTP transport first
const client = new index_js_1.Client({
name: 'backwards-compatible-client',
version: '1.0.0'
});
client.onerror = error => {
console.error('Client error:', error);
};
const baseUrl = new URL(url);
try {
// Create modern transport
const streamableTransport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl);
await client.connect(streamableTransport);
console.log('Successfully connected using modern Streamable HTTP transport.');
return {
client,
transport: streamableTransport,
transportType: 'streamable-http'
};
}
catch (error) {
// Step 2: If transport fails, try the older SSE transport
console.log(`StreamableHttp transport connection failed: ${error}`);
console.log('2. Falling back to deprecated HTTP+SSE transport...');
try {
// Create SSE transport pointing to /sse endpoint
const sseTransport = new sse_js_1.SSEClientTransport(baseUrl);
const sseClient = new index_js_1.Client({
name: 'backwards-compatible-client',
version: '1.0.0'
});
await sseClient.connect(sseTransport);
console.log('Successfully connected using deprecated HTTP+SSE transport.');
return {
client: sseClient,
transport: sseTransport,
transportType: 'sse'
};
}
catch (sseError) {
console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`);
throw new Error('Could not connect to server with any available transport');
}
}
}
/**
* List available tools on the server
*/
async function listTools(client) {
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - ${tool.name}: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server: ${error}`);
}
}
/**
* Start a notification stream by calling the notification tool
*/
async function startNotificationTool(client) {
try {
// Call the notification tool using reasonable defaults
const request = {
method: 'tools/call',
params: {
name: 'start-notification-stream',
arguments: {
interval: 1000, // 1 second between notifications
count: 5 // Send 5 notifications
}
}
};
console.log('Calling notification tool...');
const result = await client.request(request, types_js_1.CallToolResultSchema);
console.log('Tool result:');
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else {
console.log(` ${item.type} content:`, item);
}
});
}
catch (error) {
console.log(`Error calling notification tool: ${error}`);
}
}
// Start the client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,gDAAyD;AACzD,6CAMwB;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAA6D,CAAC;IAElE,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CAAC,SAAS,CAAC,CAAC;QACtE,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;QAC3B,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC;QAEjC,8BAA8B;QAC9B,MAAM,CAAC,sBAAsB,CAAC,2CAAgC,EAAE,YAAY,CAAC,EAAE;YAC3E,OAAO,CAAC,GAAG,CAAC,iBAAiB,YAAY,CAAC,MAAM,CAAC,KAAK,MAAM,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;QAC5F,CAAC,CAAC,CAAC;QAEH,iBAAiB;QACjB,0BAA0B;QAC1B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;QACjD,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC;QAExB,gCAAgC;QAChC,OAAO,CAAC,GAAG,CAAC,wCA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oC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,78 @@
import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js';
import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js';
import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js';
import { Response } from 'express';
import { AuthInfo } from '../../server/auth/types.js';
export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore {
private clients;
getClient(clientId: string): Promise<{
redirect_uris: string[];
client_id: string;
token_endpoint_auth_method?: string | undefined;
grant_types?: string[] | undefined;
response_types?: string[] | undefined;
client_name?: string | undefined;
client_uri?: string | undefined;
logo_uri?: string | undefined;
scope?: string | undefined;
contacts?: string[] | undefined;
tos_uri?: string | undefined;
policy_uri?: string | undefined;
jwks_uri?: string | undefined;
jwks?: any;
software_id?: string | undefined;
software_version?: string | undefined;
software_statement?: string | undefined;
client_secret?: string | undefined;
client_id_issued_at?: number | undefined;
client_secret_expires_at?: number | undefined;
} | undefined>;
registerClient(clientMetadata: OAuthClientInformationFull): Promise<{
redirect_uris: string[];
client_id: string;
token_endpoint_auth_method?: string | undefined;
grant_types?: string[] | undefined;
response_types?: string[] | undefined;
client_name?: string | undefined;
client_uri?: string | undefined;
logo_uri?: string | undefined;
scope?: string | undefined;
contacts?: string[] | undefined;
tos_uri?: string | undefined;
policy_uri?: string | undefined;
jwks_uri?: string | undefined;
jwks?: any;
software_id?: string | undefined;
software_version?: string | undefined;
software_statement?: string | undefined;
client_secret?: string | undefined;
client_id_issued_at?: number | undefined;
client_secret_expires_at?: number | undefined;
}>;
}
/**
* 🚨 DEMO ONLY - NOT FOR PRODUCTION
*
* This example demonstrates MCP OAuth flow but lacks some of the features required for production use,
* for example:
* - Persistent token storage
* - Rate limiting
*/
export declare class DemoInMemoryAuthProvider implements OAuthServerProvider {
private validateResource?;
clientsStore: DemoInMemoryClientsStore;
private codes;
private tokens;
constructor(validateResource?: ((resource?: URL) => boolean) | undefined);
authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise<void>;
challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise<string>;
exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise<OAuthTokens>;
exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise<OAuthTokens>;
verifyAccessToken(token: string): Promise<AuthInfo>;
}
export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: {
authServerUrl: URL;
mcpServerUrl: URL;
strictResource: boolean;
}) => OAuthMetadata;
//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"}

View File

@@ -0,0 +1,205 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupAuthServer = exports.DemoInMemoryAuthProvider = exports.DemoInMemoryClientsStore = void 0;
const node_crypto_1 = require("node:crypto");
const express_1 = __importDefault(require("express"));
const router_js_1 = require("../../server/auth/router.js");
const auth_utils_js_1 = require("../../shared/auth-utils.js");
const errors_js_1 = require("../../server/auth/errors.js");
class DemoInMemoryClientsStore {
constructor() {
this.clients = new Map();
}
async getClient(clientId) {
return this.clients.get(clientId);
}
async registerClient(clientMetadata) {
this.clients.set(clientMetadata.client_id, clientMetadata);
return clientMetadata;
}
}
exports.DemoInMemoryClientsStore = DemoInMemoryClientsStore;
/**
* 🚨 DEMO ONLY - NOT FOR PRODUCTION
*
* This example demonstrates MCP OAuth flow but lacks some of the features required for production use,
* for example:
* - Persistent token storage
* - Rate limiting
*/
class DemoInMemoryAuthProvider {
constructor(validateResource) {
this.validateResource = validateResource;
this.clientsStore = new DemoInMemoryClientsStore();
this.codes = new Map();
this.tokens = new Map();
}
async authorize(client, params, res) {
const code = (0, node_crypto_1.randomUUID)();
const searchParams = new URLSearchParams({
code
});
if (params.state !== undefined) {
searchParams.set('state', params.state);
}
this.codes.set(code, {
client,
params
});
// Simulate a user login
// Set a secure HTTP-only session cookie with authorization info
if (res.cookie) {
const authCookieData = {
userId: 'demo_user',
name: 'Demo User',
timestamp: Date.now()
};
res.cookie('demo_session', JSON.stringify(authCookieData), {
httpOnly: true,
secure: false, // In production, this should be true
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes
path: '/' // Available to all routes
});
}
if (!client.redirect_uris.includes(params.redirectUri)) {
throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri');
}
const targetUrl = new URL(params.redirectUri);
targetUrl.search = searchParams.toString();
res.redirect(targetUrl.toString());
}
async challengeForAuthorizationCode(client, authorizationCode) {
// Store the challenge with the code data
const codeData = this.codes.get(authorizationCode);
if (!codeData) {
throw new Error('Invalid authorization code');
}
return codeData.params.codeChallenge;
}
async exchangeAuthorizationCode(client, authorizationCode,
// Note: code verifier is checked in token.ts by default
// it's unused here for that reason.
_codeVerifier) {
const codeData = this.codes.get(authorizationCode);
if (!codeData) {
throw new Error('Invalid authorization code');
}
if (codeData.client.client_id !== client.client_id) {
throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`);
}
if (this.validateResource && !this.validateResource(codeData.params.resource)) {
throw new Error(`Invalid resource: ${codeData.params.resource}`);
}
this.codes.delete(authorizationCode);
const token = (0, node_crypto_1.randomUUID)();
const tokenData = {
token,
clientId: client.client_id,
scopes: codeData.params.scopes || [],
expiresAt: Date.now() + 3600000, // 1 hour
resource: codeData.params.resource,
type: 'access'
};
this.tokens.set(token, tokenData);
return {
access_token: token,
token_type: 'bearer',
expires_in: 3600,
scope: (codeData.params.scopes || []).join(' ')
};
}
async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) {
throw new Error('Not implemented for example demo');
}
async verifyAccessToken(token) {
const tokenData = this.tokens.get(token);
if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) {
throw new Error('Invalid or expired token');
}
return {
token,
clientId: tokenData.clientId,
scopes: tokenData.scopes,
expiresAt: Math.floor(tokenData.expiresAt / 1000),
resource: tokenData.resource
};
}
}
exports.DemoInMemoryAuthProvider = DemoInMemoryAuthProvider;
const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => {
// Create separate auth server app
// NOTE: This is a separate app on a separate port to illustrate
// how to separate an OAuth Authorization Server from a Resource
// server in the SDK. The SDK is not intended to be provide a standalone
// authorization server.
const validateResource = strictResource
? (resource) => {
if (!resource)
return false;
const expectedResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(mcpServerUrl);
return resource.toString() === expectedResource.toString();
}
: undefined;
const provider = new DemoInMemoryAuthProvider(validateResource);
const authApp = (0, express_1.default)();
authApp.use(express_1.default.json());
// For introspection requests
authApp.use(express_1.default.urlencoded());
// Add OAuth routes to the auth server
// NOTE: this will also add a protected resource metadata route,
// but it won't be used, so leave it.
authApp.use((0, router_js_1.mcpAuthRouter)({
provider,
issuerUrl: authServerUrl,
scopesSupported: ['mcp:tools']
}));
authApp.post('/introspect', async (req, res) => {
try {
const { token } = req.body;
if (!token) {
res.status(400).json({ error: 'Token is required' });
return;
}
const tokenInfo = await provider.verifyAccessToken(token);
res.json({
active: true,
client_id: tokenInfo.clientId,
scope: tokenInfo.scopes.join(' '),
exp: tokenInfo.expiresAt,
aud: tokenInfo.resource
});
return;
}
catch (error) {
res.status(401).json({
active: false,
error: 'Unauthorized',
error_description: `Invalid token: ${error}`
});
}
});
const auth_port = authServerUrl.port;
// Start the auth server
authApp.listen(auth_port, error => {
if (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
console.log(`OAuth Authorization Server listening on port ${auth_port}`);
});
// Note: we could fetch this from the server, but then we end up
// with some top level async which gets annoying.
const oauthMetadata = (0, router_js_1.createOAuthMetadata)({
provider,
issuerUrl: authServerUrl,
scopesSupported: ['mcp:tools']
});
oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href;
return oauthMetadata;
};
exports.setupAuthServer = setupAuthServer;
//# sourceMappingURL=demoInMemoryOAuthProvider.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=elicitationFormExample.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,460 @@
"use strict";
// Run with: npx tsx src/examples/server/elicitationFormExample.ts
//
// This example demonstrates how to use form elicitation to collect structured user input
// with JSON Schema validation via a local HTTP server with SSE streaming.
// Form elicitation allows servers to request *non-sensitive* user input through the client
// with schema-based validation.
// Note: See also elicitationUrlExample.ts for an example of using URL elicitation
// to collect *sensitive* user input via a browser.
Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = require("node:crypto");
const mcp_js_1 = require("../../server/mcp.js");
const streamableHttp_js_1 = require("../../server/streamableHttp.js");
const types_js_1 = require("../../types.js");
const express_js_1 = require("../../server/express.js");
// Factory to create a new MCP server per session.
// Each session needs its own server+transport pair to avoid cross-session contamination.
const getServer = () => {
// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults
// The validator supports format validation (email, date, etc.) if ajv-formats is installed
const mcpServer = new mcp_js_1.McpServer({
name: 'form-elicitation-example-server',
version: '1.0.0'
}, {
capabilities: {}
});
/**
* Example 1: Simple user registration tool
* Collects username, email, and password from the user
*/
mcpServer.registerTool('register_user', {
description: 'Register a new user account by collecting their information',
inputSchema: {}
}, async () => {
try {
// Request user information through form elicitation
const result = await mcpServer.server.elicitInput({
mode: 'form',
message: 'Please provide your registration information:',
requestedSchema: {
type: 'object',
properties: {
username: {
type: 'string',
title: 'Username',
description: 'Your desired username (3-20 characters)',
minLength: 3,
maxLength: 20
},
email: {
type: 'string',
title: 'Email',
description: 'Your email address',
format: 'email'
},
password: {
type: 'string',
title: 'Password',
description: 'Your password (min 8 characters)',
minLength: 8
},
newsletter: {
type: 'boolean',
title: 'Newsletter',
description: 'Subscribe to newsletter?',
default: false
},
role: {
type: 'string',
title: 'Role',
description: 'Your primary role',
oneOf: [
{ const: 'developer', title: 'Developer' },
{ const: 'designer', title: 'Designer' },
{ const: 'manager', title: 'Manager' },
{ const: 'other', title: 'Other' }
],
default: 'developer'
},
interests: {
type: 'array',
title: 'Interests',
description: 'Select your areas of interest',
items: {
type: 'string',
enum: ['frontend', 'backend', 'mobile', 'devops', 'ai']
},
minItems: 1,
maxItems: 3
}
},
required: ['username', 'email', 'password']
}
});
// Handle the different possible actions
if (result.action === 'accept' && result.content) {
const { username, email, newsletter } = result.content;
return {
content: [
{
type: 'text',
text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}`
}
]
};
}
else if (result.action === 'decline') {
return {
content: [
{
type: 'text',
text: 'Registration cancelled by user.'
}
]
};
}
else {
return {
content: [
{
type: 'text',
text: 'Registration was cancelled.'
}
]
};
}
}
catch (error) {
return {
content: [
{
type: 'text',
text: `Registration failed: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
});
/**
* Example 2: Multi-step workflow with multiple form elicitation requests
* Demonstrates how to collect information in multiple steps
*/
mcpServer.registerTool('create_event', {
description: 'Create a calendar event by collecting event details',
inputSchema: {}
}, async () => {
try {
// Step 1: Collect basic event information
const basicInfo = await mcpServer.server.elicitInput({
mode: 'form',
message: 'Step 1: Enter basic event information',
requestedSchema: {
type: 'object',
properties: {
title: {
type: 'string',
title: 'Event Title',
description: 'Name of the event',
minLength: 1
},
description: {
type: 'string',
title: 'Description',
description: 'Event description (optional)'
}
},
required: ['title']
}
});
if (basicInfo.action !== 'accept' || !basicInfo.content) {
return {
content: [{ type: 'text', text: 'Event creation cancelled.' }]
};
}
// Step 2: Collect date and time
const dateTime = await mcpServer.server.elicitInput({
mode: 'form',
message: 'Step 2: Enter date and time',
requestedSchema: {
type: 'object',
properties: {
date: {
type: 'string',
title: 'Date',
description: 'Event date',
format: 'date'
},
startTime: {
type: 'string',
title: 'Start Time',
description: 'Event start time (HH:MM)'
},
duration: {
type: 'integer',
title: 'Duration',
description: 'Duration in minutes',
minimum: 15,
maximum: 480
}
},
required: ['date', 'startTime', 'duration']
}
});
if (dateTime.action !== 'accept' || !dateTime.content) {
return {
content: [{ type: 'text', text: 'Event creation cancelled.' }]
};
}
// Combine all collected information
const event = {
...basicInfo.content,
...dateTime.content
};
return {
content: [
{
type: 'text',
text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}`
}
]
};
}
catch (error) {
return {
content: [
{
type: 'text',
text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
});
/**
* Example 3: Collecting address information
* Demonstrates validation with patterns and optional fields
*/
mcpServer.registerTool('update_shipping_address', {
description: 'Update shipping address with validation',
inputSchema: {}
}, async () => {
try {
const result = await mcpServer.server.elicitInput({
mode: 'form',
message: 'Please provide your shipping address:',
requestedSchema: {
type: 'object',
properties: {
name: {
type: 'string',
title: 'Full Name',
description: 'Recipient name',
minLength: 1
},
street: {
type: 'string',
title: 'Street Address',
minLength: 1
},
city: {
type: 'string',
title: 'City',
minLength: 1
},
state: {
type: 'string',
title: 'State/Province',
minLength: 2,
maxLength: 2
},
zipCode: {
type: 'string',
title: 'ZIP/Postal Code',
description: '5-digit ZIP code'
},
phone: {
type: 'string',
title: 'Phone Number (optional)',
description: 'Contact phone number'
}
},
required: ['name', 'street', 'city', 'state', 'zipCode']
}
});
if (result.action === 'accept' && result.content) {
return {
content: [
{
type: 'text',
text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}`
}
]
};
}
else if (result.action === 'decline') {
return {
content: [{ type: 'text', text: 'Address update cancelled by user.' }]
};
}
else {
return {
content: [{ type: 'text', text: 'Address update was cancelled.' }]
};
}
}
catch (error) {
return {
content: [
{
type: 'text',
text: `Address update failed: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
});
return mcpServer;
};
async function main() {
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
const app = (0, express_js_1.createMcpExpressApp)();
// Map to store transports by session ID
const transports = {};
// MCP POST endpoint
const mcpPostHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
if (sessionId) {
console.log(`Received MCP request for session: ${sessionId}`);
}
try {
let transport;
if (sessionId && transports[sessionId]) {
// Reuse existing transport for this session
transport = transports[sessionId];
}
else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) {
// New initialization request - create new transport
transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(),
onsessioninitialized: sessionId => {
// Store the transport by session ID when session is initialized
console.log(`Session initialized with ID: ${sessionId}`);
transports[sessionId] = transport;
}
});
// Set up onclose handler to clean up transport when closed
transport.onclose = () => {
const sid = transport.sessionId;
if (sid && transports[sid]) {
console.log(`Transport closed for session ${sid}, removing from transports map`);
delete transports[sid];
}
};
// Create a new server per session and connect it to the transport
const mcpServer = getServer();
await mcpServer.connect(transport);
await transport.handleRequest(req, res, req.body);
return;
}
else {
// Invalid request - no session ID or not initialization request
res.status(400).json({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Bad Request: No valid session ID provided'
},
id: null
});
return;
}
// Handle the request with existing transport
await transport.handleRequest(req, res, req.body);
}
catch (error) {
console.error('Error handling MCP request:', error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal server error'
},
id: null
});
}
}
};
app.post('/mcp', mcpPostHandler);
// Handle GET requests for SSE streams
const mcpGetHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
console.log(`Establishing SSE stream for session ${sessionId}`);
const transport = transports[sessionId];
await transport.handleRequest(req, res);
};
app.get('/mcp', mcpGetHandler);
// Handle DELETE requests for session termination
const mcpDeleteHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
console.log(`Received session termination request for session ${sessionId}`);
try {
const transport = transports[sessionId];
await transport.handleRequest(req, res);
}
catch (error) {
console.error('Error handling session termination:', error);
if (!res.headersSent) {
res.status(500).send('Error processing session termination');
}
}
};
app.delete('/mcp', mcpDeleteHandler);
// Start listening
app.listen(PORT, error => {
if (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`);
console.log('Available tools:');
console.log(' - register_user: Collect user registration information');
console.log(' - create_event: Multi-step event creation');
console.log(' - update_shipping_address: Collect and validate address');
console.log('\nConnect your MCP client to this server using the HTTP transport.');
});
// Handle server shutdown
process.on('SIGINT', async () => {
console.log('Shutting down server...');
// Close all active transports to properly clean up resources
for (const sessionId in transports) {
try {
console.log(`Closing transport for session ${sessionId}`);
await transports[sessionId].close();
delete transports[sessionId];
}
catch (error) {
console.error(`Error closing transport for session ${sessionId}:`, error);
}
}
console.log('Server shutdown complete');
process.exit(0);
});
}
main().catch(error => {
console.error('Server error:', error);
process.exit(1);
});
//# sourceMappingURL=elicitationFormExample.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=elicitationUrlExample.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,656 @@
"use strict";
// Run with: npx tsx src/examples/server/elicitationUrlExample.ts
//
// This example demonstrates how to use URL elicitation to securely collect
// *sensitive* user input in a remote (HTTP) server.
// URL elicitation allows servers to prompt the end-user to open a URL in their browser
// to collect sensitive information.
// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation
// to collect *non-sensitive* user input with a structured schema.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const node_crypto_1 = require("node:crypto");
const zod_1 = require("zod");
const mcp_js_1 = require("../../server/mcp.js");
const express_js_1 = require("../../server/express.js");
const streamableHttp_js_1 = require("../../server/streamableHttp.js");
const router_js_1 = require("../../server/auth/router.js");
const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js");
const types_js_1 = require("../../types.js");
const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js");
const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js");
const auth_utils_js_1 = require("../../shared/auth-utils.js");
const cors_1 = __importDefault(require("cors"));
// Create an MCP server with implementation details
const getServer = () => {
const mcpServer = new mcp_js_1.McpServer({
name: 'url-elicitation-http-server',
version: '1.0.0'
}, {
capabilities: { logging: {} }
});
mcpServer.registerTool('payment-confirm', {
description: 'A tool that confirms a payment directly with a user',
inputSchema: {
cartId: zod_1.z.string().describe('The ID of the cart to confirm')
}
}, async ({ cartId }, extra) => {
/*
In a real world scenario, there would be some logic here to check if the user has the provided cartId.
For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment)
*/
const sessionId = extra.sessionId;
if (!sessionId) {
throw new Error('Expected a Session ID');
}
// Create and track the elicitation
const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId));
throw new types_js_1.UrlElicitationRequiredError([
{
mode: 'url',
message: 'This tool requires a payment confirmation. Open the link to confirm payment!',
url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`,
elicitationId
}
]);
});
mcpServer.registerTool('third-party-auth', {
description: 'A demo tool that requires third-party OAuth credentials',
inputSchema: {
param1: zod_1.z.string().describe('First parameter')
}
}, async (_, extra) => {
/*
In a real world scenario, there would be some logic here to check if we already have a valid access token for the user.
Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`.
If we do, we can just return the result of the tool call.
If we don't, we can throw an ElicitationRequiredError to request the user to authenticate.
For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate).
*/
const sessionId = extra.sessionId;
if (!sessionId) {
throw new Error('Expected a Session ID');
}
// Create and track the elicitation
const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId));
// Simulate OAuth callback and token exchange after 5 seconds
// In a real app, this would be called from your OAuth callback handler
setTimeout(() => {
console.log(`Simulating OAuth token received for elicitation ${elicitationId}`);
completeURLElicitation(elicitationId);
}, 5000);
throw new types_js_1.UrlElicitationRequiredError([
{
mode: 'url',
message: 'This tool requires access to your example.com account. Open the link to authenticate!',
url: 'https://www.example.com/oauth/authorize',
elicitationId
}
]);
});
return mcpServer;
};
const elicitationsMap = new Map();
// Clean up old elicitations after 1 hour to prevent memory leaks
const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour
const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
function cleanupOldElicitations() {
const now = new Date();
for (const [id, metadata] of elicitationsMap.entries()) {
if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) {
elicitationsMap.delete(id);
console.log(`Cleaned up expired elicitation: ${id}`);
}
}
}
setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS);
/**
* Elicitation IDs must be unique strings within the MCP session
* UUIDs are used in this example for simplicity
*/
function generateElicitationId() {
return (0, node_crypto_1.randomUUID)();
}
/**
* Helper function to create and track a new elicitation.
*/
function generateTrackedElicitation(sessionId, createCompletionNotifier) {
const elicitationId = generateElicitationId();
// Create a Promise and its resolver for tracking completion
let completeResolver;
const completedPromise = new Promise(resolve => {
completeResolver = resolve;
});
const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined;
// Store the elicitation in our map
elicitationsMap.set(elicitationId, {
status: 'pending',
completedPromise,
completeResolver: completeResolver,
createdAt: new Date(),
sessionId,
completionNotifier
});
return elicitationId;
}
/**
* Helper function to complete an elicitation.
*/
function completeURLElicitation(elicitationId) {
const elicitation = elicitationsMap.get(elicitationId);
if (!elicitation) {
console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`);
return;
}
if (elicitation.status === 'complete') {
console.warn(`Elicitation already complete: ${elicitationId}`);
return;
}
// Update metadata
elicitation.status = 'complete';
// Send completion notification to the client
if (elicitation.completionNotifier) {
console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`);
elicitation.completionNotifier().catch(error => {
console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error);
});
}
// Resolve the promise to unblock any waiting code
elicitation.completeResolver();
}
const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000;
const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001;
const app = (0, express_js_1.createMcpExpressApp)();
// Allow CORS all domains, expose the Mcp-Session-Id header
app.use((0, cors_1.default)({
origin: '*', // Allow all origins
exposedHeaders: ['Mcp-Session-Id'],
credentials: true // Allow cookies to be sent cross-origin
}));
// Set up OAuth (required for this example)
let authMiddleware = null;
// Create auth middleware for MCP endpoints
const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`);
const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`);
const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: true });
const tokenVerifier = {
verifyAccessToken: async (token) => {
const endpoint = oauthMetadata.introspection_endpoint;
if (!endpoint) {
throw new Error('No token verification endpoint available in metadata');
}
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
token: token
}).toString()
});
if (!response.ok) {
const text = await response.text().catch(() => null);
throw new Error(`Invalid or expired token: ${text}`);
}
const data = await response.json();
if (!data.aud) {
throw new Error(`Resource Indicator (RFC8707) missing`);
}
if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) {
throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`);
}
// Convert the response to AuthInfo format
return {
token,
clientId: data.client_id,
scopes: data.scope ? data.scope.split(' ') : [],
expiresAt: data.exp
};
}
};
// Add metadata routes to the main MCP server
app.use((0, router_js_1.mcpAuthMetadataRouter)({
oauthMetadata,
resourceServerUrl: mcpServerUrl,
scopesSupported: ['mcp:tools'],
resourceName: 'MCP Demo Server'
}));
authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({
verifier: tokenVerifier,
requiredScopes: [],
resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl)
});
/**
* API Key Form Handling
*
* Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol.
* URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client.
**/
async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) {
if (!sessionId) {
console.error('No session ID provided');
throw new Error('Expected a Session ID to track elicitation');
}
console.log('🔑 URL elicitation demo: Requesting API key from client...');
const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier);
try {
const result = await sender({
mode: 'url',
message: 'Please provide your API key to authenticate with this server',
// Host the form on the same server. In a real app, you might coordinate passing these state variables differently.
url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`,
elicitationId
});
switch (result.action) {
case 'accept':
console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)');
// Wait for the API key to be submitted via the form
// The form submission will complete the elicitation
break;
default:
console.log('🔑 URL elicitation demo: Client declined to provide an API key');
// In a real app, this might close the connection, but for the demo, we'll continue
break;
}
}
catch (error) {
console.error('Error during API key elicitation:', error);
}
}
// API Key Form endpoint - serves a simple HTML form
app.get('/api-key-form', (req, res) => {
const mcpSessionId = req.query.session;
const elicitationId = req.query.elicitation;
if (!mcpSessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie
// In production, this is often handled by some user auth middleware to ensure the user has a valid session
// This session is different from the MCP session.
// This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in.
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// Serve a simple HTML form
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Submit Your API Key</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; }
input[type="text"] { width: 100%; padding: 8px; margin: 10px 0; box-sizing: border-box; }
button { background: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }
button:hover { background: #0056b3; }
.user { background: #d1ecf1; padding: 8px; margin-bottom: 10px; }
.info { color: #666; font-size: 0.9em; margin-top: 20px; }
</style>
</head>
<body>
<h1>API Key Required</h1>
<div class="user">✓ Logged in as: <strong>${userSession.name}</strong></div>
<form method="POST" action="/api-key-form">
<input type="hidden" name="session" value="${mcpSessionId}" />
<input type="hidden" name="elicitation" value="${elicitationId}" />
<label>API Key:<br>
<input type="text" name="apiKey" required placeholder="Enter your API key" />
</label>
<button type="submit">Submit</button>
</form>
<div class="info">This is a demo showing how a server can securely elicit sensitive data from a user using a URL.</div>
</body>
</html>
`);
});
// Handle API key form submission
app.post('/api-key-form', express_1.default.urlencoded(), (req, res) => {
const { session: sessionId, apiKey, elicitation: elicitationId } = req.body;
if (!sessionId || !apiKey || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie here too
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// A real app might store this API key to be used later for the user.
console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`);
// If we have an elicitationId, complete the elicitation
completeURLElicitation(elicitationId);
// Send a success response
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.success { background: #d4edda; color: #155724; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="success">
<h1>Success ✓</h1>
<p>API key received.</p>
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
});
// Helper to get the user session from the demo_session cookie
function getUserSessionCookie(cookieHeader) {
if (!cookieHeader)
return null;
const cookies = cookieHeader.split(';');
for (const cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'demo_session' && value) {
try {
return JSON.parse(decodeURIComponent(value));
}
catch (error) {
console.error('Failed to parse demo_session cookie:', error);
return null;
}
}
}
return null;
}
/**
* Payment Confirmation Form Handling
*
* This demonstrates how a server can use URL-mode elicitation to get user confirmation
* for sensitive operations like payment processing.
**/
// Payment Confirmation Form endpoint - serves a simple HTML form
app.get('/confirm-payment', (req, res) => {
const mcpSessionId = req.query.session;
const elicitationId = req.query.elicitation;
const cartId = req.query.cartId;
if (!mcpSessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie
// In production, this is often handled by some user auth middleware to ensure the user has a valid session
// This session is different from the MCP session.
// This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in.
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// Serve a simple HTML form
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Confirm Payment</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; }
button { background: #28a745; color: white; padding: 12px 24px; border: none; cursor: pointer; font-size: 16px; width: 100%; margin: 10px 0; }
button:hover { background: #218838; }
button.cancel { background: #6c757d; }
button.cancel:hover { background: #5a6268; }
.user { background: #d1ecf1; padding: 8px; margin-bottom: 10px; }
.cart-info { background: #f8f9fa; padding: 12px; margin: 15px 0; border-left: 4px solid #007bff; }
.info { color: #666; font-size: 0.9em; margin-top: 20px; }
.warning { background: #fff3cd; color: #856404; padding: 12px; margin: 15px 0; border-left: 4px solid #ffc107; }
</style>
</head>
<body>
<h1>Confirm Payment</h1>
<div class="user">✓ Logged in as: <strong>${userSession.name}</strong></div>
${cartId ? `<div class="cart-info"><strong>Cart ID:</strong> ${cartId}</div>` : ''}
<div class="warning">
<strong>⚠️ Please review your order before confirming.</strong>
</div>
<form method="POST" action="/confirm-payment">
<input type="hidden" name="session" value="${mcpSessionId}" />
<input type="hidden" name="elicitation" value="${elicitationId}" />
${cartId ? `<input type="hidden" name="cartId" value="${cartId}" />` : ''}
<button type="submit" name="action" value="confirm">Confirm Payment</button>
<button type="submit" name="action" value="cancel" class="cancel">Cancel</button>
</form>
<div class="info">This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.</div>
</body>
</html>
`);
});
// Handle Payment Confirmation form submission
app.post('/confirm-payment', express_1.default.urlencoded(), (req, res) => {
const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body;
if (!sessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie here too
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
if (action === 'confirm') {
// A real app would process the payment here
console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`);
// Complete the elicitation
completeURLElicitation(elicitationId);
// Send a success response
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Payment Confirmed</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.success { background: #d4edda; color: #155724; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="success">
<h1>Payment Confirmed ✓</h1>
<p>Your payment has been successfully processed.</p>
${cartId ? `<p><strong>Cart ID:</strong> ${cartId}</p>` : ''}
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
}
else if (action === 'cancel') {
console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`);
// The client will still receive a notifications/elicitation/complete notification,
// which indicates that the out-of-band interaction is complete (but not necessarily successful)
completeURLElicitation(elicitationId);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Payment Cancelled</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.info { background: #d1ecf1; color: #0c5460; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="info">
<h1>Payment Cancelled</h1>
<p>Your payment has been cancelled.</p>
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
}
else {
res.status(400).send('<h1>Error</h1><p>Invalid action</p>');
}
});
// Map to store transports by session ID
const transports = {};
const sessionsNeedingElicitation = {};
// MCP POST endpoint
const mcpPostHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`);
try {
let transport;
if (sessionId && transports[sessionId]) {
// Reuse existing transport
transport = transports[sessionId];
}
else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) {
const server = getServer();
// New initialization request
const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore();
transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(),
eventStore, // Enable resumability
onsessioninitialized: sessionId => {
// Store the transport by session ID when session is initialized
// This avoids race conditions where requests might come in before the session is stored
console.log(`Session initialized with ID: ${sessionId}`);
transports[sessionId] = transport;
sessionsNeedingElicitation[sessionId] = {
elicitationSender: params => server.server.elicitInput(params),
createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId)
};
}
});
// Set up onclose handler to clean up transport when closed
transport.onclose = () => {
const sid = transport.sessionId;
if (sid && transports[sid]) {
console.log(`Transport closed for session ${sid}, removing from transports map`);
delete transports[sid];
delete sessionsNeedingElicitation[sid];
}
};
// Connect the transport to the MCP server BEFORE handling the request
// so responses can flow back through the same transport
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
return; // Already handled
}
else {
// Invalid request - no session ID or not initialization request
res.status(400).json({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Bad Request: No valid session ID provided'
},
id: null
});
return;
}
// Handle the request with existing transport - no need to reconnect
// The existing transport is already connected to the server
await transport.handleRequest(req, res, req.body);
}
catch (error) {
console.error('Error handling MCP request:', error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal server error'
},
id: null
});
}
}
};
// Set up routes with auth middleware
app.post('/mcp', authMiddleware, mcpPostHandler);
// Handle GET requests for SSE streams (using built-in support from StreamableHTTP)
const mcpGetHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
// Check for Last-Event-ID header for resumability
const lastEventId = req.headers['last-event-id'];
if (lastEventId) {
console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`);
}
else {
console.log(`Establishing new SSE stream for session ${sessionId}`);
}
const transport = transports[sessionId];
await transport.handleRequest(req, res);
if (sessionsNeedingElicitation[sessionId]) {
const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId];
// Send an elicitation request to the client in the background
sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier)
.then(() => {
// Only delete on successful send for this demo
delete sessionsNeedingElicitation[sessionId];
console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`);
})
.catch(error => {
console.error('Error sending API key elicitation:', error);
// Keep in map to potentially retry on next reconnect
});
}
};
// Set up GET route with conditional auth middleware
app.get('/mcp', authMiddleware, mcpGetHandler);
// Handle DELETE requests for session termination (according to MCP spec)
const mcpDeleteHandler = async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
console.log(`Received session termination request for session ${sessionId}`);
try {
const transport = transports[sessionId];
await transport.handleRequest(req, res);
}
catch (error) {
console.error('Error handling session termination:', error);
if (!res.headersSent) {
res.status(500).send('Error processing session termination');
}
}
};
// Set up DELETE route with auth middleware
app.delete('/mcp', authMiddleware, mcpDeleteHandler);
app.listen(MCP_PORT, error => {
if (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`);
});
// Handle server shutdown
process.on('SIGINT', async () => {
console.log('Shutting down server...');
// Close all active transports to properly clean up resources
for (const sessionId in transports) {
try {
console.log(`Closing transport for session ${sessionId}`);
await transports[sessionId].close();
delete transports[sessionId];
delete sessionsNeedingElicitation[sessionId];
}
catch (error) {
console.error(`Error closing transport for session ${sessionId}:`, error);
}
}
console.log('Server shutdown complete');
process.exit(0);
});
//# sourceMappingURL=elicitationUrlExample.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
/**
* Example MCP server using Hono with WebStandardStreamableHTTPServerTransport
*
* This example demonstrates using the Web Standard transport directly with Hono,
* which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc.
*
* Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts
*/
export {};
//# sourceMappingURL=honoWebStandardStreamableHttp.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"honoWebStandardStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}

View File

@@ -0,0 +1,85 @@
"use strict";
/**
* Example MCP server using Hono with WebStandardStreamableHTTPServerTransport
*
* This example demonstrates using the Web Standard transport directly with Hono,
* which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc.
*
* Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const hono_1 = require("hono");
const cors_1 = require("hono/cors");
const node_server_1 = require("@hono/node-server");
const z = __importStar(require("zod/v4"));
const mcp_js_1 = require("../../server/mcp.js");
const webStandardStreamableHttp_js_1 = require("../../server/webStandardStreamableHttp.js");
// Factory function to create a new MCP server per request (stateless mode)
const getServer = () => {
const server = new mcp_js_1.McpServer({
name: 'hono-webstandard-mcp-server',
version: '1.0.0'
});
// Register a simple greeting tool
server.registerTool('greet', {
title: 'Greeting Tool',
description: 'A simple greeting tool',
inputSchema: { name: z.string().describe('Name to greet') }
}, async ({ name }) => {
return {
content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }]
};
});
return server;
};
// Create the Hono app
const app = new hono_1.Hono();
// Enable CORS for all origins
app.use('*', (0, cors_1.cors)({
origin: '*',
allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'],
exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']
}));
// Health check endpoint
app.get('/health', c => c.json({ status: 'ok' }));
// MCP endpoint - create a fresh transport and server per request (stateless)
app.all('/mcp', async (c) => {
const transport = new webStandardStreamableHttp_js_1.WebStandardStreamableHTTPServerTransport();
const server = getServer();
await server.connect(transport);
return transport.handleRequest(c.req.raw);
});
// Start the server
const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000;
console.log(`Starting Hono MCP server on port ${PORT}`);
console.log(`Health check: http://localhost:${PORT}/health`);
console.log(`MCP endpoint: http://localhost:${PORT}/mcp`);
(0, node_server_1.serve)({
fetch: app.fetch,
port: PORT
});
//# sourceMappingURL=honoWebStandardStreamableHttp.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"honoWebStandardStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+BAA4B;AAC5B,oCAAiC;AACjC,mDAA0C;AAC1C,0CAA4B;AAC5B,gDAAgD;AAChD,4FAAqG;AAGrG,2EAA2E;AAC3E,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAA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AM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC9C,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAE9E,OAAO,CAAC,GAAG,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAC;AACxD,OAAO,CAAC,GAAG,CAAC,kCAAkC,IAAI,SAAS,CAAC,CAAC;AAC7D,OAAO,CAAC,GAAG,CAAC,kCAAkC,IAAI,MAAM,CAAC,CAAC;AAE1D,IAAA,mBAAK,EAAC;IACF,KAAK,EAAE,GAAG,CAAC,KAAK;IAChB,IAAI,EAAE,IAAI;CACb,CAAC,CAAC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,171 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = require("node:crypto");
const mcp_js_1 = require("../../server/mcp.js");
const streamableHttp_js_1 = require("../../server/streamableHttp.js");
const z = __importStar(require("zod/v4"));
const types_js_1 = require("../../types.js");
const express_js_1 = require("../../server/express.js");
// Create an MCP server with implementation details
const getServer = () => {
const server = new mcp_js_1.McpServer({
name: 'json-response-streamable-http-server',
version: '1.0.0'
}, {
capabilities: {
logging: {}
}
});
// Register a simple tool that returns a greeting
server.registerTool('greet', {
description: 'A simple greeting tool',
inputSchema: {
name: z.string().describe('Name to greet')
}
}, async ({ name }) => {
return {
content: [
{
type: 'text',
text: `Hello, ${name}!`
}
]
};
});
// Register a tool that sends multiple greetings with notifications
server.registerTool('multi-greet', {
description: 'A tool that sends different greetings with delays between them',
inputSchema: {
name: z.string().describe('Name to greet')
}
}, async ({ name }, extra) => {
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await server.sendLoggingMessage({
level: 'debug',
data: `Starting multi-greet for ${name}`
}, extra.sessionId);
await sleep(1000); // Wait 1 second before first greeting
await server.sendLoggingMessage({
level: 'info',
data: `Sending first greeting to ${name}`
}, extra.sessionId);
await sleep(1000); // Wait another second before second greeting
await server.sendLoggingMessage({
level: 'info',
data: `Sending second greeting to ${name}`
}, extra.sessionId);
return {
content: [
{
type: 'text',
text: `Good morning, ${name}!`
}
]
};
});
return server;
};
const app = (0, express_js_1.createMcpExpressApp)();
// Map to store transports by session ID
const transports = {};
app.post('/mcp', async (req, res) => {
console.log('Received MCP request:', req.body);
try {
// Check for existing session ID
const sessionId = req.headers['mcp-session-id'];
let transport;
if (sessionId && transports[sessionId]) {
// Reuse existing transport
transport = transports[sessionId];
}
else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) {
// New initialization request - use JSON response mode
transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(),
enableJsonResponse: true, // Enable JSON response mode
onsessioninitialized: sessionId => {
// Store the transport by session ID when session is initialized
// This avoids race conditions where requests might come in before the session is stored
console.log(`Session initialized with ID: ${sessionId}`);
transports[sessionId] = transport;
}
});
// Connect the transport to the MCP server BEFORE handling the request
const server = getServer();
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
return; // Already handled
}
else {
// Invalid request - no session ID or not initialization request
res.status(400).json({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Bad Request: No valid session ID provided'
},
id: null
});
return;
}
// Handle the request with existing transport - no need to reconnect
await transport.handleRequest(req, res, req.body);
}
catch (error) {
console.error('Error handling MCP request:', error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal server error'
},
id: null
});
}
}
});
// Handle GET requests for SSE streams according to spec
app.get('/mcp', async (req, res) => {
// Since this is a very simple example, we don't support GET requests for this server
// The spec requires returning 405 Method Not Allowed in this case
res.status(405).set('Allow', 'POST').send('Method Not Allowed');
});
// Start the server
const PORT = 3000;
app.listen(PORT, error => {
if (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
console.log(`MCP Streamable HTTP Server listening on port ${PORT}`);
});
// Handle server shutdown
process.on('SIGINT', async () => {
console.log('Shutting down server...');
process.exit(0);
});
//# sourceMappingURL=jsonResponseStreamableHttp.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,0CAA4B;AAC5B,6CAAqE;AACrE,wDAA8D;AAE9D,mDAAmD;AACnD,MA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wD;AACxD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IAClD,qFAAqF;IACrF,kEAAkE;IAClE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env node
/**
* Example MCP server using the high-level McpServer API with outputSchema
* This demonstrates how to easily create tools with structured output
*/
export {};
//# sourceMappingURL=mcpServerOutputSchema.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"}

View File

@@ -0,0 +1,95 @@
#!/usr/bin/env node
"use strict";
/**
* Example MCP server using the high-level McpServer API with outputSchema
* This demonstrates how to easily create tools with structured output
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const mcp_js_1 = require("../../server/mcp.js");
const stdio_js_1 = require("../../server/stdio.js");
const z = __importStar(require("zod/v4"));
const server = new mcp_js_1.McpServer({
name: 'mcp-output-schema-high-level-example',
version: '1.0.0'
});
// Define a tool with structured output - Weather data
server.registerTool('get_weather', {
description: 'Get weather information for a city',
inputSchema: {
city: z.string().describe('City name'),
country: z.string().describe('Country code (e.g., US, UK)')
},
outputSchema: {
temperature: z.object({
celsius: z.number(),
fahrenheit: z.number()
}),
conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']),
humidity: z.number().min(0).max(100),
wind: z.object({
speed_kmh: z.number(),
direction: z.string()
})
}
}, async ({ city, country }) => {
// Parameters are available but not used in this example
void city;
void country;
// Simulate weather API call
const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10;
const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)];
const structuredContent = {
temperature: {
celsius: temp_c,
fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10
},
conditions,
humidity: Math.round(Math.random() * 100),
wind: {
speed_kmh: Math.round(Math.random() * 50),
direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)]
}
};
return {
content: [
{
type: 'text',
text: JSON.stringify(structuredContent, null, 2)
}
],
structuredContent
};
});
async function main() {
const transport = new stdio_js_1.StdioServerTransport();
await server.connect(transport);
console.error('High-level Output Schema Example Server running on stdio');
}
main().catch(error => {
console.error('Server error:', error);
process.exit(1);
});
//# sourceMappingURL=mcpServerOutputSchema.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";;AACA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,CAAC,YAAY,CACf,aAAa,EACb;IACI,WAAW,EAAE,oCAAoC;IACjD,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC;QACtC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6BAA6B,CAAC;KAC9D;IACD,YAAY,EAAE;QACV,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YAClB,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE;YACnB,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;SACzB,CAAC;QACF,UAAU,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACnE,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QACpC,IAAI,EAAE,CAAC,CAAC,M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gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC;aACnD;SACJ;QACD,iBAAiB;KACpB,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,+BAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;AAC9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,12 @@
/**
* Example: Progress notifications over stdio.
*
* Demonstrates a tool that reports progress to the client while processing.
*
* Run:
* npx tsx src/examples/server/progressExample.ts
*
* Then connect a client with an `onprogress` callback (see docs/protocol.md).
*/
export {};
//# sourceMappingURL=progressExample.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"progressExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/progressExample.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}

Some files were not shown because too many files have changed in this diff Show More