|
| 1 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 2 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 3 | +import packageJson from "../../package.json"; |
| 4 | +import { Command } from "commander"; |
| 5 | +import { z } from "zod"; |
| 6 | +import { registerAction, type Event } from "../actions/register"; |
| 7 | +import type { AtwZero } from "../core/create-zero"; |
| 8 | +import { sleep } from "bun"; |
| 9 | + |
| 10 | +type Deps = { |
| 11 | + zero: AtwZero; |
| 12 | +}; |
| 13 | + |
| 14 | +export const createMCPServeCommand = ({ zero }: Deps): Command => { |
| 15 | + const command = new Command("mcp-serve") |
| 16 | + .description("Start the MCP server.") |
| 17 | + .action(async () => { |
| 18 | + const mcpServer = new McpServer({ |
| 19 | + name: "All Things Web meetup events", |
| 20 | + version: packageJson.version, |
| 21 | + }); |
| 22 | + |
| 23 | + mcpServer.tool( |
| 24 | + "get-events", |
| 25 | + "Get all upcoming published All Things Web events", |
| 26 | + {}, |
| 27 | + async () => { |
| 28 | + const getEvents = async (): Promise<Event[]> => { |
| 29 | + let count = 0; |
| 30 | + return new Promise(async (resolve) => { |
| 31 | + for(let i = 0; i < 10; i++) { |
| 32 | + const events = zero.query.events |
| 33 | + //.where("startDate", ">", new Date().getTime()) |
| 34 | + .orderBy("startDate", "desc") |
| 35 | + .limit(10) |
| 36 | + .run(); |
| 37 | + if(!events.length) { |
| 38 | + count += 1; |
| 39 | + await sleep(200); |
| 40 | + } else { |
| 41 | + resolve(events); |
| 42 | + } |
| 43 | + } |
| 44 | + }); |
| 45 | + }; |
| 46 | + const events = await getEvents(); |
| 47 | + return { content: events.map((event) => ({ |
| 48 | + type: "text", |
| 49 | + text: ` |
| 50 | + name: ${event.name} |
| 51 | + start: ${event.startDate} |
| 52 | + location: ${event.shortLocation} |
| 53 | + tagline: ${event.tagline} |
| 54 | + eventId: ${event.id}` |
| 55 | + })) }; |
| 56 | + }, |
| 57 | + ); |
| 58 | + |
| 59 | + mcpServer.tool( |
| 60 | + "register", |
| 61 | + "Register to an All Things Web event", |
| 62 | + { |
| 63 | + eventId: z.string().describe("The event id to register to."), |
| 64 | + email: z.string().email().describe("The email to register with."), |
| 65 | + }, |
| 66 | + async ({ eventId, email }) => { |
| 67 | + const results = await registerAction(email, eventId); |
| 68 | + let text = "Registered!"; |
| 69 | + if (results.success === false) { |
| 70 | + text = `Oh no! Something went wrong! ${results.error}`; |
| 71 | + } |
| 72 | + return { |
| 73 | + content: [{ type: "text", text }, {type: "text", text: `eventId: ${eventId}`}], |
| 74 | + }; |
| 75 | + }, |
| 76 | + ); |
| 77 | + |
| 78 | + const stdioServer = new StdioServerTransport(); |
| 79 | + await mcpServer.connect(stdioServer); |
| 80 | + }); |
| 81 | + return command; |
| 82 | +}; |
0 commit comments