|
| 1 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 2 | +import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { logger } from "../utilities/logger.js"; |
| 5 | +import { CliApiClient } from "../apiClient.js"; |
| 6 | +import { ApiClient } from "@trigger.dev/core/v3"; |
| 7 | +import polka from "polka"; |
| 8 | + |
| 9 | +let projectRef: string; |
| 10 | +let dashboardUrl: string; |
| 11 | +// there is some overlap between `ApiClient` and `CliApiClient` which is not ideal |
| 12 | +// we can address in this in the future, but for now we need keep using both |
| 13 | +// as `ApiClient` exposes most of the methods needed for the MCP tools |
| 14 | +let sdkApiClient: ApiClient; |
| 15 | + |
| 16 | +let mcpTransport: SSEServerTransport | null = null; |
| 17 | + |
| 18 | +const server = new McpServer({ |
| 19 | + name: "trigger.dev", |
| 20 | + version: "1.0.0", |
| 21 | +}); |
| 22 | + |
| 23 | +server.tool( |
| 24 | + "trigger-task", |
| 25 | + "Trigger a task", |
| 26 | + { |
| 27 | + id: z.string().describe("The id of the task to trigger"), |
| 28 | + }, |
| 29 | + async ({ id }) => { |
| 30 | + const result = await sdkApiClient.triggerTask(id, { |
| 31 | + // TODO: enable the user to pass in a custom payload |
| 32 | + payload: {}, |
| 33 | + }); |
| 34 | + |
| 35 | + const taskRunUrl = `${dashboardUrl}/projects/v3/${projectRef}/runs/${result.id}`; |
| 36 | + |
| 37 | + return { |
| 38 | + content: [ |
| 39 | + { |
| 40 | + type: "text", |
| 41 | + text: JSON.stringify({ ...result, taskRunUrl }, null, 2), |
| 42 | + }, |
| 43 | + ], |
| 44 | + }; |
| 45 | + } |
| 46 | +); |
| 47 | + |
| 48 | +const app = polka(); |
| 49 | +app.get("/sse", (_req, res) => { |
| 50 | + mcpTransport = new SSEServerTransport("/messages", res); |
| 51 | + server.connect(mcpTransport); |
| 52 | +}); |
| 53 | +app.post("/messages", (req, res) => { |
| 54 | + if (mcpTransport) { |
| 55 | + mcpTransport.handlePostMessage(req, res); |
| 56 | + } |
| 57 | +}); |
| 58 | + |
| 59 | +export const startMcpServer = async (options: { |
| 60 | + cliApiClient: CliApiClient; |
| 61 | + devSession: { |
| 62 | + dashboardUrl: string; |
| 63 | + projectRef: string; |
| 64 | + }; |
| 65 | +}) => { |
| 66 | + const { apiURL, accessToken } = options.cliApiClient; |
| 67 | + |
| 68 | + if (!accessToken) { |
| 69 | + logger.error("No access token found in the API client, failed to start the MCP server"); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + sdkApiClient = new ApiClient(apiURL, accessToken); |
| 74 | + projectRef = options.devSession.projectRef; |
| 75 | + dashboardUrl = options.devSession.dashboardUrl; |
| 76 | + |
| 77 | + // TODO: make the port configurable |
| 78 | + const port = 3333; |
| 79 | + app.listen(port, () => { |
| 80 | + logger.info(`Trigger.dev MCP Server is now running on port ${port} ✨`); |
| 81 | + }); |
| 82 | +}; |
0 commit comments