Tests and assertions for client/server capabilities

Resolves #45.
This commit is contained in:
Justin Spahr-Summers 2024-11-11 22:30:50 +00:00
commit 90e91cdd62
No known key found for this signature in database
2 changed files with 128 additions and 4 deletions

View file

@ -9,10 +9,10 @@ import {
ResultSchema,
LATEST_PROTOCOL_VERSION,
SUPPORTED_PROTOCOL_VERSIONS,
InitializeRequestSchema,
InitializeResultSchema,
} from "../types.js";
import { Transport } from "../shared/transport.js";
import { InMemoryTransport } from "../inMemory.js";
import { Client } from "../client/index.js";
test("should accept latest protocol version", async () => {
let sendPromiseResolve: (value: unknown) => void;
@ -165,6 +165,33 @@ test("should handle unsupported protocol version", async () => {
await expect(sendPromise).resolves.toBeUndefined();
});
test("should respect client capabilities", async () => {
const server = new Server({
name: "test server",
version: "1.0",
});
const client = new Client({
name: "test client",
version: "1.0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await Promise.all([
client.connect(clientTransport),
server.connect(serverTransport),
]);
expect(server.getClientCapabilities()).toEqual({});
// This should throw because roots are not supported by the client
await expect(server.listRoots()).rejects.toThrow(
"Client does not support roots",
);
});
/*
Test that custom request/notification/result schemas can be used with the Server class.
*/

View file

@ -25,7 +25,7 @@ import {
ServerRequest,
ServerResult,
SetLevelRequestSchema,
SUPPORTED_PROTOCOL_VERSIONS
SUPPORTED_PROTOCOL_VERSIONS,
} from "../types.js";
/**
@ -93,7 +93,9 @@ export class Server<
this._clientVersion = request.params.clientInfo;
return {
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION,
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)
? requestedVersion
: LATEST_PROTOCOL_VERSION,
capabilities: this.getCapabilities(),
serverInfo: this._serverInfo,
};
@ -138,6 +140,17 @@ export class Server<
};
}
private assertCapability(
capability: keyof ClientCapabilities,
method: string,
) {
if (!this._clientCapabilities?.[capability]) {
throw new Error(
`Client does not support ${capability} (required for ${method})`,
);
}
}
async ping() {
return this.request({ method: "ping" }, EmptyResultSchema);
}
@ -146,6 +159,7 @@ export class Server<
params: CreateMessageRequest["params"],
onprogress?: ProgressCallback,
) {
this.assertCapability("sampling", "sampling/createMessage");
return this.request(
{ method: "sampling/createMessage", params },
CreateMessageResultSchema,
@ -157,6 +171,7 @@ export class Server<
params?: ListRootsRequest["params"],
onprogress?: ProgressCallback,
) {
this.assertCapability("roots", "roots/list");
return this.request(
{ method: "roots/list", params },
ListRootsResultSchema,