mcp.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ResourceTemplate = exports.McpServer = void 0;
  4. const index_js_1 = require("./index.js");
  5. const zod_compat_js_1 = require("./zod-compat.js");
  6. const zod_json_schema_compat_js_1 = require("./zod-json-schema-compat.js");
  7. const types_js_1 = require("../types.js");
  8. const completable_js_1 = require("./completable.js");
  9. const uriTemplate_js_1 = require("../shared/uriTemplate.js");
  10. const toolNameValidation_js_1 = require("../shared/toolNameValidation.js");
  11. const mcp_server_js_1 = require("../experimental/tasks/mcp-server.js");
  12. const zod_1 = require("zod");
  13. /**
  14. * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.
  15. * For advanced usage (like sending notifications or setting custom request handlers), use the underlying
  16. * Server instance available via the `server` property.
  17. */
  18. class McpServer {
  19. constructor(serverInfo, options) {
  20. this._registeredResources = {};
  21. this._registeredResourceTemplates = {};
  22. this._registeredTools = {};
  23. this._registeredPrompts = {};
  24. this._toolHandlersInitialized = false;
  25. this._completionHandlerInitialized = false;
  26. this._resourceHandlersInitialized = false;
  27. this._promptHandlersInitialized = false;
  28. this.server = new index_js_1.Server(serverInfo, options);
  29. }
  30. /**
  31. * Access experimental features.
  32. *
  33. * WARNING: These APIs are experimental and may change without notice.
  34. *
  35. * @experimental
  36. */
  37. get experimental() {
  38. if (!this._experimental) {
  39. this._experimental = {
  40. tasks: new mcp_server_js_1.ExperimentalMcpServerTasks(this)
  41. };
  42. }
  43. return this._experimental;
  44. }
  45. /**
  46. * Attaches to the given transport, starts it, and starts listening for messages.
  47. *
  48. * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
  49. */
  50. async connect(transport) {
  51. return await this.server.connect(transport);
  52. }
  53. /**
  54. * Closes the connection.
  55. */
  56. async close() {
  57. await this.server.close();
  58. }
  59. setToolRequestHandlers() {
  60. if (this._toolHandlersInitialized) {
  61. return;
  62. }
  63. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListToolsRequestSchema));
  64. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CallToolRequestSchema));
  65. this.server.registerCapabilities({
  66. tools: {
  67. listChanged: true
  68. }
  69. });
  70. this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, () => ({
  71. tools: Object.entries(this._registeredTools)
  72. .filter(([, tool]) => tool.enabled)
  73. .map(([name, tool]) => {
  74. const toolDefinition = {
  75. name,
  76. title: tool.title,
  77. description: tool.description,
  78. inputSchema: (() => {
  79. const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema);
  80. return obj
  81. ? (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, {
  82. strictUnions: true,
  83. pipeStrategy: 'input'
  84. })
  85. : EMPTY_OBJECT_JSON_SCHEMA;
  86. })(),
  87. annotations: tool.annotations,
  88. execution: tool.execution,
  89. _meta: tool._meta
  90. };
  91. if (tool.outputSchema) {
  92. const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema);
  93. if (obj) {
  94. toolDefinition.outputSchema = (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, {
  95. strictUnions: true,
  96. pipeStrategy: 'output'
  97. });
  98. }
  99. }
  100. return toolDefinition;
  101. })
  102. }));
  103. this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
  104. try {
  105. const tool = this._registeredTools[request.params.name];
  106. if (!tool) {
  107. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
  108. }
  109. if (!tool.enabled) {
  110. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
  111. }
  112. const isTaskRequest = !!request.params.task;
  113. const taskSupport = tool.execution?.taskSupport;
  114. const isTaskHandler = 'createTask' in tool.handler;
  115. // Validate task hint configuration
  116. if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) {
  117. throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
  118. }
  119. // Handle taskSupport 'required' without task augmentation
  120. if (taskSupport === 'required' && !isTaskRequest) {
  121. throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
  122. }
  123. // Handle taskSupport 'optional' without task augmentation - automatic polling
  124. if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) {
  125. return await this.handleAutomaticTaskPolling(tool, request, extra);
  126. }
  127. // Normal execution path
  128. const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
  129. const result = await this.executeToolHandler(tool, args, extra);
  130. // Return CreateTaskResult immediately for task requests
  131. if (isTaskRequest) {
  132. return result;
  133. }
  134. // Validate output schema for non-task requests
  135. await this.validateToolOutput(tool, result, request.params.name);
  136. return result;
  137. }
  138. catch (error) {
  139. if (error instanceof types_js_1.McpError) {
  140. if (error.code === types_js_1.ErrorCode.UrlElicitationRequired) {
  141. throw error; // Return the error to the caller without wrapping in CallToolResult
  142. }
  143. }
  144. return this.createToolError(error instanceof Error ? error.message : String(error));
  145. }
  146. });
  147. this._toolHandlersInitialized = true;
  148. }
  149. /**
  150. * Creates a tool error result.
  151. *
  152. * @param errorMessage - The error message.
  153. * @returns The tool error result.
  154. */
  155. createToolError(errorMessage) {
  156. return {
  157. content: [
  158. {
  159. type: 'text',
  160. text: errorMessage
  161. }
  162. ],
  163. isError: true
  164. };
  165. }
  166. /**
  167. * Validates tool input arguments against the tool's input schema.
  168. */
  169. async validateToolInput(tool, args, toolName) {
  170. if (!tool.inputSchema) {
  171. return undefined;
  172. }
  173. // Try to normalize to object schema first (for raw shapes and object schemas)
  174. // If that fails, use the schema directly (for union/intersection/etc)
  175. const inputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema);
  176. const schemaToParse = inputObj ?? tool.inputSchema;
  177. const parseResult = await (0, zod_compat_js_1.safeParseAsync)(schemaToParse, args);
  178. if (!parseResult.success) {
  179. const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
  180. const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error);
  181. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
  182. }
  183. return parseResult.data;
  184. }
  185. /**
  186. * Validates tool output against the tool's output schema.
  187. */
  188. async validateToolOutput(tool, result, toolName) {
  189. if (!tool.outputSchema) {
  190. return;
  191. }
  192. // Only validate CallToolResult, not CreateTaskResult
  193. if (!('content' in result)) {
  194. return;
  195. }
  196. if (result.isError) {
  197. return;
  198. }
  199. if (!result.structuredContent) {
  200. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
  201. }
  202. // if the tool has an output schema, validate structured content
  203. const outputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema);
  204. const parseResult = await (0, zod_compat_js_1.safeParseAsync)(outputObj, result.structuredContent);
  205. if (!parseResult.success) {
  206. const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
  207. const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error);
  208. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
  209. }
  210. }
  211. /**
  212. * Executes a tool handler (either regular or task-based).
  213. */
  214. async executeToolHandler(tool, args, extra) {
  215. const handler = tool.handler;
  216. const isTaskHandler = 'createTask' in handler;
  217. if (isTaskHandler) {
  218. if (!extra.taskStore) {
  219. throw new Error('No task store provided.');
  220. }
  221. const taskExtra = { ...extra, taskStore: extra.taskStore };
  222. if (tool.inputSchema) {
  223. const typedHandler = handler;
  224. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  225. return await Promise.resolve(typedHandler.createTask(args, taskExtra));
  226. }
  227. else {
  228. const typedHandler = handler;
  229. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  230. return await Promise.resolve(typedHandler.createTask(taskExtra));
  231. }
  232. }
  233. if (tool.inputSchema) {
  234. const typedHandler = handler;
  235. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  236. return await Promise.resolve(typedHandler(args, extra));
  237. }
  238. else {
  239. const typedHandler = handler;
  240. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  241. return await Promise.resolve(typedHandler(extra));
  242. }
  243. }
  244. /**
  245. * Handles automatic task polling for tools with taskSupport 'optional'.
  246. */
  247. async handleAutomaticTaskPolling(tool, request, extra) {
  248. if (!extra.taskStore) {
  249. throw new Error('No task store provided for task-capable tool.');
  250. }
  251. // Validate input and create task
  252. const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
  253. const handler = tool.handler;
  254. const taskExtra = { ...extra, taskStore: extra.taskStore };
  255. const createTaskResult = args // undefined only if tool.inputSchema is undefined
  256. ? await Promise.resolve(handler.createTask(args, taskExtra))
  257. : // eslint-disable-next-line @typescript-eslint/no-explicit-any
  258. await Promise.resolve(handler.createTask(taskExtra));
  259. // Poll until completion
  260. const taskId = createTaskResult.task.taskId;
  261. let task = createTaskResult.task;
  262. const pollInterval = task.pollInterval ?? 5000;
  263. while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') {
  264. await new Promise(resolve => setTimeout(resolve, pollInterval));
  265. const updatedTask = await extra.taskStore.getTask(taskId);
  266. if (!updatedTask) {
  267. throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} not found during polling`);
  268. }
  269. task = updatedTask;
  270. }
  271. // Return the final result
  272. return (await extra.taskStore.getTaskResult(taskId));
  273. }
  274. setCompletionRequestHandler() {
  275. if (this._completionHandlerInitialized) {
  276. return;
  277. }
  278. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CompleteRequestSchema));
  279. this.server.registerCapabilities({
  280. completions: {}
  281. });
  282. this.server.setRequestHandler(types_js_1.CompleteRequestSchema, async (request) => {
  283. switch (request.params.ref.type) {
  284. case 'ref/prompt':
  285. (0, types_js_1.assertCompleteRequestPrompt)(request);
  286. return this.handlePromptCompletion(request, request.params.ref);
  287. case 'ref/resource':
  288. (0, types_js_1.assertCompleteRequestResourceTemplate)(request);
  289. return this.handleResourceCompletion(request, request.params.ref);
  290. default:
  291. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
  292. }
  293. });
  294. this._completionHandlerInitialized = true;
  295. }
  296. async handlePromptCompletion(request, ref) {
  297. const prompt = this._registeredPrompts[ref.name];
  298. if (!prompt) {
  299. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
  300. }
  301. if (!prompt.enabled) {
  302. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
  303. }
  304. if (!prompt.argsSchema) {
  305. return EMPTY_COMPLETION_RESULT;
  306. }
  307. const promptShape = (0, zod_compat_js_1.getObjectShape)(prompt.argsSchema);
  308. const field = promptShape?.[request.params.argument.name];
  309. if (!(0, completable_js_1.isCompletable)(field)) {
  310. return EMPTY_COMPLETION_RESULT;
  311. }
  312. const completer = (0, completable_js_1.getCompleter)(field);
  313. if (!completer) {
  314. return EMPTY_COMPLETION_RESULT;
  315. }
  316. const suggestions = await completer(request.params.argument.value, request.params.context);
  317. return createCompletionResult(suggestions);
  318. }
  319. async handleResourceCompletion(request, ref) {
  320. const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);
  321. if (!template) {
  322. if (this._registeredResources[ref.uri]) {
  323. // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be).
  324. return EMPTY_COMPLETION_RESULT;
  325. }
  326. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
  327. }
  328. const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
  329. if (!completer) {
  330. return EMPTY_COMPLETION_RESULT;
  331. }
  332. const suggestions = await completer(request.params.argument.value, request.params.context);
  333. return createCompletionResult(suggestions);
  334. }
  335. setResourceRequestHandlers() {
  336. if (this._resourceHandlersInitialized) {
  337. return;
  338. }
  339. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourcesRequestSchema));
  340. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourceTemplatesRequestSchema));
  341. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ReadResourceRequestSchema));
  342. this.server.registerCapabilities({
  343. resources: {
  344. listChanged: true
  345. }
  346. });
  347. this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async (request, extra) => {
  348. const resources = Object.entries(this._registeredResources)
  349. .filter(([_, resource]) => resource.enabled)
  350. .map(([uri, resource]) => ({
  351. uri,
  352. name: resource.name,
  353. ...resource.metadata
  354. }));
  355. const templateResources = [];
  356. for (const template of Object.values(this._registeredResourceTemplates)) {
  357. if (!template.resourceTemplate.listCallback) {
  358. continue;
  359. }
  360. const result = await template.resourceTemplate.listCallback(extra);
  361. for (const resource of result.resources) {
  362. templateResources.push({
  363. ...template.metadata,
  364. // the defined resource metadata should override the template metadata if present
  365. ...resource
  366. });
  367. }
  368. }
  369. return { resources: [...resources, ...templateResources] };
  370. });
  371. this.server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => {
  372. const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
  373. name,
  374. uriTemplate: template.resourceTemplate.uriTemplate.toString(),
  375. ...template.metadata
  376. }));
  377. return { resourceTemplates };
  378. });
  379. this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request, extra) => {
  380. const uri = new URL(request.params.uri);
  381. // First check for exact resource match
  382. const resource = this._registeredResources[uri.toString()];
  383. if (resource) {
  384. if (!resource.enabled) {
  385. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} disabled`);
  386. }
  387. return resource.readCallback(uri, extra);
  388. }
  389. // Then check templates
  390. for (const template of Object.values(this._registeredResourceTemplates)) {
  391. const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
  392. if (variables) {
  393. return template.readCallback(uri, variables, extra);
  394. }
  395. }
  396. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} not found`);
  397. });
  398. this._resourceHandlersInitialized = true;
  399. }
  400. setPromptRequestHandlers() {
  401. if (this._promptHandlersInitialized) {
  402. return;
  403. }
  404. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListPromptsRequestSchema));
  405. this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.GetPromptRequestSchema));
  406. this.server.registerCapabilities({
  407. prompts: {
  408. listChanged: true
  409. }
  410. });
  411. this.server.setRequestHandler(types_js_1.ListPromptsRequestSchema, () => ({
  412. prompts: Object.entries(this._registeredPrompts)
  413. .filter(([, prompt]) => prompt.enabled)
  414. .map(([name, prompt]) => {
  415. return {
  416. name,
  417. title: prompt.title,
  418. description: prompt.description,
  419. arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
  420. };
  421. })
  422. }));
  423. this.server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request, extra) => {
  424. const prompt = this._registeredPrompts[request.params.name];
  425. if (!prompt) {
  426. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
  427. }
  428. if (!prompt.enabled) {
  429. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
  430. }
  431. if (prompt.argsSchema) {
  432. const argsObj = (0, zod_compat_js_1.normalizeObjectSchema)(prompt.argsSchema);
  433. const parseResult = await (0, zod_compat_js_1.safeParseAsync)(argsObj, request.params.arguments);
  434. if (!parseResult.success) {
  435. const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
  436. const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error);
  437. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
  438. }
  439. const args = parseResult.data;
  440. const cb = prompt.callback;
  441. return await Promise.resolve(cb(args, extra));
  442. }
  443. else {
  444. const cb = prompt.callback;
  445. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  446. return await Promise.resolve(cb(extra));
  447. }
  448. });
  449. this._promptHandlersInitialized = true;
  450. }
  451. resource(name, uriOrTemplate, ...rest) {
  452. let metadata;
  453. if (typeof rest[0] === 'object') {
  454. metadata = rest.shift();
  455. }
  456. const readCallback = rest[0];
  457. if (typeof uriOrTemplate === 'string') {
  458. if (this._registeredResources[uriOrTemplate]) {
  459. throw new Error(`Resource ${uriOrTemplate} is already registered`);
  460. }
  461. const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback);
  462. this.setResourceRequestHandlers();
  463. this.sendResourceListChanged();
  464. return registeredResource;
  465. }
  466. else {
  467. if (this._registeredResourceTemplates[name]) {
  468. throw new Error(`Resource template ${name} is already registered`);
  469. }
  470. const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback);
  471. this.setResourceRequestHandlers();
  472. this.sendResourceListChanged();
  473. return registeredResourceTemplate;
  474. }
  475. }
  476. registerResource(name, uriOrTemplate, config, readCallback) {
  477. if (typeof uriOrTemplate === 'string') {
  478. if (this._registeredResources[uriOrTemplate]) {
  479. throw new Error(`Resource ${uriOrTemplate} is already registered`);
  480. }
  481. const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
  482. this.setResourceRequestHandlers();
  483. this.sendResourceListChanged();
  484. return registeredResource;
  485. }
  486. else {
  487. if (this._registeredResourceTemplates[name]) {
  488. throw new Error(`Resource template ${name} is already registered`);
  489. }
  490. const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
  491. this.setResourceRequestHandlers();
  492. this.sendResourceListChanged();
  493. return registeredResourceTemplate;
  494. }
  495. }
  496. _createRegisteredResource(name, title, uri, metadata, readCallback) {
  497. const registeredResource = {
  498. name,
  499. title,
  500. metadata,
  501. readCallback,
  502. enabled: true,
  503. disable: () => registeredResource.update({ enabled: false }),
  504. enable: () => registeredResource.update({ enabled: true }),
  505. remove: () => registeredResource.update({ uri: null }),
  506. update: updates => {
  507. if (typeof updates.uri !== 'undefined' && updates.uri !== uri) {
  508. delete this._registeredResources[uri];
  509. if (updates.uri)
  510. this._registeredResources[updates.uri] = registeredResource;
  511. }
  512. if (typeof updates.name !== 'undefined')
  513. registeredResource.name = updates.name;
  514. if (typeof updates.title !== 'undefined')
  515. registeredResource.title = updates.title;
  516. if (typeof updates.metadata !== 'undefined')
  517. registeredResource.metadata = updates.metadata;
  518. if (typeof updates.callback !== 'undefined')
  519. registeredResource.readCallback = updates.callback;
  520. if (typeof updates.enabled !== 'undefined')
  521. registeredResource.enabled = updates.enabled;
  522. this.sendResourceListChanged();
  523. }
  524. };
  525. this._registeredResources[uri] = registeredResource;
  526. return registeredResource;
  527. }
  528. _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
  529. const registeredResourceTemplate = {
  530. resourceTemplate: template,
  531. title,
  532. metadata,
  533. readCallback,
  534. enabled: true,
  535. disable: () => registeredResourceTemplate.update({ enabled: false }),
  536. enable: () => registeredResourceTemplate.update({ enabled: true }),
  537. remove: () => registeredResourceTemplate.update({ name: null }),
  538. update: updates => {
  539. if (typeof updates.name !== 'undefined' && updates.name !== name) {
  540. delete this._registeredResourceTemplates[name];
  541. if (updates.name)
  542. this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
  543. }
  544. if (typeof updates.title !== 'undefined')
  545. registeredResourceTemplate.title = updates.title;
  546. if (typeof updates.template !== 'undefined')
  547. registeredResourceTemplate.resourceTemplate = updates.template;
  548. if (typeof updates.metadata !== 'undefined')
  549. registeredResourceTemplate.metadata = updates.metadata;
  550. if (typeof updates.callback !== 'undefined')
  551. registeredResourceTemplate.readCallback = updates.callback;
  552. if (typeof updates.enabled !== 'undefined')
  553. registeredResourceTemplate.enabled = updates.enabled;
  554. this.sendResourceListChanged();
  555. }
  556. };
  557. this._registeredResourceTemplates[name] = registeredResourceTemplate;
  558. // If the resource template has any completion callbacks, enable completions capability
  559. const variableNames = template.uriTemplate.variableNames;
  560. const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v));
  561. if (hasCompleter) {
  562. this.setCompletionRequestHandler();
  563. }
  564. return registeredResourceTemplate;
  565. }
  566. _createRegisteredPrompt(name, title, description, argsSchema, callback) {
  567. const registeredPrompt = {
  568. title,
  569. description,
  570. argsSchema: argsSchema === undefined ? undefined : (0, zod_compat_js_1.objectFromShape)(argsSchema),
  571. callback,
  572. enabled: true,
  573. disable: () => registeredPrompt.update({ enabled: false }),
  574. enable: () => registeredPrompt.update({ enabled: true }),
  575. remove: () => registeredPrompt.update({ name: null }),
  576. update: updates => {
  577. if (typeof updates.name !== 'undefined' && updates.name !== name) {
  578. delete this._registeredPrompts[name];
  579. if (updates.name)
  580. this._registeredPrompts[updates.name] = registeredPrompt;
  581. }
  582. if (typeof updates.title !== 'undefined')
  583. registeredPrompt.title = updates.title;
  584. if (typeof updates.description !== 'undefined')
  585. registeredPrompt.description = updates.description;
  586. if (typeof updates.argsSchema !== 'undefined')
  587. registeredPrompt.argsSchema = (0, zod_compat_js_1.objectFromShape)(updates.argsSchema);
  588. if (typeof updates.callback !== 'undefined')
  589. registeredPrompt.callback = updates.callback;
  590. if (typeof updates.enabled !== 'undefined')
  591. registeredPrompt.enabled = updates.enabled;
  592. this.sendPromptListChanged();
  593. }
  594. };
  595. this._registeredPrompts[name] = registeredPrompt;
  596. // If any argument uses a Completable schema, enable completions capability
  597. if (argsSchema) {
  598. const hasCompletable = Object.values(argsSchema).some(field => {
  599. const inner = field instanceof zod_1.ZodOptional ? field._def?.innerType : field;
  600. return (0, completable_js_1.isCompletable)(inner);
  601. });
  602. if (hasCompletable) {
  603. this.setCompletionRequestHandler();
  604. }
  605. }
  606. return registeredPrompt;
  607. }
  608. _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
  609. // Validate tool name according to SEP specification
  610. (0, toolNameValidation_js_1.validateAndWarnToolName)(name);
  611. const registeredTool = {
  612. title,
  613. description,
  614. inputSchema: getZodSchemaObject(inputSchema),
  615. outputSchema: getZodSchemaObject(outputSchema),
  616. annotations,
  617. execution,
  618. _meta,
  619. handler: handler,
  620. enabled: true,
  621. disable: () => registeredTool.update({ enabled: false }),
  622. enable: () => registeredTool.update({ enabled: true }),
  623. remove: () => registeredTool.update({ name: null }),
  624. update: updates => {
  625. if (typeof updates.name !== 'undefined' && updates.name !== name) {
  626. if (typeof updates.name === 'string') {
  627. (0, toolNameValidation_js_1.validateAndWarnToolName)(updates.name);
  628. }
  629. delete this._registeredTools[name];
  630. if (updates.name)
  631. this._registeredTools[updates.name] = registeredTool;
  632. }
  633. if (typeof updates.title !== 'undefined')
  634. registeredTool.title = updates.title;
  635. if (typeof updates.description !== 'undefined')
  636. registeredTool.description = updates.description;
  637. if (typeof updates.paramsSchema !== 'undefined')
  638. registeredTool.inputSchema = (0, zod_compat_js_1.objectFromShape)(updates.paramsSchema);
  639. if (typeof updates.outputSchema !== 'undefined')
  640. registeredTool.outputSchema = (0, zod_compat_js_1.objectFromShape)(updates.outputSchema);
  641. if (typeof updates.callback !== 'undefined')
  642. registeredTool.handler = updates.callback;
  643. if (typeof updates.annotations !== 'undefined')
  644. registeredTool.annotations = updates.annotations;
  645. if (typeof updates._meta !== 'undefined')
  646. registeredTool._meta = updates._meta;
  647. if (typeof updates.enabled !== 'undefined')
  648. registeredTool.enabled = updates.enabled;
  649. this.sendToolListChanged();
  650. }
  651. };
  652. this._registeredTools[name] = registeredTool;
  653. this.setToolRequestHandlers();
  654. this.sendToolListChanged();
  655. return registeredTool;
  656. }
  657. /**
  658. * tool() implementation. Parses arguments passed to overrides defined above.
  659. */
  660. tool(name, ...rest) {
  661. if (this._registeredTools[name]) {
  662. throw new Error(`Tool ${name} is already registered`);
  663. }
  664. let description;
  665. let inputSchema;
  666. let outputSchema;
  667. let annotations;
  668. // Tool properties are passed as separate arguments, with omissions allowed.
  669. // Support for this style is frozen as of protocol version 2025-03-26. Future additions
  670. // to tool definition should *NOT* be added.
  671. if (typeof rest[0] === 'string') {
  672. description = rest.shift();
  673. }
  674. // Handle the different overload combinations
  675. if (rest.length > 1) {
  676. // We have at least one more arg before the callback
  677. const firstArg = rest[0];
  678. if (isZodRawShapeCompat(firstArg)) {
  679. // We have a params schema as the first arg
  680. inputSchema = rest.shift();
  681. // Check if the next arg is potentially annotations
  682. if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
  683. // Case: tool(name, paramsSchema, annotations, cb)
  684. // Or: tool(name, description, paramsSchema, annotations, cb)
  685. annotations = rest.shift();
  686. }
  687. }
  688. else if (typeof firstArg === 'object' && firstArg !== null) {
  689. // ToolAnnotations values are primitives. Nested objects indicate a misplaced schema
  690. if (Object.values(firstArg).some(v => typeof v === 'object' && v !== null)) {
  691. throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);
  692. }
  693. annotations = rest.shift();
  694. }
  695. }
  696. const callback = rest[0];
  697. return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback);
  698. }
  699. /**
  700. * Registers a tool with a config object and callback.
  701. */
  702. registerTool(name, config, cb) {
  703. if (this._registeredTools[name]) {
  704. throw new Error(`Tool ${name} is already registered`);
  705. }
  706. const { title, description, inputSchema, outputSchema, annotations, _meta } = config;
  707. return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb);
  708. }
  709. prompt(name, ...rest) {
  710. if (this._registeredPrompts[name]) {
  711. throw new Error(`Prompt ${name} is already registered`);
  712. }
  713. let description;
  714. if (typeof rest[0] === 'string') {
  715. description = rest.shift();
  716. }
  717. let argsSchema;
  718. if (rest.length > 1) {
  719. argsSchema = rest.shift();
  720. }
  721. const cb = rest[0];
  722. const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb);
  723. this.setPromptRequestHandlers();
  724. this.sendPromptListChanged();
  725. return registeredPrompt;
  726. }
  727. /**
  728. * Registers a prompt with a config object and callback.
  729. */
  730. registerPrompt(name, config, cb) {
  731. if (this._registeredPrompts[name]) {
  732. throw new Error(`Prompt ${name} is already registered`);
  733. }
  734. const { title, description, argsSchema } = config;
  735. const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
  736. this.setPromptRequestHandlers();
  737. this.sendPromptListChanged();
  738. return registeredPrompt;
  739. }
  740. /**
  741. * Checks if the server is connected to a transport.
  742. * @returns True if the server is connected
  743. */
  744. isConnected() {
  745. return this.server.transport !== undefined;
  746. }
  747. /**
  748. * Sends a logging message to the client, if connected.
  749. * Note: You only need to send the parameters object, not the entire JSON RPC message
  750. * @see LoggingMessageNotification
  751. * @param params
  752. * @param sessionId optional for stateless and backward compatibility
  753. */
  754. async sendLoggingMessage(params, sessionId) {
  755. return this.server.sendLoggingMessage(params, sessionId);
  756. }
  757. /**
  758. * Sends a resource list changed event to the client, if connected.
  759. */
  760. sendResourceListChanged() {
  761. if (this.isConnected()) {
  762. this.server.sendResourceListChanged();
  763. }
  764. }
  765. /**
  766. * Sends a tool list changed event to the client, if connected.
  767. */
  768. sendToolListChanged() {
  769. if (this.isConnected()) {
  770. this.server.sendToolListChanged();
  771. }
  772. }
  773. /**
  774. * Sends a prompt list changed event to the client, if connected.
  775. */
  776. sendPromptListChanged() {
  777. if (this.isConnected()) {
  778. this.server.sendPromptListChanged();
  779. }
  780. }
  781. }
  782. exports.McpServer = McpServer;
  783. /**
  784. * A resource template combines a URI pattern with optional functionality to enumerate
  785. * all resources matching that pattern.
  786. */
  787. class ResourceTemplate {
  788. constructor(uriTemplate, _callbacks) {
  789. this._callbacks = _callbacks;
  790. this._uriTemplate = typeof uriTemplate === 'string' ? new uriTemplate_js_1.UriTemplate(uriTemplate) : uriTemplate;
  791. }
  792. /**
  793. * Gets the URI template pattern.
  794. */
  795. get uriTemplate() {
  796. return this._uriTemplate;
  797. }
  798. /**
  799. * Gets the list callback, if one was provided.
  800. */
  801. get listCallback() {
  802. return this._callbacks.list;
  803. }
  804. /**
  805. * Gets the callback for completing a specific URI template variable, if one was provided.
  806. */
  807. completeCallback(variable) {
  808. return this._callbacks.complete?.[variable];
  809. }
  810. }
  811. exports.ResourceTemplate = ResourceTemplate;
  812. const EMPTY_OBJECT_JSON_SCHEMA = {
  813. type: 'object',
  814. properties: {}
  815. };
  816. /**
  817. * Checks if a value looks like a Zod schema by checking for parse/safeParse methods.
  818. */
  819. function isZodTypeLike(value) {
  820. return (value !== null &&
  821. typeof value === 'object' &&
  822. 'parse' in value &&
  823. typeof value.parse === 'function' &&
  824. 'safeParse' in value &&
  825. typeof value.safeParse === 'function');
  826. }
  827. /**
  828. * Checks if an object is a Zod schema instance (v3 or v4).
  829. *
  830. * Zod schemas have internal markers:
  831. * - v3: `_def` property
  832. * - v4: `_zod` property
  833. *
  834. * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe().
  835. */
  836. function isZodSchemaInstance(obj) {
  837. return '_def' in obj || '_zod' in obj || isZodTypeLike(obj);
  838. }
  839. /**
  840. * Checks if an object is a "raw shape" - a plain object where values are Zod schemas.
  841. *
  842. * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`.
  843. *
  844. * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe),
  845. * which have internal properties that could be mistaken for schema values.
  846. */
  847. function isZodRawShapeCompat(obj) {
  848. if (typeof obj !== 'object' || obj === null) {
  849. return false;
  850. }
  851. // If it's already a Zod schema instance, it's NOT a raw shape
  852. if (isZodSchemaInstance(obj)) {
  853. return false;
  854. }
  855. // Empty objects are valid raw shapes (tools with no parameters)
  856. if (Object.keys(obj).length === 0) {
  857. return true;
  858. }
  859. // A raw shape has at least one property that is a Zod schema
  860. return Object.values(obj).some(isZodTypeLike);
  861. }
  862. /**
  863. * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat,
  864. * otherwise returns the schema as is. Throws if the value is not a valid Zod schema.
  865. */
  866. function getZodSchemaObject(schema) {
  867. if (!schema) {
  868. return undefined;
  869. }
  870. if (isZodRawShapeCompat(schema)) {
  871. return (0, zod_compat_js_1.objectFromShape)(schema);
  872. }
  873. if (!isZodSchemaInstance(schema)) {
  874. throw new Error('inputSchema must be a Zod schema or raw shape, received an unrecognized object');
  875. }
  876. return schema;
  877. }
  878. function promptArgumentsFromSchema(schema) {
  879. const shape = (0, zod_compat_js_1.getObjectShape)(schema);
  880. if (!shape)
  881. return [];
  882. return Object.entries(shape).map(([name, field]) => {
  883. // Get description - works for both v3 and v4
  884. const description = (0, zod_compat_js_1.getSchemaDescription)(field);
  885. // Check if optional - works for both v3 and v4
  886. const isOptional = (0, zod_compat_js_1.isSchemaOptional)(field);
  887. return {
  888. name,
  889. description,
  890. required: !isOptional
  891. };
  892. });
  893. }
  894. function getMethodValue(schema) {
  895. const shape = (0, zod_compat_js_1.getObjectShape)(schema);
  896. const methodSchema = shape?.method;
  897. if (!methodSchema) {
  898. throw new Error('Schema is missing a method literal');
  899. }
  900. // Extract literal value - works for both v3 and v4
  901. const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema);
  902. if (typeof value === 'string') {
  903. return value;
  904. }
  905. throw new Error('Schema method literal must be a string');
  906. }
  907. function createCompletionResult(suggestions) {
  908. return {
  909. completion: {
  910. values: suggestions.slice(0, 100),
  911. total: suggestions.length,
  912. hasMore: suggestions.length > 100
  913. }
  914. };
  915. }
  916. const EMPTY_COMPLETION_RESULT = {
  917. completion: {
  918. values: [],
  919. hasMore: false
  920. }
  921. };
  922. //# sourceMappingURL=mcp.js.map