server.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var server_exports = {};
  30. __export(server_exports, {
  31. connect: () => connect,
  32. createServer: () => createServer,
  33. firstRootPath: () => firstRootPath,
  34. start: () => start,
  35. wrapInProcess: () => wrapInProcess
  36. });
  37. module.exports = __toCommonJS(server_exports);
  38. var import_url = require("url");
  39. var import_utilsBundle = require("playwright-core/lib/utilsBundle");
  40. var mcpBundle = __toESM(require("./bundle"));
  41. var import_http = require("./http");
  42. var import_inProcessTransport = require("./inProcessTransport");
  43. const serverDebug = (0, import_utilsBundle.debug)("pw:mcp:server");
  44. const serverDebugResponse = (0, import_utilsBundle.debug)("pw:mcp:server:response");
  45. async function connect(factory, transport, runHeartbeat) {
  46. const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
  47. await server.connect(transport);
  48. }
  49. async function wrapInProcess(backend) {
  50. const server = createServer("Internal", "0.0.0", backend, false);
  51. return new import_inProcessTransport.InProcessTransport(server);
  52. }
  53. function createServer(name, version, backend, runHeartbeat) {
  54. const server = new mcpBundle.Server({ name, version }, {
  55. capabilities: {
  56. tools: {}
  57. }
  58. });
  59. server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
  60. serverDebug("listTools");
  61. const tools = await backend.listTools();
  62. return { tools };
  63. });
  64. let initializePromise;
  65. server.setRequestHandler(mcpBundle.CallToolRequestSchema, async (request, extra) => {
  66. serverDebug("callTool", request);
  67. const progressToken = request.params._meta?.progressToken;
  68. let progressCounter = 0;
  69. const progress = progressToken ? (params) => {
  70. extra.sendNotification({
  71. method: "notifications/progress",
  72. params: {
  73. progressToken,
  74. progress: params.progress ?? ++progressCounter,
  75. total: params.total,
  76. message: params.message
  77. }
  78. }).catch(serverDebug);
  79. } : () => {
  80. };
  81. try {
  82. if (!initializePromise)
  83. initializePromise = initializeServer(server, backend, runHeartbeat);
  84. await initializePromise;
  85. const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, progress);
  86. const mergedResult = mergeTextParts(toolResult);
  87. serverDebugResponse("callResult", mergedResult);
  88. return mergedResult;
  89. } catch (error) {
  90. return {
  91. content: [{ type: "text", text: "### Result\n" + String(error) }],
  92. isError: true
  93. };
  94. }
  95. });
  96. addServerListener(server, "close", () => backend.serverClosed?.(server));
  97. return server;
  98. }
  99. const initializeServer = async (server, backend, runHeartbeat) => {
  100. const capabilities = server.getClientCapabilities();
  101. let clientRoots = [];
  102. if (capabilities?.roots) {
  103. const { roots } = await server.listRoots().catch((e) => {
  104. serverDebug(e);
  105. return { roots: [] };
  106. });
  107. clientRoots = roots;
  108. }
  109. const clientInfo = {
  110. name: server.getClientVersion()?.name ?? "unknown",
  111. version: server.getClientVersion()?.version ?? "unknown",
  112. roots: clientRoots,
  113. timestamp: Date.now()
  114. };
  115. await backend.initialize?.(clientInfo);
  116. if (runHeartbeat)
  117. startHeartbeat(server);
  118. };
  119. const startHeartbeat = (server) => {
  120. const beat = () => {
  121. Promise.race([
  122. server.ping(),
  123. new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), 5e3))
  124. ]).then(() => {
  125. setTimeout(beat, 3e3);
  126. }).catch(() => {
  127. void server.close();
  128. });
  129. };
  130. beat();
  131. };
  132. function addServerListener(server, event, listener) {
  133. const oldListener = server[`on${event}`];
  134. server[`on${event}`] = () => {
  135. oldListener?.();
  136. listener();
  137. };
  138. }
  139. async function start(serverBackendFactory, options) {
  140. if (options.port === void 0) {
  141. await connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
  142. return;
  143. }
  144. const httpServer = await (0, import_http.startHttpServer)(options);
  145. const url = await (0, import_http.installHttpTransport)(httpServer, serverBackendFactory, false, options.allowedHosts);
  146. const mcpConfig = { mcpServers: {} };
  147. mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
  148. url: `${url}/mcp`
  149. };
  150. const message = [
  151. `Listening on ${url}`,
  152. "Put this in your client config:",
  153. JSON.stringify(mcpConfig, void 0, 2),
  154. "For legacy SSE transport support, you can use the /sse endpoint instead."
  155. ].join("\n");
  156. console.error(message);
  157. }
  158. function firstRootPath(clientInfo) {
  159. if (clientInfo.roots.length === 0)
  160. return void 0;
  161. const firstRootUri = clientInfo.roots[0]?.uri;
  162. const url = firstRootUri ? new URL(firstRootUri) : void 0;
  163. try {
  164. return url ? (0, import_url.fileURLToPath)(url) : void 0;
  165. } catch (error) {
  166. serverDebug(error);
  167. return void 0;
  168. }
  169. }
  170. function mergeTextParts(result) {
  171. const content = [];
  172. const testParts = [];
  173. for (const part of result.content) {
  174. if (part.type === "text") {
  175. testParts.push(part.text);
  176. continue;
  177. }
  178. if (testParts.length > 0) {
  179. content.push({ type: "text", text: testParts.join("\n") });
  180. testParts.length = 0;
  181. }
  182. content.push(part);
  183. }
  184. if (testParts.length > 0)
  185. content.push({ type: "text", text: testParts.join("\n") });
  186. return {
  187. ...result,
  188. content
  189. };
  190. }
  191. // Annotate the CommonJS export names for ESM import in node:
  192. 0 && (module.exports = {
  193. connect,
  194. createServer,
  195. firstRootPath,
  196. start,
  197. wrapInProcess
  198. });