Disconnect from client side if initialization fails

Resolves #24.
This commit is contained in:
Justin Spahr-Summers 2024-11-11 22:08:46 +00:00
commit c82d633d8d
No known key found for this signature in database
2 changed files with 37 additions and 27 deletions

View file

@ -122,6 +122,8 @@ test("should reject unsupported protocol version", async () => {
await expect(client.connect(clientTransport)).rejects.toThrow(
"Server's protocol version is not supported: invalid-version",
);
expect(clientTransport.close).toHaveBeenCalled();
});
/*

View file

@ -32,7 +32,7 @@ import {
ServerCapabilities,
SubscribeRequest,
SUPPORTED_PROTOCOL_VERSIONS,
UnsubscribeRequest
UnsubscribeRequest,
} from "../types.js";
/**
@ -82,34 +82,40 @@ export class Client<
override async connect(transport: Transport): Promise<void> {
await super.connect(transport);
const result = await this.request(
{
method: "initialize",
params: {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: {},
clientInfo: this._clientInfo,
try {
const result = await this.request(
{
method: "initialize",
params: {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: {},
clientInfo: this._clientInfo,
},
},
},
InitializeResultSchema,
);
if (result === undefined) {
throw new Error(`Server sent invalid initialize result: ${result}`);
}
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
throw new Error(
`Server's protocol version is not supported: ${result.protocolVersion}`,
InitializeResultSchema,
);
if (result === undefined) {
throw new Error(`Server sent invalid initialize result: ${result}`);
}
if (!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;
await this.notification({
method: "notifications/initialized",
});
} catch (error) {
// Disconnect if initialization fails.
void this.close();
throw error;
}
this._serverCapabilities = result.capabilities;
this._serverVersion = result.serverInfo;
await this.notification({
method: "notifications/initialized",
});
}
/**
@ -219,7 +225,9 @@ export class Client<
async callTool(
params: CallToolRequest["params"],
resultSchema: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema = CallToolResultSchema,
resultSchema:
| typeof CallToolResultSchema
| typeof CompatibilityCallToolResultSchema = CallToolResultSchema,
onprogress?: ProgressCallback,
) {
return this.request(