client.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  2. import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
  3. import { MCPClientLogger } from "./logger";
  4. import { z } from "zod";
  5. export interface ServerConfig {
  6. command: string;
  7. args?: string[];
  8. env?: Record<string, string>;
  9. }
  10. const logger = new MCPClientLogger();
  11. export async function createClient(
  12. serverConfig: ServerConfig,
  13. name: string,
  14. ): Promise<Client> {
  15. logger.info(`Creating client for server ${name}`);
  16. const transport = new StdioClientTransport({
  17. command: serverConfig.command,
  18. args: serverConfig.args,
  19. env: serverConfig.env,
  20. });
  21. const client = new Client(
  22. {
  23. name: `nextchat-mcp-client-${name}`,
  24. version: "1.0.0",
  25. },
  26. {
  27. capabilities: {
  28. // roots: {
  29. // listChanged: true,
  30. // },
  31. },
  32. },
  33. );
  34. await client.connect(transport);
  35. return client;
  36. }
  37. interface Primitive {
  38. type: "resource" | "tool" | "prompt";
  39. value: any;
  40. }
  41. /** List all resources, tools, and prompts */
  42. export async function listPrimitives(client: Client) {
  43. const capabilities = client.getServerCapabilities();
  44. const primitives: Primitive[] = [];
  45. const promises = [];
  46. if (capabilities?.resources) {
  47. promises.push(
  48. client.listResources().then(({ resources }) => {
  49. resources.forEach((item) =>
  50. primitives.push({ type: "resource", value: item }),
  51. );
  52. }),
  53. );
  54. }
  55. if (capabilities?.tools) {
  56. promises.push(
  57. client.listTools().then(({ tools }) => {
  58. tools.forEach((item) => primitives.push({ type: "tool", value: item }));
  59. }),
  60. );
  61. }
  62. if (capabilities?.prompts) {
  63. promises.push(
  64. client.listPrompts().then(({ prompts }) => {
  65. prompts.forEach((item) =>
  66. primitives.push({ type: "prompt", value: item }),
  67. );
  68. }),
  69. );
  70. }
  71. await Promise.all(promises);
  72. return primitives;
  73. }
  74. /** Execute a request */
  75. export async function executeRequest(client: Client, request: any) {
  76. return client.request(request, z.any());
  77. }