⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(mcp): implement Model Context Protocol server with HTTP and stdio support
Andreje402fe16928e
diff --git a/apps/api/package.json b/apps/api/package.jsonindex eef97e40a..bdf02e67a 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -14,7 +14,7 @@},"scripts": {"dev": "tsx watch src/index.ts",- "build": "esbuild src/index.ts --bundle --platform=node --outdir=dist --format=esm --packages=external --external:fs --external:path --external:crypto --external:os --external:util --external:stream --external:buffer --external:events --external:url --external:querystring --external:http --external:https --external:net --external:tls --external:zlib",+ "build": "esbuild src/index.ts --bundle --platform=node --outdir=dist --format=esm --packages=external --external:fs --external:path --external:crypto --external:os --external:util --external:stream --external:buffer --external:events --external:url --external:querystring --external:http --external:https --external:net --external:tls --external:zlib --external:@modelcontextprotocol/sdk","lint": "biome check --write .","test": "npm run test:unit","test:coverage": "vitest run --config vitest.config.ts --coverage",@@ -34,6 +34,7 @@"@hono/node-server": "^1.19.11","@hono/standard-validator": "^0.2.2","@kaneo/email": "workspace:*",+ "@modelcontextprotocol/sdk": "^1.26.0","@octokit/webhooks": "^14.2.0","@oslojs/crypto": "^1.0.1","@oslojs/encoding": "^1.1.0",diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 571fc9320..042581d74 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -29,6 +29,7 @@ import githubIntegration, {} from "./github-integration";import invitation from "./invitation";import label from "./label";+import mcpRoutes, { mcpWellKnownRoutes } from "./mcp";import { migrateColumns } from "./migrations/column-migration";import notification from "./notification";import notificationPreferences from "./notification-preferences";@@ -421,6 +422,8 @@ export function createApp() {return auth.handler(c.req.raw);});+ api.route("/", mcpRoutes);+api.use("*", async (c, next) => {try {await authenticateApiRequest(c);@@ -471,6 +474,11 @@ export function createApp() {const invitationApi = api.route("/invitation", invitation);const workspaceApi = api.route("/workspace", workspace);+ app.route(+ "/",+ mcpWellKnownRoutes(process.env.KANEO_API_URL || "http://localhost:1337"),+ );+app.route("/api", api);return {diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.tsnew file mode 100644index 000000000..55d6dc5ef--- /dev/null+++ b/apps/api/src/mcp/index.ts@@ -0,0 +1,217 @@+import { randomUUID } from "node:crypto";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";+import { Hono } from "hono";+import { auth } from "../auth";+import {+ createAuthCode,+ exchangeCode,+ getClient,+ registerClient,+} from "./oauth";+import { registerMcpTools } from "./tools";++const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";+const apiUrl = process.env.KANEO_API_URL || "http://localhost:1337";++const sessions = new Map<string, WebStandardStreamableHTTPServerTransport>();++function createMcpServerForUser(token: string): McpServer {+ const server = new McpServer({+ name: "kaneo-mcp",+ version: "1.0.0",+ });+ registerMcpTools(server, apiUrl, token);+ return server;+}++async function validateBearerToken(+ req: Request,+): Promise<{ userId: string; token: string } | null> {+ const authHeader = req.headers.get("authorization");+ if (!authHeader) return null;+ const match = authHeader.match(/^Bearer\s+(\S+)$/i);+ if (!match?.[1]) return null;+ const token = match[1];++ const headers = new Headers();+ headers.set("authorization", `Bearer ${token}`);+ const session = await auth.api.getSession({ headers });++ if (!session?.user?.id) return null;+ return { userId: session.user.id, token };+}++const mcp = new Hono();++mcp.post("/mcp/register", async (c) => {+ const body = await c.req.json();+ const client = registerClient({+ redirectUris: body.redirect_uris ?? [],+ clientName: body.client_name,+ });+ return c.json({+ client_id: client.clientId,+ client_id_issued_at: client.issuedAt,+ redirect_uris: client.redirectUris,+ client_name: client.clientName,+ token_endpoint_auth_method: body.token_endpoint_auth_method ?? "none",+ grant_types: body.grant_types ?? ["authorization_code"],+ response_types: body.response_types ?? ["code"],+ });+});++mcp.get("/mcp/authorize", async (c) => {+ const clientId = c.req.query("client_id");+ const redirectUri = c.req.query("redirect_uri");+ const codeChallenge = c.req.query("code_challenge");+ const state = c.req.query("state");++ if (!clientId || !redirectUri || !codeChallenge) {+ return c.json({ error: "invalid_request" }, 400);+ }++ const client = getClient(clientId);+ if (!client) {+ return c.json({ error: "invalid_client" }, 400);+ }+ if (+ client.redirectUris.length > 0 &&+ !client.redirectUris.includes(redirectUri)+ ) {+ return c.json({ error: "invalid_redirect_uri" }, 400);+ }++ const session = await auth.api.getSession({+ headers: c.req.raw.headers,+ });++ if (session?.user?.id) {+ const code = createAuthCode({+ clientId,+ userId: session.user.id,+ codeChallenge,+ redirectUri,+ });+ const url = new URL(redirectUri);+ url.searchParams.set("code", code);+ if (state) url.searchParams.set("state", state);+ return c.redirect(url.toString());+ }++ const returnUrl = c.req.url;+ const loginUrl = `${clientUrl}/auth/sign-in?redirect=${encodeURIComponent(returnUrl)}`;+ return c.redirect(loginUrl);+});++mcp.post("/mcp/token", async (c) => {+ const contentType = c.req.header("content-type") || "";+ let params: Record<string, string>;++ if (contentType.includes("application/x-www-form-urlencoded")) {+ const body = await c.req.text();+ params = Object.fromEntries(new URLSearchParams(body));+ } else {+ params = await c.req.json();+ }++ const { grant_type, code, client_id, code_verifier, redirect_uri } = params;++ if (grant_type !== "authorization_code") {+ return c.json({ error: "unsupported_grant_type" }, 400);+ }+ if (!code || !client_id || !code_verifier || !redirect_uri) {+ return c.json({ error: "invalid_request" }, 400);+ }++ const result = await exchangeCode(+ code,+ client_id,+ code_verifier,+ redirect_uri,+ );+ if (!result) {+ return c.json({ error: "invalid_grant" }, 400);+ }++ return c.json({+ access_token: result.accessToken,+ token_type: "bearer",+ expires_in: result.expiresIn,+ });+});++mcp.all("/mcp", async (c) => {+ const authResult = await validateBearerToken(c.req.raw);+ if (!authResult) {+ return c.json(+ {+ error: "invalid_token",+ error_description: "Missing or invalid token",+ },+ 401,+ );+ }++ const sessionId = c.req.header("mcp-session-id");++ if (sessionId) {+ const existing = sessions.get(sessionId);+ if (existing) {+ return existing.handleRequest(c.req.raw);+ }+ return c.json({ error: "Session not found" }, 404);+ }++ if (c.req.method !== "POST") {+ return c.json({ error: "Method not allowed" }, 405);+ }++ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: () => randomUUID(),+ });++ transport.onclose = () => {+ if (transport.sessionId) {+ sessions.delete(transport.sessionId);+ }+ };++ const server = createMcpServerForUser(authResult.token);+ await server.connect(transport);+ const response = await transport.handleRequest(c.req.raw);++ if (transport.sessionId) {+ sessions.set(transport.sessionId, transport);+ }++ return response;+});++export default mcp;++export function mcpWellKnownRoutes(baseUrl: string) {+ const wellKnown = new Hono();++ wellKnown.get("/.well-known/oauth-protected-resource/api/mcp", (c) =>+ c.json({+ resource: `${baseUrl}/api/mcp`,+ authorization_servers: [`${baseUrl}/api`],+ }),+ );++ wellKnown.get("/.well-known/oauth-authorization-server/api", (c) =>+ c.json({+ issuer: `${baseUrl}/api`,+ authorization_endpoint: `${baseUrl}/api/mcp/authorize`,+ token_endpoint: `${baseUrl}/api/mcp/token`,+ registration_endpoint: `${baseUrl}/api/mcp/register`,+ response_types_supported: ["code"],+ grant_types_supported: ["authorization_code"],+ code_challenge_methods_supported: ["S256"],+ token_endpoint_auth_methods_supported: ["none"],+ }),+ );++ return wellKnown;+}diff --git a/apps/api/src/mcp/oauth.ts b/apps/api/src/mcp/oauth.tsnew file mode 100644index 000000000..6277e4456--- /dev/null+++ b/apps/api/src/mcp/oauth.ts@@ -0,0 +1,94 @@+import { createHash, randomUUID } from "node:crypto";+import { createId } from "@paralleldrive/cuid2";+import db from "../database";+import { sessionTable } from "../database/schema";++type RegisteredClient = {+ clientId: string;+ redirectUris: string[];+ clientName?: string;+ issuedAt: number;+};++type AuthCode = {+ clientId: string;+ userId: string;+ codeChallenge: string;+ redirectUri: string;+ expiresAt: number;+};++const clients = new Map<string, RegisteredClient>();+const codes = new Map<string, AuthCode>();++export function getClient(clientId: string): RegisteredClient | undefined {+ return clients.get(clientId);+}++export function registerClient(params: {+ redirectUris: string[];+ clientName?: string;+}): RegisteredClient {+ const clientId = randomUUID();+ const client: RegisteredClient = {+ clientId,+ redirectUris: params.redirectUris,+ clientName: params.clientName,+ issuedAt: Math.floor(Date.now() / 1000),+ };+ clients.set(clientId, client);+ return client;+}++export function createAuthCode(params: {+ clientId: string;+ userId: string;+ codeChallenge: string;+ redirectUri: string;+}): string {+ const code = randomUUID();+ codes.set(code, {+ ...params,+ expiresAt: Date.now() + 5 * 60 * 1000,+ });+ return code;+}++function base64url(buf: Buffer): string {+ return buf.toString("base64url");+}++function verifyPkce(codeVerifier: string, codeChallenge: string): boolean {+ const hash = createHash("sha256").update(codeVerifier).digest();+ return base64url(hash) === codeChallenge;+}++export async function exchangeCode(+ code: string,+ clientId: string,+ codeVerifier: string,+ redirectUri: string,+): Promise<{ accessToken: string; expiresIn: number } | null> {+ const stored = codes.get(code);+ if (!stored) return null;+ codes.delete(code);++ if (stored.clientId !== clientId) return null;+ if (stored.redirectUri !== redirectUri) return null;+ if (stored.expiresAt < Date.now()) return null;+ if (!verifyPkce(codeVerifier, stored.codeChallenge)) return null;++ const sessionToken = randomUUID();+ const expiresIn = 30 * 24 * 60 * 60;++ await db.insert(sessionTable).values({+ id: createId(),+ token: sessionToken,+ userId: stored.userId,+ expiresAt: new Date(Date.now() + expiresIn * 1000),+ createdAt: new Date(),+ updatedAt: new Date(),+ });++ return { accessToken: sessionToken, expiresIn };+}diff --git a/apps/api/src/mcp/tools.ts b/apps/api/src/mcp/tools.tsnew file mode 100644index 000000000..1dddad356--- /dev/null+++ b/apps/api/src/mcp/tools.ts@@ -0,0 +1,582 @@+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";+import { z } from "zod";++class ApiClient {+ constructor(+ private baseUrl: string,+ private token: string,+ ) {}++ async json<T = unknown>(path: string, init?: RequestInit): Promise<T> {+ const headers = new Headers(init?.headers);+ headers.set("Authorization", `Bearer ${this.token}`);+ if (init?.body != null && !headers.has("Content-Type")) {+ headers.set("Content-Type", "application/json");+ }++ const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;+ const res = await fetch(url, {+ ...init,+ headers,+ signal: AbortSignal.timeout(10_000),+ });++ const text = await res.text();+ let body: unknown = null;+ if (text) {+ try {+ body = JSON.parse(text);+ } catch {+ body = text;+ }+ }+ if (!res.ok) {+ const detail =+ typeof body === "object" && body !== null && "message" in body+ ? (body as { message: string }).message+ : typeof body === "string" && body.length > 0+ ? body.slice(0, 500)+ : `HTTP ${res.status}`;+ throw new Error(`${path}: ${detail}`);+ }+ return body as T;+ }+}++function textResult(data: unknown, isError = false): CallToolResult {+ const text =+ typeof data === "string" ? data : (JSON.stringify(data, null, 2) ?? "");+ return { content: [{ type: "text", text }], isError };+}++function errorResult(message: string): CallToolResult {+ return textResult({ error: message }, true);+}++function run(fn: () => Promise<unknown>): Promise<CallToolResult> {+ return fn()+ .then((data) => textResult(data))+ .catch((e: unknown) =>+ errorResult(e instanceof Error ? e.message : String(e)),+ );+}++const PRIORITIES = ["no-priority", "low", "medium", "high", "urgent"] as const;++function isTaskPriority(v: string): v is (typeof PRIORITIES)[number] {+ return (PRIORITIES as readonly string[]).includes(v);+}++function formatOptionalIso(value: unknown): string | undefined {+ if (value === null || value === undefined) return undefined;+ if (value instanceof Date) return value.toISOString();+ if (typeof value === "string") return value;+ return undefined;+}++function buildFullTaskUpdateBody(+ existing: Record<string, unknown>,+ patch: Record<string, unknown>,+): Record<string, string | number | undefined> {+ const positionRaw = patch.position ?? existing.position;+ const position =+ typeof positionRaw === "number"+ ? positionRaw+ : typeof positionRaw === "string"+ ? Number(positionRaw)+ : Number.NaN;+ if (!Number.isFinite(position))+ throw new Error(+ "Cannot update task: missing numeric `position` on existing task.",+ );++ const title =+ (patch.title as string) ??+ (typeof existing.title === "string" ? existing.title : undefined);+ if (!title) throw new Error("Cannot update task: missing title.");++ const description =+ patch.description !== undefined+ ? patch.description === null+ ? ""+ : String(patch.description)+ : existing.description == null+ ? ""+ : String(existing.description);++ const status =+ (patch.status as string) ??+ (typeof existing.status === "string" ? existing.status : undefined);+ if (!status) throw new Error("Cannot update task: missing status.");++ const priorityRaw =+ (patch.priority as string) ??+ (typeof existing.priority === "string" ? existing.priority : undefined);+ if (!priorityRaw || !isTaskPriority(priorityRaw))+ throw new Error("Cannot update task: invalid or missing priority.");++ const projectId =+ (patch.projectId as string) ??+ (typeof existing.projectId === "string" ? existing.projectId : undefined);+ if (!projectId) throw new Error("Cannot update task: missing projectId.");++ const userId =+ patch.userId !== undefined+ ? patch.userId === null+ ? ""+ : (patch.userId as string)+ : typeof existing.userId === "string"+ ? existing.userId+ : undefined;++ const startDate = formatOptionalIso(+ patch.startDate !== undefined ? patch.startDate : existing.startDate,+ );+ const dueDate = formatOptionalIso(+ patch.dueDate !== undefined ? patch.dueDate : existing.dueDate,+ );++ const body: Record<string, string | number | undefined> = {+ title,+ description,+ status,+ priority: priorityRaw,+ projectId,+ position,+ };+ if (startDate !== undefined) body.startDate = startDate;+ if (dueDate !== undefined) body.dueDate = dueDate;+ if (userId !== undefined) body.userId = userId;+ return body;+}++const prioritySchema = z.enum([+ "no-priority",+ "low",+ "medium",+ "high",+ "urgent",+]);+const nonEmptyString = z.string().trim().min(1);+const optionalNonEmptyString = nonEmptyString.optional();+const nullableOptionalNonEmptyString = nonEmptyString.nullable().optional();+const isoDateTimeSchema = z.string().datetime({ offset: true });+const optionalIsoDateTimeSchema = isoDateTimeSchema.optional();+const nullableOptionalIsoDateTimeSchema = isoDateTimeSchema+ .nullable()+ .optional();+const hexColorSchema = z+ .string()+ .regex(+ /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,+ "Expected a hex color like #FF6600",+ );++export function registerMcpTools(+ server: McpServer,+ baseUrl: string,+ token: string,+): void {+ const client = new ApiClient(baseUrl, token);++ server.registerTool(+ "whoami",+ {+ description: "Return the current Kaneo session and user.",+ inputSchema: z.object({}),+ },+ async () =>+ run(() => client.json("/api/auth/get-session", { method: "GET" })),+ );++ server.registerTool(+ "list_workspaces",+ {+ description: "List workspaces the signed-in user can access.",+ inputSchema: z.object({}),+ },+ async () =>+ run(() => client.json("/api/auth/organization/list", { method: "GET" })),+ );++ server.registerTool(+ "list_projects",+ {+ description: "List projects in a workspace.",+ inputSchema: z.object({+ workspaceId: nonEmptyString.describe("Workspace ID"),+ includeArchived: z+ .boolean()+ .optional()+ .describe("Include archived projects"),+ }),+ },+ async (args) => {+ const qs = new URLSearchParams({ workspaceId: args.workspaceId });+ if (args.includeArchived === true) qs.set("includeArchived", "true");+ return run(() =>+ client.json(`/api/project?${qs.toString()}`, { method: "GET" }),+ );+ },+ );++ server.registerTool(+ "get_project",+ {+ description: "Get a single project by ID.",+ inputSchema: z.object({ id: nonEmptyString }),+ },+ async (args) =>+ run(() => client.json(`/api/project/${encodeURIComponent(args.id)}`)),+ );++ server.registerTool(+ "create_project",+ {+ description: "Create a project in a workspace.",+ inputSchema: z.object({+ name: nonEmptyString,+ workspaceId: nonEmptyString,+ icon: nonEmptyString,+ slug: nonEmptyString,+ }),+ },+ async (args) =>+ run(() =>+ client.json("/api/project", {+ method: "POST",+ body: JSON.stringify({+ name: args.name,+ workspaceId: args.workspaceId,+ icon: args.icon,+ slug: args.slug,+ }),+ }),+ ),+ );++ server.registerTool(+ "update_project",+ {+ description:+ "Update project metadata (PATCH-style: only provided fields are changed).",+ inputSchema: z.object({+ id: nonEmptyString,+ name: optionalNonEmptyString,+ icon: z.string().optional(),+ slug: optionalNonEmptyString,+ description: z.string().optional(),+ isPublic: z.boolean().optional(),+ }),+ },+ async (args) => {+ const { id, ...patch } = args;+ return run(async () => {+ const existing = (await client.json(+ `/api/project/${encodeURIComponent(id)}`,+ { method: "GET" },+ )) as Record<string, unknown>;+ const name =+ patch.name ??+ (typeof existing.name === "string" ? existing.name : "");+ if (!name) throw new Error("Cannot update project: missing name.");+ const icon =+ patch.icon !== undefined+ ? patch.icon+ : typeof existing.icon === "string"+ ? existing.icon+ : "Layout";+ const slug =+ patch.slug ??+ (typeof existing.slug === "string" ? existing.slug : "");+ if (!slug) throw new Error("Cannot update project: missing slug.");+ const description =+ patch.description !== undefined+ ? patch.description+ : typeof existing.description === "string"+ ? existing.description+ : "";+ const isPublic =+ patch.isPublic !== undefined+ ? patch.isPublic+ : typeof existing.isPublic === "boolean"+ ? existing.isPublic+ : false;+ return client.json(`/api/project/${encodeURIComponent(id)}`, {+ method: "PUT",+ body: JSON.stringify({ name, icon, slug, description, isPublic }),+ });+ });+ },+ );++ server.registerTool(+ "list_tasks",+ {+ description: "List tasks for a project (optionally filtered/sorted).",+ inputSchema: z.object({+ projectId: nonEmptyString,+ status: optionalNonEmptyString,+ priority: prioritySchema.optional(),+ assigneeId: optionalNonEmptyString,+ page: z.number().int().positive().optional(),+ limit: z.number().int().positive().optional(),+ sortBy: z+ .enum([+ "createdAt",+ "priority",+ "dueDate",+ "position",+ "title",+ "number",+ ])+ .optional(),+ sortOrder: z.enum(["asc", "desc"]).optional(),+ dueBefore: optionalIsoDateTimeSchema,+ dueAfter: optionalIsoDateTimeSchema,+ }),+ },+ async (args) => {+ const { projectId, ...rest } = args;+ const qs = new URLSearchParams();+ for (const [k, v] of Object.entries(rest)) {+ if (v !== undefined && v !== null) qs.set(k, String(v));+ }+ const q = qs.toString();+ return run(() =>+ client.json(+ `/api/task/tasks/${encodeURIComponent(projectId)}${q ? `?${q}` : ""}`,+ { method: "GET" },+ ),+ );+ },+ );++ server.registerTool(+ "get_task",+ {+ description: "Get a task by ID.",+ inputSchema: z.object({ taskId: nonEmptyString }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/task/${encodeURIComponent(args.taskId)}`, {+ method: "GET",+ }),+ ),+ );++ server.registerTool(+ "create_task",+ {+ description: "Create a task in a project.",+ inputSchema: z.object({+ projectId: nonEmptyString,+ title: nonEmptyString,+ description: z.string(),+ priority: prioritySchema,+ status: nonEmptyString,+ startDate: optionalIsoDateTimeSchema,+ dueDate: optionalIsoDateTimeSchema,+ userId: optionalNonEmptyString,+ }),+ },+ async (args) => {+ const body: Record<string, string | undefined> = {+ title: args.title,+ description: args.description,+ priority: args.priority,+ status: args.status,+ };+ if (args.startDate !== undefined) body.startDate = args.startDate;+ if (args.dueDate !== undefined) body.dueDate = args.dueDate;+ if (args.userId !== undefined) body.userId = args.userId;+ return run(() =>+ client.json(`/api/task/${encodeURIComponent(args.projectId)}`, {+ method: "POST",+ body: JSON.stringify(body),+ }),+ );+ },+ );++ server.registerTool(+ "update_task",+ {+ description:+ "Update a task (fetches current task, merges fields, then full update).",+ inputSchema: z.object({+ taskId: nonEmptyString,+ title: optionalNonEmptyString,+ description: z.string().nullable().optional(),+ status: optionalNonEmptyString,+ priority: prioritySchema.optional(),+ projectId: optionalNonEmptyString,+ position: z.number().optional(),+ startDate: nullableOptionalIsoDateTimeSchema,+ dueDate: nullableOptionalIsoDateTimeSchema,+ userId: nullableOptionalNonEmptyString,+ }),+ },+ async (args) => {+ const { taskId, ...patch } = args;+ return run(async () => {+ const existing = (await client.json(+ `/api/task/${encodeURIComponent(taskId)}`,+ { method: "GET" },+ )) as Record<string, unknown>;+ const body = buildFullTaskUpdateBody(existing, patch);+ return client.json(`/api/task/${encodeURIComponent(taskId)}`, {+ method: "PUT",+ body: JSON.stringify(body),+ });+ });+ },+ );++ server.registerTool(+ "move_task",+ {+ description:+ "Move a task to another project (and optional column status).",+ inputSchema: z.object({+ taskId: nonEmptyString,+ destinationProjectId: nonEmptyString,+ destinationStatus: optionalNonEmptyString,+ }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/task/move/${encodeURIComponent(args.taskId)}`, {+ method: "PUT",+ body: JSON.stringify({+ destinationProjectId: args.destinationProjectId,+ ...(args.destinationStatus !== undefined+ ? { destinationStatus: args.destinationStatus }+ : {}),+ }),+ }),+ ),+ );++ server.registerTool(+ "update_task_status",+ {+ description: "Update only the status (column) of a task.",+ inputSchema: z.object({ taskId: nonEmptyString, status: nonEmptyString }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/task/status/${encodeURIComponent(args.taskId)}`, {+ method: "PUT",+ body: JSON.stringify({ status: args.status }),+ }),+ ),+ );++ server.registerTool(+ "list_task_comments",+ {+ description: "List comments on a task.",+ inputSchema: z.object({ taskId: nonEmptyString }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/comment/${encodeURIComponent(args.taskId)}`, {+ method: "GET",+ }),+ ),+ );++ server.registerTool(+ "create_task_comment",+ {+ description: "Add a comment to a task.",+ inputSchema: z.object({+ taskId: nonEmptyString,+ content: nonEmptyString,+ }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/comment/${encodeURIComponent(args.taskId)}`, {+ method: "POST",+ body: JSON.stringify({ content: args.content }),+ }),+ ),+ );++ server.registerTool(+ "list_workspace_labels",+ {+ description: "List labels defined in a workspace.",+ inputSchema: z.object({ workspaceId: nonEmptyString }),+ },+ async (args) =>+ run(() =>+ client.json(+ `/api/label/workspace/${encodeURIComponent(args.workspaceId)}`,+ { method: "GET" },+ ),+ ),+ );++ server.registerTool(+ "create_label",+ {+ description:+ "Create a label in a workspace (optionally attach to a task).",+ inputSchema: z.object({+ name: nonEmptyString,+ color: hexColorSchema,+ workspaceId: nonEmptyString,+ taskId: optionalNonEmptyString,+ }),+ },+ async (args) =>+ run(() =>+ client.json("/api/label", {+ method: "POST",+ body: JSON.stringify({+ name: args.name,+ color: args.color,+ workspaceId: args.workspaceId,+ ...(args.taskId !== undefined ? { taskId: args.taskId } : {}),+ }),+ }),+ ),+ );++ server.registerTool(+ "attach_label_to_task",+ {+ description: "Attach an existing label to a task.",+ inputSchema: z.object({+ labelId: nonEmptyString,+ taskId: nonEmptyString,+ }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/label/${encodeURIComponent(args.labelId)}/task`, {+ method: "PUT",+ body: JSON.stringify({ taskId: args.taskId }),+ }),+ ),+ );++ server.registerTool(+ "detach_label_from_task",+ {+ description: "Detach a label from its current task.",+ inputSchema: z.object({ labelId: nonEmptyString }),+ },+ async (args) =>+ run(() =>+ client.json(`/api/label/${encodeURIComponent(args.labelId)}/task`, {+ method: "DELETE",+ }),+ ),+ );+}diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdxindex a777d10e3..3a914ba1c 100644--- a/apps/docs/core/integrations/mcp.mdx+++ b/apps/docs/core/integrations/mcp.mdx@@ -3,11 +3,35 @@ title: MCPdescription: Connect Kaneo to MCP clients like Cursor and Claude Desktop using the official Kaneo MCP server.----Kaneo ships an official MCP server package, `@kaneo/mcp`, so you can manage workspaces, projects, tasks, comments, and labels from MCP-compatible tools.+Kaneo supports the Model Context Protocol (MCP) in two ways:-The server runs locally over stdio and authenticates with Kaneo using device authorization.+1. **Built-in HTTP endpoint** — every Kaneo instance exposes `/api/mcp` out of the box. No extra setup, no extra process.+2. **Stdio package** (`@kaneo/mcp`) — a local stdio server for clients that prefer stdio transport.-## Prerequisites+Both offer the same tools for managing workspaces, projects, tasks, comments, and labels.++## Built-in HTTP endpoint++Every Kaneo API instance ships with a Streamable HTTP MCP endpoint. This is the recommended approach for self-hosted deployments.++Point your MCP client at:++```+https://your-kaneo-instance.com/api/mcp+```++On first connect, you will be redirected to Kaneo's login page. After you sign in, all MCP tools run as your authenticated user.++The endpoint implements OAuth 2.1 with PKCE for authentication. Discovery metadata is available at:++- `/.well-known/oauth-protected-resource/api/mcp`+- `/.well-known/oauth-authorization-server/api`++## Stdio package++The `@kaneo/mcp` package runs a local stdio MCP server and authenticates with Kaneo using device authorization. Use this when your MCP client requires stdio transport.++### Prerequisites- Node.js 20 or newer- A running Kaneo API@@ -15,7 +39,7 @@ The server runs locally over stdio and authenticates with Kaneo using device autBy default, self-hosted Kaneo allows both `kaneo-cli` and `kaneo-mcp` as device auth client IDs.-## Install and register+### Install and registerUse the recommended interactive installer:@@ -42,7 +66,7 @@ Use `--help` to see all available targets and flags:kaneo-mcp install --help```-## Point to a self-hosted instance+### Point to a self-hosted instanceWhen generating config, pass your Kaneo base URL:@@ -59,7 +83,7 @@ Or set it via environment variable:If you override `KANEO_MCP_CLIENT_ID`, make sure it is included in [`DEVICE_AUTH_CLIENT_IDS`](/core/installation/environment-variables).-## Authentication flow+### Authentication flowOn the first tool call that needs Kaneo access, the MCP server:@@ -71,7 +95,7 @@ On the first tool call that needs Kaneo access, the MCP server:## Available tools-Current MCP tools include:+Both the HTTP endpoint and stdio package expose the same tools:- Session: `whoami`, `list_workspaces`- Projects: `list_projects`, `get_project`, `create_project`, `update_project`@@ -79,7 +103,7 @@ Current MCP tools include:- Comments: `list_task_comments`, `create_task_comment`- Labels: `list_workspace_labels`, `create_label`, `attach_label_to_task`, `detach_label_from_task`-## Run manually for debugging+## DebuggingTo run the stdio server directly:@@ -93,4 +117,3 @@ When running from source in this monorepo:pnpm --filter @kaneo/mcp run buildpnpm --filter @kaneo/mcp run start```-diff --git a/packages/mcp/README.md b/packages/mcp/README.mdindex cf85d8343..e78804af4 100644--- a/packages/mcp/README.md+++ b/packages/mcp/README.md@@ -1,9 +1,11 @@# Kaneo MCP server-`@kaneo/mcp` is a local MCP server for Kaneo.+`@kaneo/mcp` is a local stdio MCP server for Kaneo.It runs over stdio, signs in with Kaneo's device flow, and then calls the Kaneo API with a bearer token. The package lives in `packages/mcp` in this monorepo and exposes the `kaneo-mcp` CLI.+> **Tip:** Every Kaneo instance also ships a built-in HTTP MCP endpoint at `/api/mcp`. If your MCP client supports Streamable HTTP transport (e.g. Claude Code), you can connect directly without this package. See the [MCP docs](https://docs.kaneo.app/core/integrations/mcp) for details.+## Prerequisites- Node.js 20+diff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex 9e3d9fdc5..26d81c940 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -13,6 +13,12 @@"bin": {"kaneo-mcp": "dist/index.js"},+ "exports": {+ ".": {+ "import": "./dist/server.js",+ "types": "./dist/server.d.ts"+ }+ },"publishConfig": {"access": "public"},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e19b6ad2a..331ca0566 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -84,6 +84,9 @@ importers:'@kaneo/email':specifier: workspace:*version: link:../../packages/email+ '@modelcontextprotocol/sdk':+ specifier: ^1.26.0+ version: 1.26.0([email protected])'@octokit/webhooks':specifier: ^14.2.0version: 14.2.0