diff --git a/.github/workflows/deploy-preview.yml b/.github/workflows/deploy-preview.yml index f5c74a3b85c..840efc5ff7f 100644 --- a/.github/workflows/deploy-preview.yml +++ b/.github/workflows/deploy-preview.yml @@ -184,6 +184,7 @@ jobs: POSTHOG_PROJECT_ID: ${{ secrets.POSTHOG_PROJECT_ID }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} LINEAR_CLIENT_ID: ${{ secrets.LINEAR_CLIENT_ID }} LINEAR_CLIENT_SECRET: ${{ secrets.LINEAR_CLIENT_SECRET }} @@ -223,6 +224,7 @@ jobs: --env POSTHOG_PROJECT_ID=$POSTHOG_PROJECT_ID \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env LINEAR_CLIENT_ID=$LINEAR_CLIENT_ID \ --env LINEAR_CLIENT_SECRET=$LINEAR_CLIENT_SECRET \ @@ -316,6 +318,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -340,6 +343,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ @@ -407,6 +411,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -428,6 +433,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ @@ -510,6 +516,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -535,6 +542,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index 55bfc378dfe..ad96f6c91b5 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -88,6 +88,7 @@ jobs: POSTHOG_PROJECT_ID: ${{ secrets.POSTHOG_PROJECT_ID }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} LINEAR_CLIENT_ID: ${{ secrets.LINEAR_CLIENT_ID }} LINEAR_CLIENT_SECRET: ${{ secrets.LINEAR_CLIENT_SECRET }} @@ -127,6 +128,7 @@ jobs: --env POSTHOG_PROJECT_ID=$POSTHOG_PROJECT_ID \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env LINEAR_CLIENT_ID=$LINEAR_CLIENT_ID \ --env LINEAR_CLIENT_SECRET=$LINEAR_CLIENT_SECRET \ @@ -192,6 +194,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -216,6 +219,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ @@ -267,6 +271,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -288,6 +293,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ @@ -343,6 +349,7 @@ jobs: NEXT_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }} KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }} + KV_URL: ${{ secrets.KV_URL }} RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} @@ -368,6 +375,7 @@ jobs: --env NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT \ --env KV_REST_API_URL=$KV_REST_API_URL \ --env KV_REST_API_TOKEN=$KV_REST_API_TOKEN \ + --env KV_URL=$KV_URL \ --env RESEND_API_KEY=$RESEND_API_KEY \ --env STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY \ --env STRIPE_WEBHOOK_SECRET=$STRIPE_WEBHOOK_SECRET \ diff --git a/apps/api/package.json b/apps/api/package.json index 509d8f5fdb9..ad0a03f780c 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -26,13 +26,13 @@ "@trpc/server": "^11.7.1", "@upstash/qstash": "^2.8.4", "@vercel/blob": "^2.0.0", - "@vercel/mcp-adapter": "^1.0.0", "better-auth": "1.4.17", "date-fns": "^4.1.0", "drizzle-orm": "0.45.1", "import-in-the-middle": "2.0.1", "jose": "^6.1.3", "lodash.chunk": "^4.2.0", + "mcp-handler": "^1.0.7", "next": "^16.0.10", "react": "19.1.0", "react-dom": "19.1.0", diff --git a/apps/api/src/app/api/agent/[transport]/route.ts b/apps/api/src/app/api/agent/[transport]/route.ts index 0c6c84e2c03..da35f47e3da 100644 --- a/apps/api/src/app/api/agent/[transport]/route.ts +++ b/apps/api/src/app/api/agent/[transport]/route.ts @@ -1,130 +1,78 @@ import { auth } from "@superset/auth/server"; -import { createMcpHandler, withMcpAuth } from "@vercel/mcp-adapter"; -import { buildMcpContext, type McpContext } from "@/lib/mcp/auth"; -import { registerMcpTools } from "@/lib/mcp/tools"; - -/** - * Verify token using Better Auth (API key or OAuth) - * Returns AuthInfo with McpContext in extra field - */ -async function verifyToken( - req: Request, - bearerToken?: string, -): Promise< - | { - token: string; - clientId: string; - scopes: string[]; - extra: { mcpContext: McpContext }; - } - | undefined -> { - // 1. Try Better Auth session (handles x-api-key header via apiKey plugin) - const session = await auth.api.getSession({ - headers: req.headers, - }); +import { createMcpHandler, withMcpAuth } from "mcp-handler"; +import { env } from "@/env"; +import type { McpContext } from "@/lib/mcp/auth"; +import { registerTools } from "@/lib/mcp/tools"; +async function verifyToken(req: Request, bearerToken?: string) { + // 1. Try session auth + const session = await auth.api.getSession({ headers: req.headers }); if (session?.session) { - const { user, session: sess } = session; - const extendedSession = sess as typeof sess & { - activeOrganizationId?: string | null; - role?: string; - plan?: string | null; + const extendedSession = session.session as { + activeOrganizationId?: string; }; - if (!extendedSession.activeOrganizationId) { - console.error("[mcp/auth] Session has no activeOrganizationId:", user.id); + console.error("[mcp/auth] Session missing activeOrganizationId"); return undefined; } - - const mcpContext: McpContext = { - userId: user.id, - organizationId: extendedSession.activeOrganizationId, - role: extendedSession.role ?? null, - plan: extendedSession.plan ?? null, - defaultDeviceId: null, - }; - return { token: "session", clientId: "session", scopes: ["mcp:full"], - extra: { mcpContext }, + extra: { + mcpContext: { + userId: session.user.id, + organizationId: extendedSession.activeOrganizationId, + } satisfies McpContext, + }, }; } - // 2. Try MCP OAuth bearer token + // 2. Try OAuth bearer token if (bearerToken) { - const mcpSession = await auth.api.getMcpSession({ - headers: req.headers, - }); - - if (mcpSession) { - // Extract organizationId from OAuth token scopes - const rawScopes = mcpSession.scopes; - const scopeArray = Array.isArray(rawScopes) - ? rawScopes - : typeof rawScopes === "string" - ? rawScopes.split(" ") - : []; - const orgScope = scopeArray.find((s) => s.startsWith("organization:")); - const organizationId = orgScope?.split(":")[1]; - - if (!organizationId) { - console.error( - "[mcp/auth] OAuth token missing organization scope:", - mcpSession.userId, - ); - return undefined; - } + const mcpSession = await auth.api.getMcpSession({ headers: req.headers }); + if (!mcpSession) return undefined; - const mcpContext = await buildMcpContext({ - userId: mcpSession.userId, - organizationId, - }); + const scopes = Array.isArray(mcpSession.scopes) + ? mcpSession.scopes + : (mcpSession.scopes?.split(" ") ?? []); - if (!mcpContext) { - return undefined; - } + // Get organization from scope + const orgScope = scopes.find((s) => s.startsWith("organization:")); + const organizationId = orgScope?.split(":")[1]; - return { - token: bearerToken, - clientId: mcpSession.clientId ?? "mcp-client", - scopes: scopeArray, - extra: { mcpContext }, - }; + if (!organizationId) { + console.error("[mcp/auth] OAuth token missing organization scope"); + return undefined; } + + return { + token: bearerToken, + clientId: mcpSession.clientId ?? "mcp-client", + scopes, + extra: { + mcpContext: { + userId: mcpSession.userId, + organizationId, + } satisfies McpContext, + }, + }; } return undefined; } -/** - * Create the base MCP handler - * Tools access context via extra.authInfo.extra.mcpContext - */ const baseHandler = createMcpHandler( - (server) => { - registerMcpTools(server); - }, - { - capabilities: { - tools: {}, - }, - }, + (server) => registerTools(server), + { capabilities: { tools: {} } }, { - redisUrl: process.env.UPSTASH_REDIS_URL, + redisUrl: env.KV_URL, basePath: "/api/agent", - verboseLogs: process.env.NODE_ENV === "development", + verboseLogs: env.NODE_ENV === "development", maxDuration: 60, }, ); -/** - * Wrap with authentication - */ -const handler = withMcpAuth(baseHandler, verifyToken, { - required: true, -}); +const handler = withMcpAuth(baseHandler, verifyToken, { required: true }); export { handler as GET, handler as POST, handler as DELETE }; diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 0b86929c46c..b83d7c741a8 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -30,6 +30,7 @@ export const env = createEnv({ RESEND_API_KEY: z.string(), KV_REST_API_URL: z.string(), KV_REST_API_TOKEN: z.string(), + KV_URL: z.string().url(), STRIPE_SECRET_KEY: z.string(), STRIPE_WEBHOOK_SECRET: z.string(), STRIPE_PRO_MONTHLY_PRICE_ID: z.string(), diff --git a/apps/api/src/lib/mcp/auth.ts b/apps/api/src/lib/mcp/auth.ts index be83e006c48..e5b82d12ae0 100644 --- a/apps/api/src/lib/mcp/auth.ts +++ b/apps/api/src/lib/mcp/auth.ts @@ -1,73 +1,4 @@ -import { db } from "@superset/db/client"; -import { members, subscriptions } from "@superset/db/schema"; -import { and, eq } from "drizzle-orm"; - export interface McpContext { userId: string; organizationId: string; - role: string | null; - plan: string | null; - defaultDeviceId: string | null; -} - -export async function buildMcpContext({ - userId, - organizationId, -}: { - userId: string; - organizationId: string; -}): Promise { - const membership = await db.query.members.findFirst({ - where: and( - eq(members.userId, userId), - eq(members.organizationId, organizationId), - ), - }); - - if (!membership) { - console.error( - "[mcp/auth] User is not a member of organization:", - userId, - organizationId, - ); - return null; - } - - const subscription = await db.query.subscriptions.findFirst({ - where: and( - eq(subscriptions.referenceId, organizationId), - eq(subscriptions.status, "active"), - ), - }); - - return { - userId, - organizationId: organizationId, - role: membership.role ?? null, - plan: subscription?.plan ?? null, - defaultDeviceId: null, - }; -} - -export function createUnauthorizedResponse(): Response { - const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"; - const resourceMetadataUrl = `${baseUrl}/.well-known/oauth-protected-resource`; - - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - error: { - code: -32001, - message: "Unauthorized: Invalid or missing credentials", - }, - id: null, - }), - { - status: 401, - headers: { - "Content-Type": "application/json", - "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadataUrl}"`, - }, - }, - ); } diff --git a/apps/api/src/lib/mcp/tools.ts b/apps/api/src/lib/mcp/tools.ts deleted file mode 100644 index ca81930a75b..00000000000 --- a/apps/api/src/lib/mcp/tools.ts +++ /dev/null @@ -1,1125 +0,0 @@ -import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { db, dbWs } from "@superset/db/client"; -import { - agentCommands, - devicePresence, - members, - taskStatuses, - tasks, - users, -} from "@superset/db/schema"; -import { getCurrentTxid } from "@superset/db/utils"; -import { and, desc, eq, gt, ilike, isNull, or } from "drizzle-orm"; -import { alias } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import type { McpContext } from "./auth"; - -const DEVICE_ONLINE_THRESHOLD_MS = 60_000; // 60 seconds - -/** - * Extra parameter passed to tool handlers by withMcpAuth - */ -interface ToolHandlerExtra { - authInfo?: { - extra?: { - mcpContext?: McpContext; - }; - }; -} - -/** - * Extract McpContext from tool handler's extra parameter - */ -function getContext(extra: ToolHandlerExtra): McpContext { - const ctx = extra.authInfo?.extra?.mcpContext; - if (!ctx) { - throw new Error("No MCP context available - authentication required"); - } - return ctx; -} - -/** - * Register all MCP tools on the server - * Tools access context via extra.authInfo.extra.mcpContext - */ -export function registerMcpTools(server: McpServer) { - // ======================================== - // TASK TOOLS (Cloud - Immediate Execution) - // ======================================== - - server.tool( - "create_task", - "Create a new task in the organization", - { - title: z.string().min(1).describe("Task title"), - description: z - .string() - .optional() - .describe("Task description (markdown)"), - priority: z - .enum(["urgent", "high", "medium", "low", "none"]) - .default("none") - .describe("Task priority"), - assigneeId: z - .string() - .uuid() - .optional() - .describe("User ID to assign the task to"), - statusId: z - .string() - .uuid() - .optional() - .describe("Status ID (defaults to first backlog status)"), - labels: z.array(z.string()).optional().describe("Array of label strings"), - dueDate: z - .string() - .datetime() - .optional() - .describe("Due date in ISO format"), - estimate: z - .number() - .int() - .positive() - .optional() - .describe("Estimate in points/hours"), - }, - async (params, extra) => { - const ctx = getContext(extra); - - // Get default status if not provided - let statusId = params.statusId; - if (!statusId) { - const defaultStatus = await db - .select() - .from(taskStatuses) - .where( - and( - eq(taskStatuses.organizationId, ctx.organizationId), - eq(taskStatuses.type, "backlog"), - ), - ) - .orderBy(taskStatuses.position) - .limit(1); - statusId = defaultStatus[0]?.id; - if (!statusId) { - return { - content: [ - { - type: "text", - text: "Error: No default status found for organization", - }, - ], - isError: true, - }; - } - } - - // Generate slug from title - const slug = params.title - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, "") - .slice(0, 50); - - // Check for existing slug and make unique - const existingTasks = await db - .select({ slug: tasks.slug }) - .from(tasks) - .where( - and( - eq(tasks.organizationId, ctx.organizationId), - ilike(tasks.slug, `${slug}%`), - ), - ); - - let uniqueSlug = slug; - if (existingTasks.length > 0) { - const existingSlugs = new Set(existingTasks.map((t) => t.slug)); - let counter = 1; - while (existingSlugs.has(uniqueSlug)) { - uniqueSlug = `${slug}-${counter}`; - counter++; - } - } - - const result = await dbWs.transaction(async (tx) => { - const [task] = await tx - .insert(tasks) - .values({ - slug: uniqueSlug, - title: params.title, - description: params.description ?? null, - priority: params.priority ?? "none", - statusId, - organizationId: ctx.organizationId, - creatorId: ctx.userId, - assigneeId: params.assigneeId ?? null, - labels: params.labels ?? [], - dueDate: params.dueDate ? new Date(params.dueDate) : null, - estimate: params.estimate ?? null, - }) - .returning(); - - const txid = await getCurrentTxid(tx); - return { task, txid }; - }); - - return { - content: [ - { - type: "text", - text: JSON.stringify( - { - id: result.task?.id, - slug: result.task?.slug, - title: result.task?.title, - txid: result.txid, - }, - null, - 2, - ), - }, - ], - }; - }, - ); - - server.tool( - "update_task", - "Update an existing task", - { - taskId: z.string().describe("Task ID (uuid) or slug"), - title: z.string().min(1).optional().describe("New title"), - description: z.string().optional().describe("New description"), - priority: z.enum(["urgent", "high", "medium", "low", "none"]).optional(), - assigneeId: z - .string() - .uuid() - .nullable() - .optional() - .describe("New assignee (null to unassign)"), - statusId: z.string().uuid().optional().describe("New status ID"), - labels: z.array(z.string()).optional().describe("Replace labels"), - dueDate: z - .string() - .datetime() - .nullable() - .optional() - .describe("New due date (null to clear)"), - estimate: z.number().int().positive().nullable().optional(), - }, - async (params, extra) => { - const ctx = getContext(extra); - - // Find task by ID or slug - const isUuid = - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( - params.taskId, - ); - const [existingTask] = await db - .select() - .from(tasks) - .where( - and( - isUuid - ? eq(tasks.id, params.taskId) - : eq(tasks.slug, params.taskId), - eq(tasks.organizationId, ctx.organizationId), - isNull(tasks.deletedAt), - ), - ) - .limit(1); - - if (!existingTask) { - return { - content: [{ type: "text", text: "Error: Task not found" }], - isError: true, - }; - } - - const updateData: Record = {}; - if (params.title !== undefined) updateData.title = params.title; - if (params.description !== undefined) - updateData.description = params.description; - if (params.priority !== undefined) updateData.priority = params.priority; - if (params.assigneeId !== undefined) - updateData.assigneeId = params.assigneeId; - if (params.statusId !== undefined) updateData.statusId = params.statusId; - if (params.labels !== undefined) updateData.labels = params.labels; - if (params.dueDate !== undefined) - updateData.dueDate = params.dueDate ? new Date(params.dueDate) : null; - if (params.estimate !== undefined) updateData.estimate = params.estimate; - - const result = await dbWs.transaction(async (tx) => { - const [task] = await tx - .update(tasks) - .set(updateData) - .where(eq(tasks.id, existingTask.id)) - .returning(); - - const txid = await getCurrentTxid(tx); - return { task, txid }; - }); - - return { - content: [ - { - type: "text", - text: JSON.stringify( - { - id: result.task?.id, - slug: result.task?.slug, - title: result.task?.title, - txid: result.txid, - }, - null, - 2, - ), - }, - ], - }; - }, - ); - - server.tool( - "list_tasks", - "List tasks with optional filters", - { - statusId: z.string().uuid().optional().describe("Filter by status ID"), - statusType: z - .enum(["backlog", "unstarted", "started", "completed", "canceled"]) - .optional() - .describe("Filter by status type"), - assigneeId: z.string().uuid().optional().describe("Filter by assignee"), - assignedToMe: z - .boolean() - .optional() - .describe("Filter to tasks assigned to current user"), - priority: z.enum(["urgent", "high", "medium", "low", "none"]).optional(), - search: z.string().optional().describe("Search in title/description"), - limit: z.number().int().min(1).max(100).default(50), - offset: z.number().int().min(0).default(0), - }, - async (params, extra) => { - const ctx = getContext(extra); - const assignee = alias(users, "assignee"); - const status = alias(taskStatuses, "status"); - - const conditions = [ - eq(tasks.organizationId, ctx.organizationId), - isNull(tasks.deletedAt), - ]; - - if (params.statusId) { - conditions.push(eq(tasks.statusId, params.statusId)); - } - - if (params.assigneeId) { - conditions.push(eq(tasks.assigneeId, params.assigneeId)); - } else if (params.assignedToMe) { - conditions.push(eq(tasks.assigneeId, ctx.userId)); - } - - if (params.priority) { - conditions.push(eq(tasks.priority, params.priority)); - } - - if (params.search) { - const searchCondition = or( - ilike(tasks.title, `%${params.search}%`), - ilike(tasks.description, `%${params.search}%`), - ); - if (searchCondition) { - conditions.push(searchCondition); - } - } - - // Add status type filter if provided - if (params.statusType) { - // Get status IDs of the requested type - const statusesOfType = await db - .select({ id: taskStatuses.id }) - .from(taskStatuses) - .where( - and( - eq(taskStatuses.organizationId, ctx.organizationId), - eq(taskStatuses.type, params.statusType), - ), - ); - const statusIds = statusesOfType.map((s) => s.id); - if (statusIds.length > 0) { - const statusCondition = or( - ...statusIds.map((id) => eq(tasks.statusId, id)), - ); - if (statusCondition) { - conditions.push(statusCondition); - } - } else { - // No statuses of this type, return empty - return { - content: [ - { - type: "text", - text: JSON.stringify( - { tasks: [], count: 0, hasMore: false }, - null, - 2, - ), - }, - ], - }; - } - } - - const tasksList = await db - .select({ - id: tasks.id, - slug: tasks.slug, - title: tasks.title, - description: tasks.description, - priority: tasks.priority, - statusId: tasks.statusId, - statusName: status.name, - statusType: status.type, - assigneeId: tasks.assigneeId, - assigneeName: assignee.name, - labels: tasks.labels, - dueDate: tasks.dueDate, - estimate: tasks.estimate, - createdAt: tasks.createdAt, - }) - .from(tasks) - .leftJoin(assignee, eq(tasks.assigneeId, assignee.id)) - .leftJoin(status, eq(tasks.statusId, status.id)) - .where(and(...conditions)) - .orderBy(desc(tasks.createdAt)) - .limit(params.limit) - .offset(params.offset); - - return { - content: [ - { - type: "text", - text: JSON.stringify( - { - tasks: tasksList, - count: tasksList.length, - hasMore: tasksList.length === params.limit, - }, - null, - 2, - ), - }, - ], - }; - }, - ); - - server.tool( - "get_task", - "Get a single task by ID or slug", - { - taskId: z.string().describe("Task ID (uuid) or slug"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const isUuid = - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( - params.taskId, - ); - - const assignee = alias(users, "assignee"); - const creator = alias(users, "creator"); - const status = alias(taskStatuses, "status"); - - const [task] = await db - .select({ - id: tasks.id, - slug: tasks.slug, - title: tasks.title, - description: tasks.description, - priority: tasks.priority, - statusId: tasks.statusId, - statusName: status.name, - statusType: status.type, - statusColor: status.color, - assigneeId: tasks.assigneeId, - assigneeName: assignee.name, - assigneeEmail: assignee.email, - creatorId: tasks.creatorId, - creatorName: creator.name, - labels: tasks.labels, - dueDate: tasks.dueDate, - estimate: tasks.estimate, - branch: tasks.branch, - prUrl: tasks.prUrl, - createdAt: tasks.createdAt, - updatedAt: tasks.updatedAt, - }) - .from(tasks) - .leftJoin(assignee, eq(tasks.assigneeId, assignee.id)) - .leftJoin(creator, eq(tasks.creatorId, creator.id)) - .leftJoin(status, eq(tasks.statusId, status.id)) - .where( - and( - isUuid - ? eq(tasks.id, params.taskId) - : eq(tasks.slug, params.taskId), - eq(tasks.organizationId, ctx.organizationId), - isNull(tasks.deletedAt), - ), - ) - .limit(1); - - if (!task) { - return { - content: [{ type: "text", text: "Error: Task not found" }], - isError: true, - }; - } - - return { - content: [{ type: "text", text: JSON.stringify(task, null, 2) }], - }; - }, - ); - - server.tool( - "delete_task", - "Soft delete a task", - { - taskId: z.string().describe("Task ID (uuid) or slug"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const isUuid = - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( - params.taskId, - ); - - const [existingTask] = await db - .select() - .from(tasks) - .where( - and( - isUuid - ? eq(tasks.id, params.taskId) - : eq(tasks.slug, params.taskId), - eq(tasks.organizationId, ctx.organizationId), - isNull(tasks.deletedAt), - ), - ) - .limit(1); - - if (!existingTask) { - return { - content: [{ type: "text", text: "Error: Task not found" }], - isError: true, - }; - } - - const result = await dbWs.transaction(async (tx) => { - await tx - .update(tasks) - .set({ deletedAt: new Date() }) - .where(eq(tasks.id, existingTask.id)); - - const txid = await getCurrentTxid(tx); - return { txid }; - }); - - return { - content: [ - { - type: "text", - text: JSON.stringify( - { - success: true, - deletedAt: new Date().toISOString(), - txid: result.txid, - }, - null, - 2, - ), - }, - ], - }; - }, - ); - - // ======================================== - // ORGANIZATION TOOLS (Cloud - Immediate) - // ======================================== - - server.tool( - "list_members", - "List members in the organization", - { - search: z.string().optional().describe("Search by name or email"), - limit: z.number().int().min(1).max(100).default(50), - }, - async (params, extra) => { - const ctx = getContext(extra); - const conditions = [eq(members.organizationId, ctx.organizationId)]; - - let query = db - .select({ - id: users.id, - name: users.name, - email: users.email, - image: users.image, - role: members.role, - }) - .from(members) - .innerJoin(users, eq(members.userId, users.id)) - .where(and(...conditions)) - .limit(params.limit); - - if (params.search) { - query = db - .select({ - id: users.id, - name: users.name, - email: users.email, - image: users.image, - role: members.role, - }) - .from(members) - .innerJoin(users, eq(members.userId, users.id)) - .where( - and( - ...conditions, - or( - ilike(users.name, `%${params.search}%`), - ilike(users.email, `%${params.search}%`), - ), - ), - ) - .limit(params.limit); - } - - const membersList = await query; - - return { - content: [ - { - type: "text", - text: JSON.stringify({ members: membersList }, null, 2), - }, - ], - }; - }, - ); - - server.tool( - "list_task_statuses", - "List available task statuses for the organization", - {}, - async (_params, extra) => { - const ctx = getContext(extra); - const statuses = await db - .select({ - id: taskStatuses.id, - name: taskStatuses.name, - color: taskStatuses.color, - type: taskStatuses.type, - position: taskStatuses.position, - }) - .from(taskStatuses) - .where(eq(taskStatuses.organizationId, ctx.organizationId)) - .orderBy(taskStatuses.position); - - return { - content: [ - { type: "text", text: JSON.stringify({ statuses }, null, 2) }, - ], - }; - }, - ); - - // ======================================== - // DEVICE TOOLS (Cloud - Query) - // ======================================== - - server.tool( - "list_devices", - "List online devices in the organization", - { - includeOffline: z - .boolean() - .default(false) - .describe("Include recently offline devices"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const threshold = new Date(Date.now() - DEVICE_ONLINE_THRESHOLD_MS); - const offlineThreshold = new Date( - Date.now() - DEVICE_ONLINE_THRESHOLD_MS * 10, - ); // 10 minutes for recently offline - - const conditions = [ - eq(devicePresence.organizationId, ctx.organizationId), - ]; - - if (!params.includeOffline) { - conditions.push(gt(devicePresence.lastSeenAt, threshold)); - } else { - conditions.push(gt(devicePresence.lastSeenAt, offlineThreshold)); - } - - const devices = await db - .select({ - deviceId: devicePresence.deviceId, - deviceName: devicePresence.deviceName, - deviceType: devicePresence.deviceType, - lastSeenAt: devicePresence.lastSeenAt, - ownerId: devicePresence.userId, - ownerName: users.name, - ownerEmail: users.email, - }) - .from(devicePresence) - .innerJoin(users, eq(devicePresence.userId, users.id)) - .where(and(...conditions)) - .orderBy(desc(devicePresence.lastSeenAt)); - - const devicesWithStatus = devices.map((d) => ({ - ...d, - isOnline: d.lastSeenAt > threshold, - })); - - return { - content: [ - { - type: "text", - text: JSON.stringify({ devices: devicesWithStatus }, null, 2), - }, - ], - }; - }, - ); - - // ======================================== - // DEVICE TOOLS (Routed to Desktop) - // ======================================== - - server.tool( - "list_workspaces", - "List all workspaces/worktrees on a device", - { - deviceId: z - .string() - .optional() - .describe("Target device (defaults to caller's device)"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "list_workspaces", - params: {}, - }); - }, - ); - - server.tool( - "list_projects", - "List all projects on a device", - { - deviceId: z - .string() - .optional() - .describe("Target device (defaults to caller's device)"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "list_projects", - params: {}, - }); - }, - ); - - server.tool( - "get_app_context", - "Get the current app context including pathname and active workspace", - { - deviceId: z.string().optional(), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "get_app_context", - params: {}, - }); - }, - ); - - server.tool( - "navigate_to_workspace", - "Navigate the desktop app to a specific workspace", - { - deviceId: z.string().optional(), - workspaceId: z - .string() - .optional() - .describe("Workspace ID to navigate to"), - workspaceName: z - .string() - .optional() - .describe("Workspace name to navigate to"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - if (!params.workspaceId && !params.workspaceName) { - return { - content: [ - { - type: "text", - text: "Error: Either workspaceId or workspaceName must be provided", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "navigate_to_workspace", - params: { - workspaceId: params.workspaceId, - workspaceName: params.workspaceName, - }, - }); - }, - ); - - server.tool( - "create_workspace", - "Create a new git worktree workspace", - { - deviceId: z.string().optional(), - name: z - .string() - .optional() - .describe("Workspace name (auto-generated if not provided)"), - branchName: z - .string() - .optional() - .describe("Branch name (auto-generated if not provided)"), - baseBranch: z - .string() - .optional() - .describe("Branch to create from (defaults to main)"), - taskId: z - .string() - .optional() - .describe("Task ID to associate with workspace"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "create_workspace", - params: { - name: params.name, - branchName: params.branchName, - baseBranch: params.baseBranch, - }, - }); - }, - ); - - server.tool( - "switch_workspace", - "Switch to a different workspace", - { - deviceId: z.string().optional(), - workspaceId: z - .string() - .uuid() - .optional() - .describe("Workspace ID to switch to"), - workspaceName: z - .string() - .optional() - .describe("Workspace name to switch to"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - if (!params.workspaceId && !params.workspaceName) { - return { - content: [ - { - type: "text", - text: "Error: Either workspaceId or workspaceName must be provided", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "switch_workspace", - params: { - workspaceId: params.workspaceId, - workspaceName: params.workspaceName, - }, - }); - }, - ); - - server.tool( - "delete_workspace", - "Delete a workspace", - { - deviceId: z.string().optional(), - workspaceId: z.string().uuid().describe("Workspace ID to delete"), - }, - async (params, extra) => { - const ctx = getContext(extra); - const targetDeviceId = params.deviceId ?? ctx.defaultDeviceId; - - if (!targetDeviceId) { - return { - content: [ - { - type: "text", - text: "Error: No device specified and no default device configured", - }, - ], - isError: true, - }; - } - - return executeOnDevice({ - ctx, - deviceId: targetDeviceId, - tool: "delete_workspace", - params: { - workspaceId: params.workspaceId, - }, - }); - }, - ); -} - -// ======================================== -// DEVICE COMMAND EXECUTION -// ======================================== - -const POLL_INTERVAL_MS = 500; -const DEFAULT_TIMEOUT_MS = 30_000; - -interface ExecuteOnDeviceParams { - ctx: McpContext; - deviceId: string; - tool: string; - params: Record; - timeout?: number; -} - -async function executeOnDevice({ - ctx, - deviceId, - tool, - params, - timeout = DEFAULT_TIMEOUT_MS, -}: ExecuteOnDeviceParams): Promise<{ - content: Array<{ type: "text"; text: string }>; - isError?: boolean; -}> { - const threshold = new Date(Date.now() - DEVICE_ONLINE_THRESHOLD_MS); - - // Check device is online - const [device] = await db - .select() - .from(devicePresence) - .where( - and( - eq(devicePresence.deviceId, deviceId), - eq(devicePresence.organizationId, ctx.organizationId), - gt(devicePresence.lastSeenAt, threshold), - ), - ) - .limit(1); - - if (!device) { - return { - content: [ - { - type: "text", - text: `Error: Device ${deviceId} is not online or not found in this organization`, - }, - ], - isError: true, - }; - } - - // Create command - const [cmd] = await db - .insert(agentCommands) - .values({ - userId: ctx.userId, - organizationId: ctx.organizationId, - targetDeviceId: deviceId, - targetDeviceType: device.deviceType, - tool, - params, - status: "pending", - timeoutAt: new Date(Date.now() + timeout), - }) - .returning(); - - if (!cmd) { - return { - content: [{ type: "text", text: "Error: Failed to create command" }], - isError: true, - }; - } - - // Poll for result - const startTime = Date.now(); - - while (Date.now() - startTime < timeout) { - const [updated] = await db - .select() - .from(agentCommands) - .where(eq(agentCommands.id, cmd.id)) - .limit(1); - - if (updated?.status === "completed") { - return { - content: [ - { - type: "text", - text: JSON.stringify(updated.result ?? { success: true }, null, 2), - }, - ], - }; - } - - if (updated?.status === "failed") { - return { - content: [ - { - type: "text", - text: `Error: ${updated.error ?? "Command failed"}`, - }, - ], - isError: true, - }; - } - - // Wait before next poll - await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); - } - - // Mark as timeout - await db - .update(agentCommands) - .set({ status: "timeout" }) - .where(eq(agentCommands.id, cmd.id)); - - return { - content: [ - { - type: "text", - text: `Error: Command timed out after ${timeout}ms. The device may be offline or busy.`, - }, - ], - isError: true, - }; -} diff --git a/apps/api/src/lib/mcp/tools/devices/create-workspace/create-workspace.ts b/apps/api/src/lib/mcp/tools/devices/create-workspace/create-workspace.ts new file mode 100644 index 00000000000..bede438152a --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/create-workspace/create-workspace.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "create_workspace", + { + description: "Create a new git worktree workspace", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + name: z + .string() + .optional() + .describe("Workspace name (auto-generated if not provided)"), + branchName: z + .string() + .optional() + .describe("Branch name (auto-generated if not provided)"), + baseBranch: z + .string() + .optional() + .describe("Branch to create from (defaults to main)"), + taskId: z + .string() + .optional() + .describe("Task ID to associate with workspace"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "create_workspace", + params: { + name: params.name, + branchName: params.branchName, + baseBranch: params.baseBranch, + taskId: params.taskId, + }, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/create-workspace/index.ts b/apps/api/src/lib/mcp/tools/devices/create-workspace/index.ts new file mode 100644 index 00000000000..2ce9cc6b818 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/create-workspace/index.ts @@ -0,0 +1 @@ +export { register } from "./create-workspace"; diff --git a/apps/api/src/lib/mcp/tools/devices/delete-workspace/delete-workspace.ts b/apps/api/src/lib/mcp/tools/devices/delete-workspace/delete-workspace.ts new file mode 100644 index 00000000000..83cb6d6ed1c --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/delete-workspace/delete-workspace.ts @@ -0,0 +1,31 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "delete_workspace", + { + description: "Delete a workspace", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + workspaceId: z.string().uuid().describe("Workspace ID to delete"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + const workspaceId = params.workspaceId as string; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "delete_workspace", + params: { workspaceId }, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/delete-workspace/index.ts b/apps/api/src/lib/mcp/tools/devices/delete-workspace/index.ts new file mode 100644 index 00000000000..10bd1d26194 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/delete-workspace/index.ts @@ -0,0 +1 @@ +export { register } from "./delete-workspace"; diff --git a/apps/api/src/lib/mcp/tools/devices/get-app-context/get-app-context.ts b/apps/api/src/lib/mcp/tools/devices/get-app-context/get-app-context.ts new file mode 100644 index 00000000000..ecc4c845646 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/get-app-context/get-app-context.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "get_app_context", + { + description: + "Get the current app context including pathname and active workspace", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "get_app_context", + params: {}, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/get-app-context/index.ts b/apps/api/src/lib/mcp/tools/devices/get-app-context/index.ts new file mode 100644 index 00000000000..00f89158e9f --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/get-app-context/index.ts @@ -0,0 +1 @@ +export { register } from "./get-app-context"; diff --git a/apps/api/src/lib/mcp/tools/devices/list-devices/index.ts b/apps/api/src/lib/mcp/tools/devices/list-devices/index.ts new file mode 100644 index 00000000000..8d26a8b2e30 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-devices/index.ts @@ -0,0 +1 @@ +export { register } from "./list-devices"; diff --git a/apps/api/src/lib/mcp/tools/devices/list-devices/list-devices.ts b/apps/api/src/lib/mcp/tools/devices/list-devices/list-devices.ts new file mode 100644 index 00000000000..0dc8c943cde --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-devices/list-devices.ts @@ -0,0 +1,62 @@ +import { db } from "@superset/db/client"; +import { devicePresence, users } from "@superset/db/schema"; +import { and, desc, eq, gt } from "drizzle-orm"; +import { z } from "zod"; +import { DEVICE_ONLINE_THRESHOLD_MS, registerTool } from "../../utils"; + +export const register = registerTool( + "list_devices", + { + description: "List online devices in the organization", + inputSchema: { + includeOffline: z + .boolean() + .default(false) + .describe("Include recently offline devices"), + }, + }, + async (params, ctx) => { + const includeOffline = params.includeOffline as boolean; + const threshold = new Date(Date.now() - DEVICE_ONLINE_THRESHOLD_MS); + const offlineThreshold = new Date( + Date.now() - DEVICE_ONLINE_THRESHOLD_MS * 10, + ); + + const conditions = [eq(devicePresence.organizationId, ctx.organizationId)]; + + if (!includeOffline) { + conditions.push(gt(devicePresence.lastSeenAt, threshold)); + } else { + conditions.push(gt(devicePresence.lastSeenAt, offlineThreshold)); + } + + const devices = await db + .select({ + deviceId: devicePresence.deviceId, + deviceName: devicePresence.deviceName, + deviceType: devicePresence.deviceType, + lastSeenAt: devicePresence.lastSeenAt, + ownerId: devicePresence.userId, + ownerName: users.name, + ownerEmail: users.email, + }) + .from(devicePresence) + .innerJoin(users, eq(devicePresence.userId, users.id)) + .where(and(...conditions)) + .orderBy(desc(devicePresence.lastSeenAt)); + + const devicesWithStatus = devices.map((d) => ({ + ...d, + isOnline: d.lastSeenAt > threshold, + })); + + return { + content: [ + { + type: "text", + text: JSON.stringify({ devices: devicesWithStatus }, null, 2), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/list-projects/index.ts b/apps/api/src/lib/mcp/tools/devices/list-projects/index.ts new file mode 100644 index 00000000000..18410496f5d --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-projects/index.ts @@ -0,0 +1 @@ +export { register } from "./list-projects"; diff --git a/apps/api/src/lib/mcp/tools/devices/list-projects/list-projects.ts b/apps/api/src/lib/mcp/tools/devices/list-projects/list-projects.ts new file mode 100644 index 00000000000..4ab56a1d60e --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-projects/list-projects.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "list_projects", + { + description: "List all projects on a device", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "list_projects", + params: {}, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/list-workspaces/index.ts b/apps/api/src/lib/mcp/tools/devices/list-workspaces/index.ts new file mode 100644 index 00000000000..f305c23d806 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-workspaces/index.ts @@ -0,0 +1 @@ +export { register } from "./list-workspaces"; diff --git a/apps/api/src/lib/mcp/tools/devices/list-workspaces/list-workspaces.ts b/apps/api/src/lib/mcp/tools/devices/list-workspaces/list-workspaces.ts new file mode 100644 index 00000000000..17fc74f1696 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/list-workspaces/list-workspaces.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "list_workspaces", + { + description: "List all workspaces/worktrees on a device", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "list_workspaces", + params: {}, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/index.ts b/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/index.ts new file mode 100644 index 00000000000..3b0dd7e63fa --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/index.ts @@ -0,0 +1 @@ +export { register } from "./navigate-to-workspace"; diff --git a/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/navigate-to-workspace.ts b/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/navigate-to-workspace.ts new file mode 100644 index 00000000000..8f45c467f42 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/navigate-to-workspace/navigate-to-workspace.ts @@ -0,0 +1,51 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "navigate_to_workspace", + { + description: "Navigate the desktop app to a specific workspace", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + workspaceId: z + .string() + .optional() + .describe("Workspace ID to navigate to"), + workspaceName: z + .string() + .optional() + .describe("Workspace name to navigate to"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + const workspaceId = params.workspaceId as string | undefined; + const workspaceName = params.workspaceName as string | undefined; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + if (!workspaceId && !workspaceName) { + return { + content: [ + { + type: "text", + text: "Error: Either workspaceId or workspaceName must be provided", + }, + ], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "navigate_to_workspace", + params: { workspaceId, workspaceName }, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/devices/switch-workspace/index.ts b/apps/api/src/lib/mcp/tools/devices/switch-workspace/index.ts new file mode 100644 index 00000000000..c5b8198ee6a --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/switch-workspace/index.ts @@ -0,0 +1 @@ +export { register } from "./switch-workspace"; diff --git a/apps/api/src/lib/mcp/tools/devices/switch-workspace/switch-workspace.ts b/apps/api/src/lib/mcp/tools/devices/switch-workspace/switch-workspace.ts new file mode 100644 index 00000000000..4b765cc8b89 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/devices/switch-workspace/switch-workspace.ts @@ -0,0 +1,52 @@ +import { z } from "zod"; +import { executeOnDevice, registerTool } from "../../utils"; + +export const register = registerTool( + "switch_workspace", + { + description: "Switch to a different workspace", + inputSchema: { + deviceId: z.string().describe("Target device ID"), + workspaceId: z + .string() + .uuid() + .optional() + .describe("Workspace ID to switch to"), + workspaceName: z + .string() + .optional() + .describe("Workspace name to switch to"), + }, + }, + async (params, ctx) => { + const deviceId = params.deviceId as string; + const workspaceId = params.workspaceId as string | undefined; + const workspaceName = params.workspaceName as string | undefined; + + if (!deviceId) { + return { + content: [{ type: "text", text: "Error: deviceId is required" }], + isError: true, + }; + } + + if (!workspaceId && !workspaceName) { + return { + content: [ + { + type: "text", + text: "Error: Either workspaceId or workspaceName must be provided", + }, + ], + isError: true, + }; + } + + return executeOnDevice({ + ctx, + deviceId, + tool: "switch_workspace", + params: { workspaceId, workspaceName }, + }); + }, +); diff --git a/apps/api/src/lib/mcp/tools/index.ts b/apps/api/src/lib/mcp/tools/index.ts new file mode 100644 index 00000000000..e0536069d4f --- /dev/null +++ b/apps/api/src/lib/mcp/tools/index.ts @@ -0,0 +1,42 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { register as registerCreateWorkspace } from "./devices/create-workspace"; +import { register as registerDeleteWorkspace } from "./devices/delete-workspace"; +import { register as registerGetAppContext } from "./devices/get-app-context"; +// Devices +import { register as registerListDevices } from "./devices/list-devices"; +import { register as registerListProjects } from "./devices/list-projects"; +import { register as registerListWorkspaces } from "./devices/list-workspaces"; +import { register as registerNavigateToWorkspace } from "./devices/navigate-to-workspace"; +import { register as registerSwitchWorkspace } from "./devices/switch-workspace"; +// Organizations +import { register as registerListMembers } from "./organizations/list-members"; +// Tasks +import { register as registerCreateTask } from "./tasks/create-task"; +import { register as registerDeleteTask } from "./tasks/delete-task"; +import { register as registerGetTask } from "./tasks/get-task"; +import { register as registerListTaskStatuses } from "./tasks/list-task-statuses"; +import { register as registerListTasks } from "./tasks/list-tasks"; +import { register as registerUpdateTask } from "./tasks/update-task"; + +export function registerTools(server: McpServer) { + // Tasks + registerCreateTask(server); + registerUpdateTask(server); + registerListTasks(server); + registerGetTask(server); + registerDeleteTask(server); + registerListTaskStatuses(server); + + // Organizations + registerListMembers(server); + + // Devices + registerListDevices(server); + registerListWorkspaces(server); + registerListProjects(server); + registerGetAppContext(server); + registerNavigateToWorkspace(server); + registerCreateWorkspace(server); + registerSwitchWorkspace(server); + registerDeleteWorkspace(server); +} diff --git a/apps/api/src/lib/mcp/tools/organizations/list-members/index.ts b/apps/api/src/lib/mcp/tools/organizations/list-members/index.ts new file mode 100644 index 00000000000..e0ba8ee420c --- /dev/null +++ b/apps/api/src/lib/mcp/tools/organizations/list-members/index.ts @@ -0,0 +1 @@ +export { register } from "./list-members"; diff --git a/apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts b/apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts new file mode 100644 index 00000000000..e3179513a33 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts @@ -0,0 +1,68 @@ +import { db } from "@superset/db/client"; +import { members, users } from "@superset/db/schema"; +import { and, eq, ilike, or } from "drizzle-orm"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +export const register = registerTool( + "list_members", + { + description: "List members in the organization", + inputSchema: { + search: z.string().optional().describe("Search by name or email"), + limit: z.number().int().min(1).max(100).default(50), + }, + }, + async (params, ctx) => { + const limit = params.limit as number; + const search = params.search as string | undefined; + const conditions = [eq(members.organizationId, ctx.organizationId)]; + + let query = db + .select({ + id: users.id, + name: users.name, + email: users.email, + image: users.image, + role: members.role, + }) + .from(members) + .innerJoin(users, eq(members.userId, users.id)) + .where(and(...conditions)) + .limit(limit); + + if (search) { + query = db + .select({ + id: users.id, + name: users.name, + email: users.email, + image: users.image, + role: members.role, + }) + .from(members) + .innerJoin(users, eq(members.userId, users.id)) + .where( + and( + ...conditions, + or( + ilike(users.name, `%${search}%`), + ilike(users.email, `%${search}%`), + ), + ), + ) + .limit(limit); + } + + const membersList = await query; + + return { + content: [ + { + type: "text", + text: JSON.stringify({ members: membersList }, null, 2), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/create-task/create-task.ts b/apps/api/src/lib/mcp/tools/tasks/create-task/create-task.ts new file mode 100644 index 00000000000..0a9e501e763 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/create-task/create-task.ts @@ -0,0 +1,163 @@ +import { db, dbWs } from "@superset/db/client"; +import { taskStatuses, tasks } from "@superset/db/schema"; +import { getCurrentTxid } from "@superset/db/utils"; +import { and, eq, ilike } from "drizzle-orm"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +const PRIORITIES = ["urgent", "high", "medium", "low", "none"] as const; +type TaskPriority = (typeof PRIORITIES)[number]; + +function isPriority(value: unknown): value is TaskPriority { + return PRIORITIES.includes(value as TaskPriority); +} + +export const register = registerTool( + "create_task", + { + description: "Create a new task in the organization", + inputSchema: { + title: z.string().min(1).describe("Task title"), + description: z + .string() + .optional() + .describe("Task description (markdown)"), + priority: z + .enum(["urgent", "high", "medium", "low", "none"]) + .default("none") + .describe("Task priority"), + assigneeId: z.string().uuid().optional().describe("User ID to assign to"), + statusId: z + .string() + .uuid() + .optional() + .describe("Status ID (defaults to backlog)"), + labels: z.array(z.string()).optional().describe("Array of label strings"), + dueDate: z + .string() + .datetime() + .optional() + .describe("Due date in ISO format"), + estimate: z + .number() + .int() + .positive() + .optional() + .describe("Estimate in points/hours"), + }, + }, + async (params, ctx) => { + const title = params.title as string; + const description = params.description as string | undefined; + const priorityParam = params.priority; + const priority: TaskPriority = isPriority(priorityParam) + ? priorityParam + : "none"; + const assigneeId = params.assigneeId as string | undefined; + const labels = params.labels as string[] | undefined; + const dueDate = params.dueDate as string | undefined; + const estimate = params.estimate as number | undefined; + + let statusId = params.statusId as string | undefined; + if (!statusId) { + const [defaultStatus] = await db + .select({ id: taskStatuses.id }) + .from(taskStatuses) + .where( + and( + eq(taskStatuses.organizationId, ctx.organizationId), + eq(taskStatuses.type, "backlog"), + ), + ) + .orderBy(taskStatuses.position) + .limit(1); + + statusId = defaultStatus?.id; + if (!statusId) { + return { + content: [{ type: "text", text: "Error: No default status found" }], + isError: true, + }; + } + } + + const baseSlug = title + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") + .slice(0, 50); + + const existingTasks = await db + .select({ slug: tasks.slug }) + .from(tasks) + .where( + and( + eq(tasks.organizationId, ctx.organizationId), + ilike(tasks.slug, `${baseSlug}%`), + ), + ); + + let slug = baseSlug; + if (existingTasks.length > 0) { + const existing = new Set(existingTasks.map((t) => t.slug)); + let counter = 1; + while (existing.has(slug)) slug = `${baseSlug}-${counter++}`; + } + + const result = await dbWs.transaction(async (tx) => { + const [task] = await tx + .insert(tasks) + .values({ + slug, + title, + description: description ?? null, + priority, + statusId, + organizationId: ctx.organizationId, + creatorId: ctx.userId, + assigneeId: assigneeId ?? null, + labels: labels ?? [], + dueDate: dueDate ? new Date(dueDate) : null, + estimate: estimate ?? null, + }) + .returning(); + + const txid = await getCurrentTxid(tx); + return { task, txid }; + }); + + if (!result.task) { + return { + content: [ + { + type: "text", + text: JSON.stringify( + { error: "Failed to create task", txid: result.txid }, + null, + 2, + ), + }, + ], + isError: true, + }; + } + + return { + content: [ + { + type: "text", + text: JSON.stringify( + { + id: result.task.id, + slug: result.task.slug, + title: result.task.title, + txid: result.txid, + }, + null, + 2, + ), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/create-task/index.ts b/apps/api/src/lib/mcp/tools/tasks/create-task/index.ts new file mode 100644 index 00000000000..c1e16d05717 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/create-task/index.ts @@ -0,0 +1 @@ +export { register } from "./create-task"; diff --git a/apps/api/src/lib/mcp/tools/tasks/delete-task/delete-task.ts b/apps/api/src/lib/mcp/tools/tasks/delete-task/delete-task.ts new file mode 100644 index 00000000000..e76668faed1 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/delete-task/delete-task.ts @@ -0,0 +1,70 @@ +import { db, dbWs } from "@superset/db/client"; +import { tasks } from "@superset/db/schema"; +import { getCurrentTxid } from "@superset/db/utils"; +import { and, eq, isNull } from "drizzle-orm"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +export const register = registerTool( + "delete_task", + { + description: "Soft delete a task", + inputSchema: { + taskId: z.string().describe("Task ID (uuid) or slug"), + }, + }, + async (params, ctx) => { + const taskId = params.taskId as string; + const isUuid = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + taskId, + ); + + const [existingTask] = await db + .select() + .from(tasks) + .where( + and( + isUuid ? eq(tasks.id, taskId) : eq(tasks.slug, taskId), + eq(tasks.organizationId, ctx.organizationId), + isNull(tasks.deletedAt), + ), + ) + .limit(1); + + if (!existingTask) { + return { + content: [{ type: "text", text: "Error: Task not found" }], + isError: true, + }; + } + + const deletedAt = new Date(); + const result = await dbWs.transaction(async (tx) => { + await tx + .update(tasks) + .set({ deletedAt }) + .where(eq(tasks.id, existingTask.id)); + + const txid = await getCurrentTxid(tx); + return { txid }; + }); + + return { + content: [ + { + type: "text", + text: JSON.stringify( + { + success: true, + deletedAt: deletedAt.toISOString(), + txid: result.txid, + }, + null, + 2, + ), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/delete-task/index.ts b/apps/api/src/lib/mcp/tools/tasks/delete-task/index.ts new file mode 100644 index 00000000000..2c8e677e9eb --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/delete-task/index.ts @@ -0,0 +1 @@ +export { register } from "./delete-task"; diff --git a/apps/api/src/lib/mcp/tools/tasks/get-task/get-task.ts b/apps/api/src/lib/mcp/tools/tasks/get-task/get-task.ts new file mode 100644 index 00000000000..e210432114b --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/get-task/get-task.ts @@ -0,0 +1,75 @@ +import { db } from "@superset/db/client"; +import { taskStatuses, tasks, users } from "@superset/db/schema"; +import { and, eq, isNull } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +export const register = registerTool( + "get_task", + { + description: "Get a single task by ID or slug", + inputSchema: { + taskId: z.string().describe("Task ID (uuid) or slug"), + }, + }, + async (params, ctx) => { + const taskId = params.taskId as string; + const isUuid = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + taskId, + ); + + const assignee = alias(users, "assignee"); + const creator = alias(users, "creator"); + const status = alias(taskStatuses, "status"); + + const [task] = await db + .select({ + id: tasks.id, + slug: tasks.slug, + title: tasks.title, + description: tasks.description, + priority: tasks.priority, + statusId: tasks.statusId, + statusName: status.name, + statusType: status.type, + statusColor: status.color, + assigneeId: tasks.assigneeId, + assigneeName: assignee.name, + assigneeEmail: assignee.email, + creatorId: tasks.creatorId, + creatorName: creator.name, + labels: tasks.labels, + dueDate: tasks.dueDate, + estimate: tasks.estimate, + branch: tasks.branch, + prUrl: tasks.prUrl, + createdAt: tasks.createdAt, + updatedAt: tasks.updatedAt, + }) + .from(tasks) + .leftJoin(assignee, eq(tasks.assigneeId, assignee.id)) + .leftJoin(creator, eq(tasks.creatorId, creator.id)) + .leftJoin(status, eq(tasks.statusId, status.id)) + .where( + and( + isUuid ? eq(tasks.id, taskId) : eq(tasks.slug, taskId), + eq(tasks.organizationId, ctx.organizationId), + isNull(tasks.deletedAt), + ), + ) + .limit(1); + + if (!task) { + return { + content: [{ type: "text", text: "Error: Task not found" }], + isError: true, + }; + } + + return { + content: [{ type: "text", text: JSON.stringify(task, null, 2) }], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/get-task/index.ts b/apps/api/src/lib/mcp/tools/tasks/get-task/index.ts new file mode 100644 index 00000000000..b15e7a43fbb --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/get-task/index.ts @@ -0,0 +1 @@ +export { register } from "./get-task"; diff --git a/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/index.ts b/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/index.ts new file mode 100644 index 00000000000..01cc2e1f0c7 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/index.ts @@ -0,0 +1 @@ +export { register } from "./list-task-statuses"; diff --git a/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/list-task-statuses.ts b/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/list-task-statuses.ts new file mode 100644 index 00000000000..7b048fe559c --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/list-task-statuses/list-task-statuses.ts @@ -0,0 +1,29 @@ +import { db } from "@superset/db/client"; +import { taskStatuses } from "@superset/db/schema"; +import { eq } from "drizzle-orm"; +import { registerTool } from "../../utils"; + +export const register = registerTool( + "list_task_statuses", + { + description: "List available task statuses for the organization", + inputSchema: {}, + }, + async (_params, ctx) => { + const statuses = await db + .select({ + id: taskStatuses.id, + name: taskStatuses.name, + color: taskStatuses.color, + type: taskStatuses.type, + position: taskStatuses.position, + }) + .from(taskStatuses) + .where(eq(taskStatuses.organizationId, ctx.organizationId)) + .orderBy(taskStatuses.position); + + return { + content: [{ type: "text", text: JSON.stringify({ statuses }, null, 2) }], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/list-tasks/index.ts b/apps/api/src/lib/mcp/tools/tasks/list-tasks/index.ts new file mode 100644 index 00000000000..c8d14b96620 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/list-tasks/index.ts @@ -0,0 +1 @@ +export { register } from "./list-tasks"; diff --git a/apps/api/src/lib/mcp/tools/tasks/list-tasks/list-tasks.ts b/apps/api/src/lib/mcp/tools/tasks/list-tasks/list-tasks.ts new file mode 100644 index 00000000000..61ce92d13bd --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/list-tasks/list-tasks.ts @@ -0,0 +1,162 @@ +import { db } from "@superset/db/client"; +import { taskStatuses, tasks, users } from "@superset/db/schema"; +import type { SQL } from "drizzle-orm"; +import { and, desc, eq, ilike, isNull, or } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +type TaskStatusType = + | "backlog" + | "unstarted" + | "started" + | "completed" + | "canceled"; + +const PRIORITIES = ["urgent", "high", "medium", "low", "none"] as const; +type TaskPriority = (typeof PRIORITIES)[number]; + +function isPriority(value: unknown): value is TaskPriority { + return PRIORITIES.includes(value as TaskPriority); +} + +export const register = registerTool( + "list_tasks", + { + description: "List tasks with optional filters", + inputSchema: { + statusId: z.string().uuid().optional().describe("Filter by status ID"), + statusType: z + .enum(["backlog", "unstarted", "started", "completed", "canceled"]) + .optional() + .describe("Filter by status type"), + assigneeId: z.string().uuid().optional().describe("Filter by assignee"), + assignedToMe: z + .boolean() + .optional() + .describe("Filter to tasks assigned to current user"), + priority: z.enum(["urgent", "high", "medium", "low", "none"]).optional(), + search: z.string().optional().describe("Search in title/description"), + limit: z.number().int().min(1).max(100).default(50), + offset: z.number().int().min(0).default(0), + }, + }, + async (params, ctx) => { + const statusId = params.statusId as string | undefined; + const statusType = params.statusType as TaskStatusType | undefined; + const assigneeId = params.assigneeId as string | undefined; + const assignedToMe = params.assignedToMe as boolean | undefined; + const priority = params.priority; + const search = params.search as string | undefined; + const limit = params.limit as number; + const offset = params.offset as number; + + const assignee = alias(users, "assignee"); + const status = alias(taskStatuses, "status"); + + const conditions: SQL[] = [ + eq(tasks.organizationId, ctx.organizationId), + isNull(tasks.deletedAt), + ]; + + if (statusId) { + conditions.push(eq(tasks.statusId, statusId)); + } + + if (assigneeId) { + conditions.push(eq(tasks.assigneeId, assigneeId)); + } else if (assignedToMe) { + conditions.push(eq(tasks.assigneeId, ctx.userId)); + } + + if (isPriority(priority)) { + conditions.push(eq(tasks.priority, priority)); + } + + if (search) { + const searchCondition = or( + ilike(tasks.title, `%${search}%`), + ilike(tasks.description, `%${search}%`), + ); + if (searchCondition) { + conditions.push(searchCondition); + } + } + + if (statusType) { + const statusesOfType = await db + .select({ id: taskStatuses.id }) + .from(taskStatuses) + .where( + and( + eq(taskStatuses.organizationId, ctx.organizationId), + eq(taskStatuses.type, statusType), + ), + ); + const statusIds = statusesOfType.map((s) => s.id); + if (statusIds.length > 0) { + const statusCondition = or( + ...statusIds.map((id) => eq(tasks.statusId, id)), + ); + if (statusCondition) { + conditions.push(statusCondition); + } + } else { + return { + content: [ + { + type: "text", + text: JSON.stringify( + { tasks: [], count: 0, hasMore: false }, + null, + 2, + ), + }, + ], + }; + } + } + + const tasksList = await db + .select({ + id: tasks.id, + slug: tasks.slug, + title: tasks.title, + description: tasks.description, + priority: tasks.priority, + statusId: tasks.statusId, + statusName: status.name, + statusType: status.type, + assigneeId: tasks.assigneeId, + assigneeName: assignee.name, + labels: tasks.labels, + dueDate: tasks.dueDate, + estimate: tasks.estimate, + createdAt: tasks.createdAt, + }) + .from(tasks) + .leftJoin(assignee, eq(tasks.assigneeId, assignee.id)) + .leftJoin(status, eq(tasks.statusId, status.id)) + .where(and(...conditions)) + .orderBy(desc(tasks.createdAt)) + .limit(limit) + .offset(offset); + + return { + content: [ + { + type: "text", + text: JSON.stringify( + { + tasks: tasksList, + count: tasksList.length, + hasMore: tasksList.length === limit, + }, + null, + 2, + ), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/tasks/update-task/index.ts b/apps/api/src/lib/mcp/tools/tasks/update-task/index.ts new file mode 100644 index 00000000000..34209aab857 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/update-task/index.ts @@ -0,0 +1 @@ +export { register } from "./update-task"; diff --git a/apps/api/src/lib/mcp/tools/tasks/update-task/update-task.ts b/apps/api/src/lib/mcp/tools/tasks/update-task/update-task.ts new file mode 100644 index 00000000000..b80960db32a --- /dev/null +++ b/apps/api/src/lib/mcp/tools/tasks/update-task/update-task.ts @@ -0,0 +1,113 @@ +import { db, dbWs } from "@superset/db/client"; +import { tasks } from "@superset/db/schema"; +import { getCurrentTxid } from "@superset/db/utils"; +import { and, eq, isNull } from "drizzle-orm"; +import { z } from "zod"; +import { registerTool } from "../../utils"; + +export const register = registerTool( + "update_task", + { + description: "Update an existing task", + inputSchema: { + taskId: z.string().describe("Task ID (uuid) or slug"), + title: z.string().min(1).optional().describe("New title"), + description: z.string().optional().describe("New description"), + priority: z.enum(["urgent", "high", "medium", "low", "none"]).optional(), + assigneeId: z + .string() + .uuid() + .nullable() + .optional() + .describe("New assignee (null to unassign)"), + statusId: z.string().uuid().optional().describe("New status ID"), + labels: z.array(z.string()).optional().describe("Replace labels"), + dueDate: z + .string() + .datetime() + .nullable() + .optional() + .describe("New due date (null to clear)"), + estimate: z.number().int().positive().nullable().optional(), + }, + }, + async (params, ctx) => { + const taskId = params.taskId as string; + const isUuid = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + taskId, + ); + + const [existingTask] = await db + .select() + .from(tasks) + .where( + and( + isUuid ? eq(tasks.id, taskId) : eq(tasks.slug, taskId), + eq(tasks.organizationId, ctx.organizationId), + isNull(tasks.deletedAt), + ), + ) + .limit(1); + + if (!existingTask) { + return { + content: [{ type: "text", text: "Error: Task not found" }], + isError: true, + }; + } + + const updateData: Record = {}; + if (params.title !== undefined) updateData.title = params.title; + if (params.description !== undefined) + updateData.description = params.description; + if (params.priority !== undefined) updateData.priority = params.priority; + if (params.assigneeId !== undefined) + updateData.assigneeId = params.assigneeId; + if (params.statusId !== undefined) updateData.statusId = params.statusId; + if (params.labels !== undefined) updateData.labels = params.labels; + if (params.dueDate !== undefined) + updateData.dueDate = params.dueDate + ? new Date(params.dueDate as string) + : null; + if (params.estimate !== undefined) updateData.estimate = params.estimate; + + if (Object.keys(updateData).length === 0) { + return { + content: [ + { type: "text", text: "Error: No updatable fields provided" }, + ], + isError: true, + }; + } + + const result = await dbWs.transaction(async (tx) => { + const [task] = await tx + .update(tasks) + .set(updateData) + .where(eq(tasks.id, existingTask.id)) + .returning(); + + const txid = await getCurrentTxid(tx); + return { task, txid }; + }); + + return { + content: [ + { + type: "text", + text: JSON.stringify( + { + id: result.task?.id, + slug: result.task?.slug, + title: result.task?.title, + txid: result.txid, + }, + null, + 2, + ), + }, + ], + }; + }, +); diff --git a/apps/api/src/lib/mcp/tools/utils/execute-on-device.ts b/apps/api/src/lib/mcp/tools/utils/execute-on-device.ts new file mode 100644 index 00000000000..227346b074e --- /dev/null +++ b/apps/api/src/lib/mcp/tools/utils/execute-on-device.ts @@ -0,0 +1,126 @@ +import { db } from "@superset/db/client"; +import { agentCommands, devicePresence } from "@superset/db/schema"; +import { and, eq, gt, inArray } from "drizzle-orm"; +import type { McpContext } from "../../auth"; + +export const DEVICE_ONLINE_THRESHOLD_MS = 60_000; +const POLL_INTERVAL_MS = 500; +const DEFAULT_TIMEOUT_MS = 30_000; + +export async function executeOnDevice({ + ctx, + deviceId, + tool, + params, + timeout = DEFAULT_TIMEOUT_MS, +}: { + ctx: McpContext; + deviceId: string; + tool: string; + params: Record; + timeout?: number; +}) { + const threshold = new Date(Date.now() - DEVICE_ONLINE_THRESHOLD_MS); + + const [device] = await db + .select() + .from(devicePresence) + .where( + and( + eq(devicePresence.deviceId, deviceId), + eq(devicePresence.organizationId, ctx.organizationId), + gt(devicePresence.lastSeenAt, threshold), + ), + ) + .limit(1); + + if (!device) { + return { + content: [ + { + type: "text" as const, + text: `Error: Device ${deviceId} is not online`, + }, + ], + isError: true, + }; + } + + const [cmd] = await db + .insert(agentCommands) + .values({ + userId: ctx.userId, + organizationId: ctx.organizationId, + targetDeviceId: deviceId, + targetDeviceType: device.deviceType, + tool, + params, + status: "pending", + timeoutAt: new Date(Date.now() + timeout), + }) + .returning(); + + if (!cmd) { + return { + content: [ + { type: "text" as const, text: "Error: Failed to create command" }, + ], + isError: true, + }; + } + + const startTime = Date.now(); + while (Date.now() - startTime < timeout) { + const [updated] = await db + .select() + .from(agentCommands) + .where(eq(agentCommands.id, cmd.id)) + .limit(1); + + if (updated?.status === "completed") { + return { + content: [ + { + type: "text" as const, + text: JSON.stringify(updated.result ?? { success: true }, null, 2), + }, + ], + }; + } + + if (updated?.status === "failed") { + return { + content: [ + { + type: "text" as const, + text: `Error: ${updated.error ?? "Command failed"}`, + }, + ], + isError: true, + }; + } + + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); + } + + // Only update to timeout if still in a non-final state (avoid race condition) + await db + .update(agentCommands) + .set({ status: "timeout" }) + .where( + and( + eq(agentCommands.id, cmd.id), + inArray(agentCommands.status, ["pending", "claimed", "executing"]), + ), + ); + + return { + content: [ + { + type: "text" as const, + text: `Error: Command timed out after ${timeout}ms`, + }, + ], + isError: true, + }; +} diff --git a/apps/api/src/lib/mcp/tools/utils/index.ts b/apps/api/src/lib/mcp/tools/utils/index.ts new file mode 100644 index 00000000000..203be954c35 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/utils/index.ts @@ -0,0 +1,5 @@ +export { + DEVICE_ONLINE_THRESHOLD_MS, + executeOnDevice, +} from "./execute-on-device"; +export { registerTool } from "./register-tool"; diff --git a/apps/api/src/lib/mcp/tools/utils/register-tool.ts b/apps/api/src/lib/mcp/tools/utils/register-tool.ts new file mode 100644 index 00000000000..2bbcd997383 --- /dev/null +++ b/apps/api/src/lib/mcp/tools/utils/register-tool.ts @@ -0,0 +1,43 @@ +import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; +import type { + ServerNotification, + ServerRequest, +} from "@modelcontextprotocol/sdk/types.js"; +import type { McpContext } from "../../auth"; + +type ToolResult = { + content: Array<{ type: "text"; text: string }>; + isError?: boolean; +}; + +type ToolExtra = RequestHandlerExtra & { + authInfo?: AuthInfo & { extra?: { mcpContext?: McpContext } }; +}; + +type InputSchema = Record; + +export function registerTool( + name: string, + config: { description: string; inputSchema: InputSchema }, + handler: ( + params: Record, + ctx: McpContext, + ) => Promise, +) { + return (server: McpServer) => { + server.tool( + name, + config.description, + config.inputSchema, + async (params: Record, extra: ToolExtra) => { + const ctx = extra.authInfo?.extra?.mcpContext; + if (!ctx) { + throw new Error("No MCP context available - authentication required"); + } + return handler(params, ctx); + }, + ); + }; +} diff --git a/apps/web/src/app/oauth/consent/components/ConsentForm/ConsentForm.tsx b/apps/web/src/app/oauth/consent/components/ConsentForm/ConsentForm.tsx index 1b6c9093432..3e0b8967a9c 100644 --- a/apps/web/src/app/oauth/consent/components/ConsentForm/ConsentForm.tsx +++ b/apps/web/src/app/oauth/consent/components/ConsentForm/ConsentForm.tsx @@ -76,12 +76,28 @@ export function ConsentForm({ setError(null); try { - const finalScopes = [...scopes]; - if ( - selectedOrgId && - !finalScopes.some((s) => s.startsWith("organization:")) - ) { - finalScopes.push(`organization:${selectedOrgId}`); + // Add organization scope to verification value before consent + // (Better Auth's consent endpoint doesn't accept scope in body) + if (accept && selectedOrgId) { + const addScopeResponse = await fetch( + `${process.env.NEXT_PUBLIC_API_URL}/api/auth/oauth/add-org-scope`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + credentials: "include", + body: JSON.stringify({ + consent_code: consentCode, + organizationId: selectedOrgId, + }), + }, + ); + + if (!addScopeResponse.ok) { + const data = await addScopeResponse.json(); + throw new Error(data.error || "Failed to set organization scope"); + } } const response = await fetch( @@ -95,7 +111,6 @@ export function ConsentForm({ body: JSON.stringify({ accept, consent_code: consentCode, - scope: finalScopes.join(" "), }), }, ); diff --git a/bun.lock b/bun.lock index 9b8fb291d96..80bd9dd363d 100644 --- a/bun.lock +++ b/bun.lock @@ -73,13 +73,13 @@ "@trpc/server": "^11.7.1", "@upstash/qstash": "^2.8.4", "@vercel/blob": "^2.0.0", - "@vercel/mcp-adapter": "^1.0.0", "better-auth": "1.4.17", "date-fns": "^4.1.0", "drizzle-orm": "0.45.1", "import-in-the-middle": "2.0.1", "jose": "^6.1.3", "lodash.chunk": "^4.2.0", + "mcp-handler": "^1.0.7", "next": "^16.0.10", "react": "19.1.0", "react-dom": "19.1.0", @@ -2100,8 +2100,6 @@ "@vercel/kv": ["@vercel/kv@3.0.0", "", { "dependencies": { "@upstash/redis": "^1.34.0" } }, "sha512-pKT8fRnfyYk2MgvyB6fn6ipJPCdfZwiKDdw7vB+HL50rjboEBHDVBEcnwfkEpVSp2AjNtoaOUH7zG+bVC/rvSg=="], - "@vercel/mcp-adapter": ["@vercel/mcp-adapter@1.0.0", "", { "dependencies": { "mcp-handler": "^1.0.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.12.0", "next": ">=13.0.0" }, "optionalPeers": ["next"], "bin": { "mcp-adapter": "dist/cli/index.js", "create-mcp-route": "dist/cli/index.js" } }, "sha512-o/QA4LhYCJvuL7/i8CfKPpOm29u25/L4m1LWH44EQZ8cfYJlc4B7Bu+YzDHl23m8A3hDxCJQmlgZEGmsPAQ0vQ=="], - "@vercel/oidc": ["@vercel/oidc@3.1.0", "", {}, "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w=="], "@vitejs/plugin-react": ["@vitejs/plugin-react@5.1.2", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.53", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-EcA07pHJouywpzsoTUqNh5NwGayl2PPVEJKUSinGGSxFGYn+shYbqMGBg6FXDqgXum9Ou/ecb+411ssw8HImJQ=="], diff --git a/packages/auth/src/lib/oauth-org-scope-endpoint.ts b/packages/auth/src/lib/oauth-org-scope-endpoint.ts new file mode 100644 index 00000000000..67ec3978163 --- /dev/null +++ b/packages/auth/src/lib/oauth-org-scope-endpoint.ts @@ -0,0 +1,102 @@ +import { db } from "@superset/db/client"; +import { members, verifications } from "@superset/db/schema/auth"; +import type { BetterAuthPlugin } from "better-auth"; +import { createAuthEndpoint, sessionMiddleware } from "better-auth/api"; +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; + +/** + * Custom endpoint to add organization scope to OAuth consent flow. + * + * Better Auth's consent endpoint doesn't accept scope in the body, + * so we update the verification value directly before consent is processed. + */ +export const oauthOrgScopeEndpoint = { + id: "oauth-org-scope", + endpoints: { + addOrgScope: createAuthEndpoint( + "/oauth/add-org-scope", + { + method: "POST", + body: z.object({ + consent_code: z.string(), + organizationId: z.string().uuid(), + }), + use: [sessionMiddleware], + }, + async (ctx) => { + const { consent_code, organizationId } = ctx.body; + const userId = ctx.context.session.user.id; + + // Verify user is a member of the organization + const membership = await db.query.members.findFirst({ + where: and( + eq(members.userId, userId), + eq(members.organizationId, organizationId), + ), + }); + + if (!membership) { + return ctx.json( + { error: "User is not a member of this organization" }, + { status: 403 }, + ); + } + + // Find the verification value for this consent code + const verification = await db.query.verifications.findFirst({ + where: eq(verifications.identifier, consent_code), + }); + + if (!verification) { + return ctx.json({ error: "Invalid consent code" }, { status: 400 }); + } + + if (new Date() > new Date(verification.expiresAt)) { + return ctx.json({ error: "Consent code expired" }, { status: 400 }); + } + + // Parse the stored value and add organization scope + let value: { scope?: string | string[]; [key: string]: unknown }; + try { + value = JSON.parse(verification.value); + } catch { + console.error( + "[oauth-org-scope] Failed to parse verification value:", + verification.value, + ); + return ctx.json( + { error: "Invalid verification data" }, + { status: 400 }, + ); + } + const orgScope = `organization:${organizationId}`; + + // Ensure scope is an array + const currentScopes = Array.isArray(value.scope) + ? value.scope + : typeof value.scope === "string" + ? value.scope.split(" ") + : []; + + // Add org scope if not already present + if (!currentScopes.some((s: string) => s.startsWith("organization:"))) { + currentScopes.push(orgScope); + } + + // Update the verification value with the new scopes + await db + .update(verifications) + .set({ + value: JSON.stringify({ + ...value, + scope: currentScopes, + }), + }) + .where(eq(verifications.id, verification.id)); + + return ctx.json({ success: true }); + }, + ), + }, +} satisfies BetterAuthPlugin; diff --git a/packages/auth/src/server.ts b/packages/auth/src/server.ts index 3624a602eb1..6c562119a2d 100644 --- a/packages/auth/src/server.ts +++ b/packages/auth/src/server.ts @@ -27,6 +27,7 @@ import Stripe from "stripe"; import { env } from "./env"; import { acceptInvitationEndpoint } from "./lib/accept-invitation-endpoint"; import { generateMagicTokenForInvite } from "./lib/generate-magic-token"; +import { oauthOrgScopeEndpoint } from "./lib/oauth-org-scope-endpoint"; import { invitationRateLimit } from "./lib/rate-limit"; import { resend } from "./lib/resend"; import { formatPrice, getOrganizationOwners } from "./utils"; @@ -603,6 +604,7 @@ export const auth = betterAuth({ }, }), acceptInvitationEndpoint, + oauthOrgScopeEndpoint, ], });