progressExample.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * Example: Progress notifications over stdio.
  4. *
  5. * Demonstrates a tool that reports progress to the client while processing.
  6. *
  7. * Run:
  8. * npx tsx src/examples/server/progressExample.ts
  9. *
  10. * Then connect a client with an `onprogress` callback (see docs/protocol.md).
  11. */
  12. Object.defineProperty(exports, "__esModule", { value: true });
  13. const mcp_js_1 = require("../../server/mcp.js");
  14. const stdio_js_1 = require("../../server/stdio.js");
  15. const zod_1 = require("zod");
  16. const server = new mcp_js_1.McpServer({ name: 'progress-example', version: '1.0.0' }, { capabilities: { logging: {} } });
  17. server.registerTool('count', {
  18. description: 'Count to N with progress updates',
  19. inputSchema: { n: zod_1.z.number().int().min(1).max(100) }
  20. }, async ({ n }, extra) => {
  21. for (let i = 1; i <= n; i++) {
  22. if (extra.signal.aborted) {
  23. return { content: [{ type: 'text', text: `Cancelled at ${i}` }], isError: true };
  24. }
  25. if (extra._meta?.progressToken !== undefined) {
  26. await extra.sendNotification({
  27. method: 'notifications/progress',
  28. params: {
  29. progressToken: extra._meta.progressToken,
  30. progress: i,
  31. total: n,
  32. message: `Counting: ${i}/${n}`
  33. }
  34. });
  35. }
  36. // Simulate work
  37. await new Promise(resolve => setTimeout(resolve, 100));
  38. }
  39. return { content: [{ type: 'text', text: `Counted to ${n}` }] };
  40. });
  41. async function main() {
  42. const transport = new stdio_js_1.StdioServerTransport();
  43. await server.connect(transport);
  44. }
  45. main().catch(error => {
  46. console.error('Server error:', error);
  47. process.exit(1);
  48. });
  49. //# sourceMappingURL=progressExample.js.map