client.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 indicates whether the client will emit notifications when the list of roots changes.
  30. // listChanged 指示客户端在根列表更改时是否发出通知。
  31. listChanged: true,
  32. },
  33. },
  34. },
  35. );
  36. await client.connect(transport);
  37. return client;
  38. }
  39. interface Primitive {
  40. type: "resource" | "tool" | "prompt";
  41. value: any;
  42. }
  43. /** List all resources, tools, and prompts */
  44. export async function listPrimitives(client: Client) {
  45. const capabilities = client.getServerCapabilities();
  46. const primitives: Primitive[] = [];
  47. const promises = [];
  48. if (capabilities?.resources) {
  49. promises.push(
  50. client.listResources().then(({ resources }) => {
  51. resources.forEach((item) =>
  52. primitives.push({ type: "resource", value: item }),
  53. );
  54. }),
  55. );
  56. }
  57. if (capabilities?.tools) {
  58. promises.push(
  59. client.listTools().then(({ tools }) => {
  60. tools.forEach((item) => primitives.push({ type: "tool", value: item }));
  61. }),
  62. );
  63. }
  64. if (capabilities?.prompts) {
  65. promises.push(
  66. client.listPrompts().then(({ prompts }) => {
  67. prompts.forEach((item) =>
  68. primitives.push({ type: "prompt", value: item }),
  69. );
  70. }),
  71. );
  72. }
  73. await Promise.all(promises);
  74. return primitives;
  75. }
  76. export async function executeRequest(client: Client, request: any) {
  77. const r = client.request(request, z.any());
  78. console.log(r);
  79. return r;
  80. }