agents
Version:
A home for your AI agents
472 lines (468 loc) • 16 kB
JavaScript
import { nanoid } from "nanoid";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
//#region src/core/events.ts
function toDisposable(fn) {
return { dispose: fn };
}
var DisposableStore = class {
constructor() {
this._items = [];
}
add(d) {
this._items.push(d);
return d;
}
dispose() {
while (this._items.length) try {
this._items.pop().dispose();
} catch {}
}
};
var Emitter = class {
constructor() {
this._listeners = /* @__PURE__ */ new Set();
this.event = (listener) => {
this._listeners.add(listener);
return toDisposable(() => this._listeners.delete(listener));
};
}
fire(data) {
for (const listener of [...this._listeners]) try {
listener(data);
} catch (err) {
console.error("Emitter listener error:", err);
}
}
dispose() {
this._listeners.clear();
}
};
//#endregion
//#region src/mcp/errors.ts
function toErrorMessage(error) {
return error instanceof Error ? error.message : String(error);
}
function getErrorCode(error) {
if (error && typeof error === "object" && "code" in error && typeof error.code === "number") return error.code;
}
function isUnauthorized(error) {
if (getErrorCode(error) === 401) return true;
const msg = toErrorMessage(error);
return msg.includes("Unauthorized") || msg.includes("401");
}
function isTransportNotImplemented(error) {
const code = getErrorCode(error);
if (code === 404 || code === 405) return true;
const msg = toErrorMessage(error);
return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
}
//#endregion
//#region src/mcp/client-connection.ts
/**
* Connection state machine for MCP client connections.
*
* State transitions:
* - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
* - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
* - Any state can transition to FAILED on error
*/
const MCPConnectionState = {
AUTHENTICATING: "authenticating",
CONNECTING: "connecting",
CONNECTED: "connected",
DISCOVERING: "discovering",
READY: "ready",
FAILED: "failed"
};
var MCPClientConnection = class {
constructor(url, info, options = {
client: {},
transport: {}
}) {
this.url = url;
this.options = options;
this.connectionState = MCPConnectionState.CONNECTING;
this.connectionError = null;
this.tools = [];
this.prompts = [];
this.resources = [];
this.resourceTemplates = [];
this._onObservabilityEvent = new Emitter();
this.onObservabilityEvent = this._onObservabilityEvent.event;
this.client = new Client(info, {
...options.client,
capabilities: {
...options.client?.capabilities,
elicitation: {}
}
});
}
/**
* Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
* Sets connection state based on the result and emits observability events
*
* @returns Error message if connection failed, undefined otherwise
*/
async init() {
const transportType = this.options.transport.type;
if (!transportType) throw new Error("Transport type must be specified");
const res = await this.tryConnect(transportType);
this.connectionState = res.state;
if (res.state === MCPConnectionState.CONNECTED && res.transport) {
this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
return await this.handleElicitationRequest(request);
});
this.lastConnectedTransport = res.transport;
this._onObservabilityEvent.fire({
type: "mcp:client:connect",
displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,
payload: {
url: this.url.toString(),
transport: res.transport,
state: this.connectionState
},
timestamp: Date.now(),
id: nanoid()
});
return;
} else if (res.state === MCPConnectionState.FAILED && res.error) {
const errorMessage = toErrorMessage(res.error);
this._onObservabilityEvent.fire({
type: "mcp:client:connect",
displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,
payload: {
url: this.url.toString(),
transport: transportType,
state: this.connectionState,
error: errorMessage
},
timestamp: Date.now(),
id: nanoid()
});
return errorMessage;
}
}
/**
* Finish OAuth by probing transports based on configured type.
* - Explicit: finish on that transport
* - Auto: try streamable-http, then sse on 404/405/Not Implemented
*/
async finishAuthProbe(code) {
if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
const configuredType = this.options.transport.type;
if (!configuredType) throw new Error("Transport type must be specified");
const finishAuth = async (base) => {
await this.getTransport(base).finishAuth(code);
};
if (configuredType === "sse" || configuredType === "streamable-http") {
await finishAuth(configuredType);
return;
}
try {
await finishAuth("streamable-http");
} catch (e) {
if (isTransportNotImplemented(e)) {
await finishAuth("sse");
return;
}
throw e;
}
}
/**
* Complete OAuth authorization
*/
async completeAuthorization(code) {
if (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error("Connection must be in authenticating state to complete authorization");
try {
await this.finishAuthProbe(code);
this.connectionState = MCPConnectionState.CONNECTING;
} catch (error) {
this.connectionState = MCPConnectionState.FAILED;
throw error;
}
}
/**
* Discover server capabilities and register tools, resources, prompts, and templates.
* This method does the work but does not manage connection state - that's handled by discover().
*/
async discoverAndRegister() {
this.serverCapabilities = this.client.getServerCapabilities();
if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
const operations = [];
const operationNames = [];
operations.push(Promise.resolve(this.client.getInstructions()));
operationNames.push("instructions");
if (this.serverCapabilities.tools) {
operations.push(this.registerTools());
operationNames.push("tools");
}
if (this.serverCapabilities.resources) {
operations.push(this.registerResources());
operationNames.push("resources");
}
if (this.serverCapabilities.prompts) {
operations.push(this.registerPrompts());
operationNames.push("prompts");
}
if (this.serverCapabilities.resources) {
operations.push(this.registerResourceTemplates());
operationNames.push("resource templates");
}
try {
const results = await Promise.all(operations);
for (let i = 0; i < results.length; i++) {
const result = results[i];
switch (operationNames[i]) {
case "instructions":
this.instructions = result;
break;
case "tools":
this.tools = result;
break;
case "resources":
this.resources = result;
break;
case "prompts":
this.prompts = result;
break;
case "resource templates":
this.resourceTemplates = result;
break;
}
}
} catch (error) {
this._onObservabilityEvent.fire({
type: "mcp:client:discover",
displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,
payload: {
url: this.url.toString(),
error: toErrorMessage(error)
},
timestamp: Date.now(),
id: nanoid()
});
throw error;
}
}
/**
* Discover server capabilities with timeout and cancellation support.
* If called while a previous discovery is in-flight, the previous discovery will be aborted.
*
* @param options Optional configuration
* @param options.timeoutMs Timeout in milliseconds (default: 15000)
* @returns Result indicating success/failure with optional error message
*/
async discover(options = {}) {
const { timeoutMs = 15e3 } = options;
if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
this._onObservabilityEvent.fire({
type: "mcp:client:discover",
displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,
payload: {
url: this.url.toString(),
state: this.connectionState
},
timestamp: Date.now(),
id: nanoid()
});
return {
success: false,
error: `Discovery skipped - connection in ${this.connectionState} state`
};
}
if (this._discoveryAbortController) {
this._discoveryAbortController.abort();
this._discoveryAbortController = void 0;
}
const abortController = new AbortController();
this._discoveryAbortController = abortController;
this.connectionState = MCPConnectionState.DISCOVERING;
let timeoutId;
try {
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
});
if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
const abortPromise = new Promise((_, reject) => {
abortController.signal.addEventListener("abort", () => {
reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
});
});
await Promise.race([
this.discoverAndRegister(),
timeoutPromise,
abortPromise
]);
if (timeoutId !== void 0) clearTimeout(timeoutId);
this.connectionState = MCPConnectionState.READY;
this._onObservabilityEvent.fire({
type: "mcp:client:discover",
displayMessage: `Discovery completed for ${this.url.toString()}`,
payload: { url: this.url.toString() },
timestamp: Date.now(),
id: nanoid()
});
return { success: true };
} catch (e) {
if (timeoutId !== void 0) clearTimeout(timeoutId);
this.connectionState = MCPConnectionState.CONNECTED;
return {
success: false,
error: e instanceof Error ? e.message : String(e)
};
} finally {
this._discoveryAbortController = void 0;
}
}
/**
* Cancel any in-flight discovery operation.
* Called when closing the connection.
*/
cancelDiscovery() {
if (this._discoveryAbortController) {
this._discoveryAbortController.abort();
this._discoveryAbortController = void 0;
}
}
/**
* Notification handler registration for tools
* Should only be called if serverCapabilities.tools exists
*/
async registerTools() {
if (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
this.tools = await this.fetchTools();
});
return this.fetchTools();
}
/**
* Notification handler registration for resources
* Should only be called if serverCapabilities.resources exists
*/
async registerResources() {
if (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
this.resources = await this.fetchResources();
});
return this.fetchResources();
}
/**
* Notification handler registration for prompts
* Should only be called if serverCapabilities.prompts exists
*/
async registerPrompts() {
if (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
this.prompts = await this.fetchPrompts();
});
return this.fetchPrompts();
}
async registerResourceTemplates() {
return this.fetchResourceTemplates();
}
async fetchTools() {
let toolsAgg = [];
let toolsResult = { tools: [] };
do {
toolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
toolsAgg = toolsAgg.concat(toolsResult.tools);
} while (toolsResult.nextCursor);
return toolsAgg;
}
async fetchResources() {
let resourcesAgg = [];
let resourcesResult = { resources: [] };
do {
resourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, "resources/list"));
resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
} while (resourcesResult.nextCursor);
return resourcesAgg;
}
async fetchPrompts() {
let promptsAgg = [];
let promptsResult = { prompts: [] };
do {
promptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
promptsAgg = promptsAgg.concat(promptsResult.prompts);
} while (promptsResult.nextCursor);
return promptsAgg;
}
async fetchResourceTemplates() {
let templatesAgg = [];
let templatesResult = { resourceTemplates: [] };
do {
templatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, "resources/templates/list"));
templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
} while (templatesResult.nextCursor);
return templatesAgg;
}
/**
* Handle elicitation request from server
* Automatically uses the Agent's built-in elicitation handling if available
*/
async handleElicitationRequest(_request) {
throw new Error("Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.");
}
/**
* Get the transport for the client
* @param transportType - The transport type to get
* @returns The transport for the client
*/
getTransport(transportType) {
switch (transportType) {
case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
case "sse": return new SSEClientTransport(this.url, this.options.transport);
default: throw new Error(`Unsupported transport type: ${transportType}`);
}
}
async tryConnect(transportType) {
const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
for (const currentTransportType of transports) {
const isLastTransport = currentTransportType === transports[transports.length - 1];
const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
const transport = this.getTransport(currentTransportType);
try {
await this.client.connect(transport);
return {
state: MCPConnectionState.CONNECTED,
transport: currentTransportType
};
} catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
if (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };
if (isTransportNotImplemented(error) && hasFallback) continue;
return {
state: MCPConnectionState.FAILED,
error
};
}
}
return {
state: MCPConnectionState.FAILED,
error: /* @__PURE__ */ new Error("No transports available")
};
}
_capabilityErrorHandler(empty, method) {
return (e) => {
if (e.code === -32601) {
const url = this.url.toString();
this._onObservabilityEvent.fire({
type: "mcp:client:discover",
displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
payload: {
url,
capability: method.split("/")[0],
error: toErrorMessage(e)
},
timestamp: Date.now(),
id: nanoid()
});
return empty;
}
throw e;
};
}
};
//#endregion
export { Emitter as a, DisposableStore as i, MCPConnectionState as n, toErrorMessage as r, MCPClientConnection as t };
//# sourceMappingURL=client-connection-CGMuV62J.js.map