A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(mcp): more MCP tools
Mohamed Bassem8de38d487c48
diff --git a/apps/mcp/README.md b/apps/mcp/README.mdindex 9214b585..58281c26 100644--- a/apps/mcp/README.md+++ b/apps/mcp/README.md@@ -8,6 +8,7 @@ with Karakeep from other tools.**Bookmarks**- Searching bookmarks (`search-bookmarks`)- Reading a bookmark (`get-bookmark`, `get-bookmark-content`)+- Listing the lists that contain a bookmark (`get-bookmark-lists`)- Creating text and URL bookmarks (`create-bookmark`)- Updating a bookmark (`update-bookmark`)- Deleting a bookmark (`delete-bookmark`)@@ -17,7 +18,8 @@ with Karakeep from other tools.- Retrieving a single list (`get-list`)- Creating a list (`create-list`)- Updating a list (`update-list`) — name, icon, description, parentId, query, public; field constraints (length caps, smart-query validation) are inherited from the shared schema-- Deleting a list (`delete-list`) — child lists are NOT deleted with the parent; they keep their parentId pointing at the deleted list+- Deleting a list (`delete-list`) — child lists are NOT deleted with the parent; they become root-level lists+- Listing bookmarks in manual and smart lists (`get-list-bookmarks`)- Adding and removing bookmarks from lists (`add-bookmark-to-list`, `remove-bookmark-from-list`)**Tags**@@ -31,6 +33,12 @@ with Karakeep from other tools.**Assets**- Getting a temporary signed download URL for an asset (`get-asset`)+**Highlights**+- Listing highlights across all bookmarks (`list-highlights`)+- Listing highlights for a bookmark (`get-bookmark-highlights`)+- Retrieving a single highlight (`get-highlight`)+- Creating, updating, and deleting highlights (`create-highlight`, `update-highlight`, `delete-highlight`)+Currently, the MCP server only exposes tools (no resources).## Usage with Claude Desktopdiff --git a/apps/mcp/src/bookmarks.test.ts b/apps/mcp/src/bookmarks.test.tsindex 3c8eadef..dc3e45c7 100644--- a/apps/mcp/src/bookmarks.test.ts+++ b/apps/mcp/src/bookmarks.test.ts@@ -19,7 +19,11 @@ vi.mock("./shared", () => ({turndownService: mockTurndown,}));-import { deleteBookmarkHandler, getBookmarkContentHandler } from "./bookmarks";+import {+ deleteBookmarkHandler,+ getBookmarkContentHandler,+ getBookmarkListsHandler,+} from "./bookmarks";const textOf = (result: CallToolResult): string => {const first = result.content[0];@@ -76,6 +80,56 @@ afterEach(() => {vi.clearAllMocks();});+describe("get-bookmark-lists", () => {+ it("returns every list containing the bookmark", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: {+ lists: [+ {+ id: "list_1",+ name: "Reading",+ icon: "📚",+ type: "manual",+ description: null,+ parentId: null,+ query: null,+ public: false,+ hasCollaborators: false,+ userRole: "owner",+ },+ ],+ },+ error: undefined,+ });++ const result = await getBookmarkListsHandler({+ bookmarkId: "bookmark_1",+ });++ expect(mockClient.GET).toHaveBeenCalledWith(+ "/bookmarks/{bookmarkId}/lists",+ {+ params: { path: { bookmarkId: "bookmark_1" } },+ },+ );+ expect(textOf(result)).toContain("List ID: list_1");+ expect(textOf(result)).toContain("Name: Reading");+ });++ it("reports when the bookmark is not in a list", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: { lists: [] },+ error: undefined,+ });++ const result = await getBookmarkListsHandler({+ bookmarkId: "bookmark_1",+ });++ expect(textOf(result)).toBe("This bookmark is not in any lists.");+ });+});+describe("delete-bookmark", () => {it("fetches the bookmark, deletes it, and reports the title", async () => {mockClient.GET.mockResolvedValueOnce({diff --git a/apps/mcp/src/bookmarks.ts b/apps/mcp/src/bookmarks.tsindex 824cff22..51f94489 100644--- a/apps/mcp/src/bookmarks.ts+++ b/apps/mcp/src/bookmarks.ts@@ -2,7 +2,7 @@ import { CallToolResult } from "@modelcontextprotocol/sdk/types";import { z } from "zod";import { karakeepClient, mcpServer, turndownService } from "./shared";-import { compactBookmark, toMcpToolError } from "./utils";+import { compactBookmark, compactList, toMcpToolError } from "./utils";// ToolsmcpServer.tool(@@ -40,8 +40,12 @@ machine learning is:fav`),.describe(`The next cursor to use for pagination. The value for this is returned from a previous call to this tool.`,),+ sortOrder: z+ .enum(["asc", "desc", "relevance"])+ .optional()+ .describe(`Sort by relevance or creation date. Defaults to relevance.`),},- async ({ query, limit, nextCursor }): Promise<CallToolResult> => {+ async ({ query, limit, nextCursor, sortOrder }): Promise<CallToolResult> => {const res = await karakeepClient.GET("/bookmarks/search", {params: {query: {@@ -49,6 +53,7 @@ machine learning is:fav`),limit: limit,includeContent: false,cursor: nextCursor,+ sortOrder,},},});@@ -101,6 +106,45 @@ mcpServer.tool(},);+export const getBookmarkListsInputSchema = {+ bookmarkId: z+ .string()+ .min(1)+ .describe(`The id of the bookmark whose lists to retrieve.`),+};++export async function getBookmarkListsHandler({+ bookmarkId,+}: {+ bookmarkId: string;+}): Promise<CallToolResult> {+ const res = await karakeepClient.GET("/bookmarks/{bookmarkId}/lists", {+ params: { path: { bookmarkId } },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [+ {+ type: "text",+ text:+ res.data.lists.length > 0+ ? res.data.lists.map(compactList).join("\n\n")+ : "This bookmark is not in any lists.",+ },+ ],+ };+}++mcpServer.tool(+ "get-bookmark-lists",+ `List every list that contains a bookmark.`,+ getBookmarkListsInputSchema,+ { readOnlyHint: true },+ getBookmarkListsHandler,+);+mcpServer.tool("create-bookmark",`Create a link bookmark or a text bookmark`,diff --git a/apps/mcp/src/highlights.test.ts b/apps/mcp/src/highlights.test.tsnew file mode 100644index 00000000..2ec32a5d--- /dev/null+++ b/apps/mcp/src/highlights.test.ts@@ -0,0 +1,243 @@+import type { CallToolResult } from "@modelcontextprotocol/sdk/types";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { mockClient, mockTool } = vi.hoisted(() => ({+ mockClient: {+ GET: vi.fn(),+ POST: vi.fn(),+ PATCH: vi.fn(),+ DELETE: vi.fn(),+ },+ mockTool: vi.fn(),+}));++vi.mock("./shared", () => ({+ karakeepClient: mockClient,+ mcpServer: { tool: mockTool },+}));++import {+ createHighlightHandler,+ deleteHighlightHandler,+ getBookmarkHighlightsHandler,+ getHighlightHandler,+ listHighlightsHandler,+ updateHighlightHandler,+} from "./highlights";++const textOf = (result: CallToolResult): string => {+ const first = result.content[0];+ if (!first || first.type !== "text") {+ throw new Error(`expected text content, got ${JSON.stringify(first)}`);+ }+ return first.text;+};++const sampleHighlight = {+ id: "highlight_1",+ bookmarkId: "bookmark_1",+ userId: "user_1",+ startOffset: 10,+ endOffset: 20,+ color: "yellow" as const,+ text: "highlighted text",+ note: "important",+ createdAt: "2026-01-01T00:00:00Z",+};++beforeEach(() => {+ mockClient.GET.mockReset();+ mockClient.POST.mockReset();+ mockClient.PATCH.mockReset();+ mockClient.DELETE.mockReset();+});++afterEach(() => {+ vi.clearAllMocks();+});++describe("list-highlights", () => {+ it("forwards pagination and returns formatted highlights", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: { highlights: [sampleHighlight], nextCursor: "next_page" },+ error: undefined,+ });++ const result = await listHighlightsHandler({+ limit: 20,+ cursor: "current_page",+ });++ expect(mockClient.GET).toHaveBeenCalledWith("/highlights", {+ params: { query: { limit: 20, cursor: "current_page" } },+ });+ const text = textOf(result);+ expect(text).toContain("Highlight ID: highlight_1");+ expect(text).toContain("Bookmark ID: bookmark_1");+ expect(text).toContain("Next page cursor: next_page");+ });++ it("returns a useful empty state", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: { highlights: [], nextCursor: null },+ error: undefined,+ });++ expect(textOf(await listHighlightsHandler({}))).toBe(+ "No highlights found.",+ );+ });+});++describe("get-bookmark-highlights", () => {+ it("returns highlights for one bookmark", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: { highlights: [sampleHighlight] },+ error: undefined,+ });++ const result = await getBookmarkHighlightsHandler({+ bookmarkId: "bookmark_1",+ });++ expect(mockClient.GET).toHaveBeenCalledWith(+ "/bookmarks/{bookmarkId}/highlights",+ {+ params: { path: { bookmarkId: "bookmark_1" } },+ },+ );+ expect(textOf(result)).toContain("highlighted text");+ });++ it("surfaces bookmark lookup errors", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: undefined,+ error: { code: "NOT_FOUND", message: "Bookmark not found" },+ });++ const result = await getBookmarkHighlightsHandler({+ bookmarkId: "missing",+ });++ expect(result.isError).toBe(true);+ });+});++describe("get-highlight", () => {+ it("returns a single highlight", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: sampleHighlight,+ error: undefined,+ });++ const result = await getHighlightHandler({ highlightId: "highlight_1" });++ expect(mockClient.GET).toHaveBeenCalledWith("/highlights/{highlightId}", {+ params: { path: { highlightId: "highlight_1" } },+ });+ expect(textOf(result)).toContain("Range: 10-20");+ });+});++describe("create-highlight", () => {+ it("creates and returns a highlight", async () => {+ mockClient.POST.mockResolvedValueOnce({+ data: sampleHighlight,+ error: undefined,+ });++ const input = {+ bookmarkId: "bookmark_1",+ startOffset: 10,+ endOffset: 20,+ color: "yellow" as const,+ text: "highlighted text",+ note: "important",+ };+ const result = await createHighlightHandler(input);++ expect(mockClient.POST).toHaveBeenCalledWith("/highlights", {+ body: input,+ });+ expect(textOf(result)).toContain("Highlight ID: highlight_1");+ });++ it("rejects an empty or reversed range without calling the API", async () => {+ const result = await createHighlightHandler({+ bookmarkId: "bookmark_1",+ startOffset: 20,+ endOffset: 10,+ text: null,+ note: null,+ });++ expect(mockClient.POST).not.toHaveBeenCalled();+ expect(result.isError).toBe(true);+ expect(textOf(result)).toMatch(/endOffset must be greater/i);+ });+});++describe("update-highlight", () => {+ it("sends only fields that were provided", async () => {+ mockClient.PATCH.mockResolvedValueOnce({+ data: { ...sampleHighlight, color: "blue", note: null },+ error: undefined,+ });++ const result = await updateHighlightHandler({+ highlightId: "highlight_1",+ color: "blue",+ note: null,+ });++ expect(mockClient.PATCH).toHaveBeenCalledWith("/highlights/{highlightId}", {+ params: { path: { highlightId: "highlight_1" } },+ body: { color: "blue", note: null },+ });+ expect(textOf(result)).toContain("Color: blue");+ });++ it("rejects calls with no changed fields", async () => {+ const result = await updateHighlightHandler({+ highlightId: "highlight_1",+ });++ expect(mockClient.PATCH).not.toHaveBeenCalled();+ expect(result.isError).toBe(true);+ });+});++describe("delete-highlight", () => {+ it("deletes the highlight and identifies its bookmark", async () => {+ mockClient.DELETE.mockResolvedValueOnce({+ data: sampleHighlight,+ error: undefined,+ });++ const result = await deleteHighlightHandler({+ highlightId: "highlight_1",+ });++ expect(mockClient.DELETE).toHaveBeenCalledWith(+ "/highlights/{highlightId}",+ {+ params: { path: { highlightId: "highlight_1" } },+ },+ );+ expect(textOf(result)).toContain("Deleted highlight highlight_1");+ expect(textOf(result)).toContain("bookmark_1");+ });++ it("surfaces delete errors", async () => {+ mockClient.DELETE.mockResolvedValueOnce({+ data: undefined,+ error: { code: "NOT_FOUND", message: "Highlight not found" },+ });++ const result = await deleteHighlightHandler({+ highlightId: "missing",+ });++ expect(result.isError).toBe(true);+ });+});diff --git a/apps/mcp/src/highlights.ts b/apps/mcp/src/highlights.tsnew file mode 100644index 00000000..02de7710--- /dev/null+++ b/apps/mcp/src/highlights.ts@@ -0,0 +1,258 @@+import type { CallToolResult } from "@modelcontextprotocol/sdk/types";+import { z } from "zod";++import { karakeepClient, mcpServer } from "./shared";+import { compactHighlight, pickDefined, toMcpToolError } from "./utils";++const highlightColorSchema = z.enum(["yellow", "red", "green", "blue"]);++export const listHighlightsInputSchema = {+ limit: z+ .number()+ .int()+ .min(1)+ .optional()+ .describe(`Maximum number of highlights to return per page.`),+ cursor: z+ .string()+ .min(1)+ .optional()+ .describe(`Cursor from a previous response to fetch the next page.`),+};++export type ListHighlightsInput = z.infer<+ z.ZodObject<typeof listHighlightsInputSchema>+>;++export async function listHighlightsHandler(+ input: ListHighlightsInput,+): Promise<CallToolResult> {+ const res = await karakeepClient.GET("/highlights", {+ params: { query: pickDefined(input) },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ const cursorLine = res.data.nextCursor+ ? `\n\nNext page cursor: ${res.data.nextCursor}`+ : "";+ const highlights =+ res.data.highlights.length > 0+ ? res.data.highlights.map(compactHighlight).join("\n\n")+ : "No highlights found.";+ return {+ content: [{ type: "text", text: highlights + cursorLine }],+ };+}++mcpServer.tool(+ "list-highlights",+ `List highlights across all bookmarks, newest first.`,+ listHighlightsInputSchema,+ { readOnlyHint: true },+ listHighlightsHandler,+);++export const getBookmarkHighlightsInputSchema = {+ bookmarkId: z+ .string()+ .min(1)+ .describe(`The id of the bookmark whose highlights to retrieve.`),+};++export async function getBookmarkHighlightsHandler({+ bookmarkId,+}: {+ bookmarkId: string;+}): Promise<CallToolResult> {+ const res = await karakeepClient.GET("/bookmarks/{bookmarkId}/highlights", {+ params: { path: { bookmarkId } },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [+ {+ type: "text",+ text:+ res.data.highlights.length > 0+ ? res.data.highlights.map(compactHighlight).join("\n\n")+ : "No highlights found for this bookmark.",+ },+ ],+ };+}++mcpServer.tool(+ "get-bookmark-highlights",+ `List every highlight on a bookmark.`,+ getBookmarkHighlightsInputSchema,+ { readOnlyHint: true },+ getBookmarkHighlightsHandler,+);++export const getHighlightInputSchema = {+ highlightId: z+ .string()+ .min(1)+ .describe(`The id of the highlight to retrieve.`),+};++export async function getHighlightHandler({+ highlightId,+}: {+ highlightId: string;+}): Promise<CallToolResult> {+ const res = await karakeepClient.GET("/highlights/{highlightId}", {+ params: { path: { highlightId } },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [{ type: "text", text: compactHighlight(res.data) }],+ };+}++mcpServer.tool(+ "get-highlight",+ `Retrieve a single highlight by id.`,+ getHighlightInputSchema,+ { readOnlyHint: true },+ getHighlightHandler,+);++export const createHighlightInputSchema = {+ bookmarkId: z+ .string()+ .min(1)+ .describe(`The id of the bookmark to highlight.`),+ startOffset: z+ .number()+ .int()+ .min(0)+ .describe(`Zero-based inclusive character offset.`),+ endOffset: z+ .number()+ .int()+ .min(0)+ .describe(`Zero-based exclusive character offset.`),+ color: highlightColorSchema+ .optional()+ .describe(`Highlight color. Defaults to yellow.`),+ text: z+ .string()+ .nullable()+ .describe(`The highlighted text, or null if unavailable.`),+ note: z+ .string()+ .nullable()+ .describe(`An optional note attached to the highlight.`),+};++export type CreateHighlightInput = z.infer<+ z.ZodObject<typeof createHighlightInputSchema>+>;++export async function createHighlightHandler(+ input: CreateHighlightInput,+): Promise<CallToolResult> {+ if (input.endOffset <= input.startOffset) {+ return toMcpToolError(`endOffset must be greater than startOffset.`);+ }+ const res = await karakeepClient.POST("/highlights", {+ body: input,+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [{ type: "text", text: compactHighlight(res.data) }],+ };+}++mcpServer.tool(+ "create-highlight",+ `Create a text highlight on a bookmark using character offsets from the bookmark's readable content.`,+ createHighlightInputSchema,+ { readOnlyHint: false, destructiveHint: false },+ createHighlightHandler,+);++export const updateHighlightInputSchema = {+ highlightId: z.string().min(1).describe(`The id of the highlight to update.`),+ color: highlightColorSchema.optional().describe(`New highlight color.`),+ note: z+ .string()+ .nullable()+ .optional()+ .describe(`New note. Pass null to clear it.`),+};++export type UpdateHighlightInput = z.infer<+ z.ZodObject<typeof updateHighlightInputSchema>+>;++export async function updateHighlightHandler(+ input: UpdateHighlightInput,+): Promise<CallToolResult> {+ const { highlightId, ...fields } = input;+ const body = pickDefined(fields);+ if (Object.keys(body).length === 0) {+ return toMcpToolError(+ `update-highlight requires at least one field to update (color or note).`,+ );+ }+ const res = await karakeepClient.PATCH("/highlights/{highlightId}", {+ params: { path: { highlightId } },+ body,+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [{ type: "text", text: compactHighlight(res.data) }],+ };+}++mcpServer.tool(+ "update-highlight",+ `Update a highlight's color or note.`,+ updateHighlightInputSchema,+ { readOnlyHint: false, destructiveHint: false },+ updateHighlightHandler,+);++export const deleteHighlightInputSchema = {+ highlightId: z.string().min(1).describe(`The id of the highlight to delete.`),+};++export async function deleteHighlightHandler({+ highlightId,+}: {+ highlightId: string;+}): Promise<CallToolResult> {+ const res = await karakeepClient.DELETE("/highlights/{highlightId}", {+ params: { path: { highlightId } },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ return {+ content: [+ {+ type: "text",+ text: `Deleted highlight ${res.data.id} from bookmark ${res.data.bookmarkId}.`,+ },+ ],+ };+}++mcpServer.tool(+ "delete-highlight",+ `Delete a highlight by id.`,+ deleteHighlightInputSchema,+ { readOnlyHint: false, destructiveHint: true, idempotentHint: false },+ deleteHighlightHandler,+);diff --git a/apps/mcp/src/index.ts b/apps/mcp/src/index.tsindex c55e36e7..705b2a96 100644--- a/apps/mcp/src/index.ts+++ b/apps/mcp/src/index.ts@@ -5,6 +5,7 @@ import { mcpServer } from "./shared";import "./assets.ts";import "./bookmarks.ts";+import "./highlights.ts";import "./lists.ts";import "./tags.ts";diff --git a/apps/mcp/src/lists.test.ts b/apps/mcp/src/lists.test.tsindex 803f1cb6..7693d849 100644--- a/apps/mcp/src/lists.test.ts+++ b/apps/mcp/src/lists.test.ts@@ -17,7 +17,12 @@ vi.mock("./shared", () => ({mcpServer: { tool: mockTool },}));-import { deleteListHandler, getListHandler, updateListHandler } from "./lists";+import {+ deleteListHandler,+ getListBookmarksHandler,+ getListHandler,+ updateListHandler,+} from "./lists";const textOf = (result: CallToolResult): string => {const first = result.content[0];@@ -40,6 +45,29 @@ const sampleList = {userRole: "owner" as const,};+const sampleBookmark = {+ id: "bookmark_1",+ createdAt: "2026-01-01T00:00:00Z",+ modifiedAt: null,+ title: "Sample",+ archived: false,+ favourited: true,+ taggingStatus: "success" as const,+ summarizationStatus: null,+ embeddingStatus: null,+ note: null,+ summary: null,+ source: "api" as const,+ userId: "user_1",+ tags: [],+ content: {+ type: "text" as const,+ text: "Saved text",+ sourceUrl: null,+ },+ assets: [],+};+beforeEach(() => {mockClient.GET.mockReset();mockClient.POST.mockReset();@@ -85,6 +113,44 @@ describe("get-list", () => {});});+describe("get-list-bookmarks", () => {+ it("uses the stable list id and forwards pagination options", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: { bookmarks: [sampleBookmark], nextCursor: "next_page" },+ error: undefined,+ });++ const result = await getListBookmarksHandler({+ listId: "list_123",+ sortOrder: "asc",+ limit: 10,+ includeContent: true,+ });++ expect(mockClient.GET).toHaveBeenCalledWith("/lists/{listId}/bookmarks", {+ params: {+ path: { listId: "list_123" },+ query: { sortOrder: "asc", limit: 10, includeContent: true },+ },+ });+ const text = textOf(result);+ expect(text).toContain("Bookmark ID: bookmark_1");+ expect(text).toContain("Text: Saved text");+ expect(text).toContain("Next page cursor: next_page");+ });++ it("surfaces a missing-list error", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: undefined,+ error: { code: "NOT_FOUND", message: "List not found" },+ });++ const result = await getListBookmarksHandler({ listId: "missing" });++ expect(result.isError).toBe(true);+ });+});+describe("update-list", () => {it("sends only the provided fields and returns the updated list", async () => {const updated = { ...sampleList, name: "Reading list", icon: "📖" };diff --git a/apps/mcp/src/lists.ts b/apps/mcp/src/lists.tsindex f2995bc9..04647395 100644--- a/apps/mcp/src/lists.ts+++ b/apps/mcp/src/lists.ts@@ -1,25 +1,18 @@import { CallToolResult } from "@modelcontextprotocol/sdk/types";import { z } from "zod";-import type { KarakeepAPISchemas } from "@karakeep/sdk";import {zEditBookmarkListSchema,zEditBookmarkListSchemaWithValidation,} from "@karakeep/shared/types/lists";import { karakeepClient, mcpServer } from "./shared";-import { pickDefined, toMcpToolError } from "./utils";--function formatList(list: KarakeepAPISchemas["List"]): string {- return `List ID: ${list.id}-Name: ${list.name}-Icon: ${list.icon}-Type: ${list.type}-Description: ${list.description ?? ""}-Parent ID: ${list.parentId ?? ""}-Query: ${list.query ?? ""}-Public: ${list.public}`;-}+import {+ compactBookmark,+ compactList,+ pickDefined,+ toMcpToolError,+} from "./utils";mcpServer.tool("get-lists",@@ -35,7 +28,7 @@ mcpServer.tool(content: [{type: "text",- text: res.data.lists.map(formatList).join("\n\n"),+ text: res.data.lists.map(compactList).join("\n\n"),},],};@@ -61,7 +54,7 @@ export async function getListHandler({content: [{type: "text",- text: formatList(res.data),+ text: compactList(res.data),},],};@@ -136,7 +129,7 @@ export async function updateListHandler(type: "text",text: `List ${res.data.id} updated.-${formatList(res.data)}`,+${compactList(res.data)}`,},],};@@ -255,6 +248,71 @@ mcpServer.tool(},);+export const getListBookmarksInputSchema = {+ listId: z+ .string()+ .min(1)+ .describe(`The id of the list whose bookmarks to retrieve.`),+ sortOrder: z+ .enum(["asc", "desc"])+ .optional()+ .describe(`Sort by creation date. Defaults to newest first.`),+ limit: z+ .number()+ .int()+ .min(1)+ .optional()+ .describe(`Maximum number of bookmarks to return per page.`),+ cursor: z+ .string()+ .min(1)+ .optional()+ .describe(`Cursor from a previous response to fetch the next page.`),+ includeContent: z+ .boolean()+ .optional()+ .describe(`Whether to include each bookmark's full content.`),+};++export type GetListBookmarksInput = z.infer<+ z.ZodObject<typeof getListBookmarksInputSchema>+>;++export async function getListBookmarksHandler(+ input: GetListBookmarksInput,+): Promise<CallToolResult> {+ const { listId, includeContent, ...query } = input;+ const res = await karakeepClient.GET("/lists/{listId}/bookmarks", {+ params: {+ path: { listId },+ query: pickDefined({ ...query, includeContent }),+ },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }+ const cursorLine = res.data.nextCursor+ ? `\n\nNext page cursor: ${res.data.nextCursor}`+ : "";+ const bookmarks =+ res.data.bookmarks.length > 0+ ? res.data.bookmarks+ .map((bookmark) => compactBookmark(bookmark, { includeContent }))+ .join("\n\n")+ : "No bookmarks found in this list.";+ return {+ content: [{ type: "text", text: bookmarks + cursorLine }],+ };+}++mcpServer.tool(+ "get-list-bookmarks",+ `List bookmarks in a list by its stable id. Smart lists are evaluated using their saved query.`,+ getListBookmarksInputSchema,+ { readOnlyHint: true },+ getListBookmarksHandler,+);+mcpServer.tool("create-list",`Create a list.`,diff --git a/apps/mcp/src/shared.ts b/apps/mcp/src/shared.tsindex b2ffff05..2dbe0d68 100644--- a/apps/mcp/src/shared.ts+++ b/apps/mcp/src/shared.ts@@ -3,6 +3,8 @@ import TurndownService from "turndown";import { createKarakeepClient } from "@karakeep/sdk";+import packageJson from "../package.json";+const addr = process.env.KARAKEEP_API_ADDR;const apiKey = process.env.KARAKEEP_API_KEY;@@ -28,7 +30,7 @@ export const karakeepClient = createKarakeepClient({export const mcpServer = new McpServer({name: "Karakeep",- version: "0.23.0",+ version: packageJson.version,});export const turndownService = new TurndownService();diff --git a/apps/mcp/src/utils.test.ts b/apps/mcp/src/utils.test.tsindex c926d47f..73a79ace 100644--- a/apps/mcp/src/utils.test.ts+++ b/apps/mcp/src/utils.test.ts@@ -67,6 +67,9 @@ describe("compactBookmark", () => {});expect(out).toContain("Bookmark type: text");expect(out).toContain("Text: the actual stored text");+ expect(out).toContain("Archived: false");+ expect(out).toContain("Favourited: false");+ expect(out).toContain("Tagging status: success");});it("does not emit a Text: line for link-type bookmarks", () => {@@ -129,4 +132,23 @@ describe("compactBookmark", () => {expect(out).toContain("Bookmark type: media");expect(out).toContain("Content: extracted pdf text");});++ it("renders attached asset ids, types, and file names", () => {+ const out = compactBookmark({+ ...base,+ assets: [+ {+ id: "asset_2",+ assetType: "screenshot",+ fileName: "page.png",+ },+ ],+ content: {+ type: "link",+ url: "https://example.com",+ },+ });++ expect(out).toContain("Assets: asset_2 (screenshot, page.png)");+ });});diff --git a/apps/mcp/src/utils.ts b/apps/mcp/src/utils.tsindex b9f28be1..20758330 100644--- a/apps/mcp/src/utils.ts+++ b/apps/mcp/src/utils.ts@@ -41,6 +41,31 @@ Name: ${tag.name}Bookmarks: ${tag.numBookmarks} (human: ${humanCount}, ai: ${aiCount})`;}+export function compactList(list: KarakeepAPISchemas["List"]): string {+ return `List ID: ${list.id}+Name: ${list.name}+Icon: ${list.icon}+Type: ${list.type}+Description: ${list.description ?? ""}+Parent ID: ${list.parentId ?? ""}+Query: ${list.query ?? ""}+Public: ${list.public}+Has collaborators: ${list.hasCollaborators}+User role: ${list.userRole}`;+}++export function compactHighlight(+ highlight: KarakeepAPISchemas["Highlight"],+): string {+ return `Highlight ID: ${highlight.id}+Bookmark ID: ${highlight.bookmarkId}+Created at: ${highlight.createdAt}+Range: ${highlight.startOffset}-${highlight.endOffset}+Color: ${highlight.color}+Text: ${highlight.text ?? ""}+Note: ${highlight.note ?? ""}`;+}+export function compactBookmark(bookmark: KarakeepAPISchemas["Bookmark"],options: { includeContent?: boolean } = {},@@ -72,15 +97,33 @@ Source URL: ${bookmark.content.sourceUrl ?? ""}`;content = `Bookmark type: unknown`;}+ const assets =+ bookmark.assets.length > 0+ ? bookmark.assets+ .map(+ (asset) =>+ `${asset.id} (${asset.assetType}${asset.fileName ? `, ${asset.fileName}` : ""})`,+ )+ .join(", ")+ : "none";+return `Bookmark ID: ${bookmark.id}Created at: ${bookmark.createdAt}+ Modified at: ${bookmark.modifiedAt ?? ""}Title: ${bookmark.title? bookmark.title: ((bookmark.content.type === "link" ? bookmark.content.title : "") ?? "")}+ Archived: ${bookmark.archived}+ Favourited: ${bookmark.favourited}+ Source: ${bookmark.source ?? ""}+ Tagging status: ${bookmark.taggingStatus ?? ""}+ Summarization status: ${bookmark.summarizationStatus ?? ""}+ Embedding status: ${bookmark.embeddingStatus ?? ""}Summary: ${bookmark.summary ?? ""}Note: ${bookmark.note ?? ""}${content}- Tags: ${bookmark.tags.map((t) => t.name).join(", ")}`;+ Tags: ${bookmark.tags.map((t) => t.name).join(", ")}+ Assets: ${assets}`;}