progressExample.js 1.6 KB

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