A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(mcp): add ability to fetch assets via signed URLs
Mohamed Bassem06d99bd6d7ab
diff --git a/apps/mcp/README.md b/apps/mcp/README.mdindex 1e170e3b..9214b585 100644--- a/apps/mcp/README.md+++ b/apps/mcp/README.md@@ -28,6 +28,9 @@ with Karakeep from other tools.- Listing the bookmarks attached to a tag (`get-tag-bookmarks`)- Attaching and detaching tags on bookmarks (`attach-tag-to-bookmark`, `detach-tag-from-bookmark`)+**Assets**+- Getting a temporary signed download URL for an asset (`get-asset`)+Currently, the MCP server only exposes tools (no resources).## Usage with Claude Desktopdiff --git a/apps/mcp/src/assets.test.ts b/apps/mcp/src/assets.test.tsnew file mode 100644index 00000000..53d90de9--- /dev/null+++ b/apps/mcp/src/assets.test.ts@@ -0,0 +1,79 @@+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(),+ },+ mockTool: vi.fn(),+}));++vi.mock("./shared", () => ({+ karakeepClient: mockClient,+ mcpServer: { tool: mockTool },+}));++import { getAssetHandler } from "./assets";++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;+};++beforeEach(() => {+ mockClient.GET.mockReset();+});++afterEach(() => {+ vi.clearAllMocks();+});++describe("get-asset", () => {+ it("returns a signed URL and its expiry", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: {+ assetId: "asset_1",+ signedUrl:+ "https://example.com/api/public/assets/asset_1?token=signed-token",+ expiresAt: "2026-01-01T01:00:00.000Z",+ },+ error: undefined,+ });++ const result = await getAssetHandler({ assetId: "asset_1" });++ expect(mockClient.GET).toHaveBeenCalledWith(+ "/assets/{assetId}/signed-url",+ {+ params: {+ path: {+ assetId: "asset_1",+ },+ },+ },+ );+ expect(textOf(result)).toContain("asset_1");+ expect(textOf(result)).toContain(+ "https://example.com/api/public/assets/asset_1?token=signed-token",+ );+ expect(textOf(result)).toContain("2026-01-01T01:00:00.000Z");+ });++ it("returns an MCP error when the asset cannot be accessed", async () => {+ mockClient.GET.mockResolvedValueOnce({+ data: undefined,+ error: {+ code: "NOT_FOUND",+ message: "Asset not found",+ },+ });++ const result = await getAssetHandler({ assetId: "missing" });++ expect(result.isError).toBe(true);+ expect(textOf(result)).toContain("Asset not found");+ });+});diff --git a/apps/mcp/src/assets.ts b/apps/mcp/src/assets.tsnew file mode 100644index 00000000..309c9571--- /dev/null+++ b/apps/mcp/src/assets.ts@@ -0,0 +1,44 @@+import type { CallToolResult } from "@modelcontextprotocol/sdk/types";+import { z } from "zod";++import { karakeepClient, mcpServer } from "./shared";+import { toMcpToolError } from "./utils";++export const getAssetInputSchema = {+ assetId: z.string().min(1).describe("The ID of the asset to retrieve."),+};++export async function getAssetHandler({+ assetId,+}: {+ assetId: string;+}): Promise<CallToolResult> {+ const res = await karakeepClient.GET("/assets/{assetId}/signed-url", {+ params: {+ path: {+ assetId,+ },+ },+ });+ if (!res.data) {+ return toMcpToolError(res.error);+ }++ return {+ content: [+ {+ type: "text",+ text: `Asset ID: ${res.data.assetId}+Signed URL: ${res.data.signedUrl}+Expires at: ${res.data.expiresAt}`,+ },+ ],+ };+}++mcpServer.tool(+ "get-asset",+ "Get a temporary signed URL for downloading an asset by its asset ID.",+ getAssetInputSchema,+ getAssetHandler,+);diff --git a/apps/mcp/src/index.ts b/apps/mcp/src/index.tsindex 51437fc6..c55e36e7 100644--- a/apps/mcp/src/index.ts+++ b/apps/mcp/src/index.ts@@ -3,6 +3,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"import { mcpServer } from "./shared";+import "./assets.ts";import "./bookmarks.ts";import "./lists.ts";import "./tags.ts";diff --git a/packages/api/routes/assets.ts b/packages/api/routes/assets.tsindex f73852b7..e9e8bfb3 100644--- a/packages/api/routes/assets.ts+++ b/packages/api/routes/assets.ts@@ -2,6 +2,7 @@ import { zValidator } from "@hono/zod-validator";import { Hono } from "hono";import { z } from "zod";+import { getAlignedExpiry } from "@karakeep/shared/signedTokens";import { Asset } from "@karakeep/trpc/models/assets";import { apiKeyScopeMiddleware } from "../middlewares/apiKeyScopes";@@ -40,6 +41,25 @@ const app = new Hono()});},)+ .get(+ "/:assetId/signed-url",+ apiKeyScopeMiddleware("assets", "read"),+ async (c) => {+ const assetId = c.req.param("assetId");+ const asset = await Asset.fromId(c.var.ctx, assetId);+ const expiresAt = getAlignedExpiry(3600, 900);++ return c.json({+ assetId,+ signedUrl: Asset.getPublicSignedAssetUrl(+ assetId,+ asset.asset.userId,+ expiresAt,+ ),+ expiresAt: new Date(expiresAt).toISOString(),+ });+ },+ ).get("/:assetId", apiKeyScopeMiddleware("assets", "read"), async (c) => {const assetId = c.req.param("assetId");diff --git a/packages/e2e_tests/tests/api/assets.test.ts b/packages/e2e_tests/tests/api/assets.test.tsindex c5352928..c913746c 100644--- a/packages/e2e_tests/tests/api/assets.test.ts+++ b/packages/e2e_tests/tests/api/assets.test.ts@@ -49,6 +49,36 @@ describe("Assets API", () => {expect(resp.status).toBe(200);});+ it("should create a signed URL that retrieves an asset", async () => {+ const uploadResponse = await uploadTestAsset(+ apiKey,+ port,+ createTestPdfFile(),+ );++ const { data, response } = await client.GET(+ "/assets/{assetId}/signed-url",+ {+ params: {+ path: {+ assetId: uploadResponse.assetId,+ },+ },+ },+ );++ expect(response.status).toBe(200);+ expect(data?.assetId).toBe(uploadResponse.assetId);+ expect(data?.signedUrl).toContain(+ `/api/public/assets/${uploadResponse.assetId}?token=`,+ );+ expect(new Date(data!.expiresAt).getTime()).toBeGreaterThan(Date.now());++ const assetResponse = await fetch(data!.signedUrl);+ expect(assetResponse.status).toBe(200);+ expect(assetResponse.headers.get("content-type")).toBe("application/pdf");+ });+it("should require assets:readwrite to upload an asset", async () => {const scopedApiKey = await createTestUser(["assets:read"]);const formData = new FormData();diff --git a/packages/open-api/karakeep-openapi-spec.json b/packages/open-api/karakeep-openapi-spec.jsonindex 2eb6e093..5d24dd84 100644--- a/packages/open-api/karakeep-openapi-spec.json+++ b/packages/open-api/karakeep-openapi-spec.json@@ -667,6 +667,30 @@"fileName"]},+ "SignedAssetUrl": {+ "type": "object",+ "properties": {+ "assetId": {+ "type": "string",+ "description": "The unique identifier of the asset."+ },+ "signedUrl": {+ "type": "string",+ "format": "uri",+ "description": "The temporary URL for downloading the asset."+ },+ "expiresAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the signed URL expires, in ISO 8601 format."+ }+ },+ "required": [+ "assetId",+ "signedUrl",+ "expiresAt"+ ]+ },"Feed": {"type": "object","properties": {@@ -3988,6 +4012,49 @@}}},+ "/assets/{assetId}/signed-url": {+ "get": {+ "operationId": "getAssetSignedUrl",+ "description": "Generate a temporary signed URL that can be used to download an asset without sending an API key.",+ "summary": "Get a signed asset URL",+ "tags": [+ "Assets"+ ],+ "security": [+ {+ "bearerAuth": []+ }+ ],+ "parameters": [+ {+ "$ref": "#/components/parameters/AssetId"+ }+ ],+ "responses": {+ "200": {+ "description": "A temporary signed URL for downloading the asset and its expiration time.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SignedAssetUrl"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized — the Bearer token is missing, invalid, or expired.",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string",+ "example": "Unauthorized"+ }+ }+ }+ }+ }+ }+ },"/admin/users/{userId}": {"put": {"operationId": "adminUpdateUser",diff --git a/packages/open-api/lib/assets.ts b/packages/open-api/lib/assets.tsindex da24f928..f9e1e32b 100644--- a/packages/open-api/lib/assets.ts+++ b/packages/open-api/lib/assets.ts@@ -94,3 +94,43 @@ registry.registerPath({401: UnauthorizedResponse,},});++registry.registerPath({+ operationId: "getAssetSignedUrl",+ method: "get",+ path: "/assets/{assetId}/signed-url",+ description:+ "Generate a temporary signed URL that can be used to download an asset without sending an API key.",+ summary: "Get a signed asset URL",+ tags: ["Assets"],+ security: [{ [BearerAuth.name]: [] }],+ request: {+ params: z.object({ assetId: AssetIdSchema }),+ },+ responses: {+ 200: {+ description:+ "A temporary signed URL for downloading the asset and its expiration time.",+ content: {+ "application/json": {+ schema: z+ .object({+ assetId: z+ .string()+ .describe("The unique identifier of the asset."),+ signedUrl: z+ .string()+ .url()+ .describe("The temporary URL for downloading the asset."),+ expiresAt: z+ .string()+ .datetime()+ .describe("When the signed URL expires, in ISO 8601 format."),+ })+ .openapi("SignedAssetUrl"),+ },+ },+ },+ 401: UnauthorizedResponse,+ },+});diff --git a/packages/sdk/src/karakeep-api.d.ts b/packages/sdk/src/karakeep-api.d.tsindex 5d689c5f..bf042423 100644--- a/packages/sdk/src/karakeep-api.d.ts+++ b/packages/sdk/src/karakeep-api.d.ts@@ -524,6 +524,26 @@ export interface paths {patch?: never;trace?: never;};+ "/assets/{assetId}/signed-url": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Get a signed asset URL+ * @description Generate a temporary signed URL that can be used to download an asset without sending an API key.+ */+ get: operations["getAssetSignedUrl"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/admin/users/{userId}": {parameters: {query?: never;@@ -783,9 +803,16 @@ export interface components {* @example ieidlxygmwj87oxz5hxttoc8*/FeedId: string;+ PaginatedBookmarks: {+ bookmarks: components["schemas"]["Bookmark"][];+ /** @description Cursor for the next page, or null if no more results. */+ nextCursor: string | null;+ };Bookmark: {id: string;+ /** Format: date-time */createdAt: string;+ /** Format: date-time */modifiedAt: string | null;title?: string | null;archived: boolean;@@ -833,12 +860,15 @@ export interface components {favicon?: string | null;htmlContent?: string | null;contentAssetId?: string | null;+ /** Format: date-time */crawledAt?: string | null;/** @enum {string|null} */crawlStatus?: "success" | "failure" | "pending" | null;author?: string | null;publisher?: string | null;+ /** Format: date-time */datePublished?: string | null;+ /** Format: date-time */dateModified?: string | null;}| {@@ -881,11 +911,6 @@ export interface components {fileName?: string | null;}[];};- PaginatedBookmarks: {- bookmarks: components["schemas"]["Bookmark"][];- /** @description Cursor for the next page, or null if no more results. */- nextCursor: string | null;- };/** @description Cursor from a previous response to fetch the next page. */Cursor: string;Error: {@@ -924,6 +949,7 @@ export interface components {note: string | null;id: string;userId: string;+ /** Format: date-time */createdAt: string;};Tag: {@@ -950,7 +976,20 @@ export interface components {/** @description The original file name of the uploaded file. */fileName: string;};- "File to be uploaded": unknown;+ SignedAssetUrl: {+ /** @description The unique identifier of the asset. */+ assetId: string;+ /**+ * Format: uri+ * @description The temporary URL for downloading the asset.+ */+ signedUrl: string;+ /**+ * Format: date-time+ * @description When the signed URL expires, in ISO 8601 format.+ */+ expiresAt: string;+ };Feed: {id: string;name: string;@@ -974,12 +1013,19 @@ export interface components {};responses: never;parameters: {+ /** @description The unique identifier of the bookmark. */BookmarkId: components["schemas"]["BookmarkId"];+ /** @description The unique identifier of the list. */ListId: components["schemas"]["ListId"];+ /** @description The unique identifier of the tag. */TagId: components["schemas"]["TagId"];+ /** @description The unique identifier of the highlight. */HighlightId: components["schemas"]["HighlightId"];+ /** @description The unique identifier of the asset. */AssetId: components["schemas"]["AssetId"];+ /** @description The unique identifier of the backup. */BackupId: components["schemas"]["BackupId"];+ /** @description The unique identifier of the feed. */FeedId: components["schemas"]["FeedId"];};requestBodies: never;@@ -1046,7 +1092,8 @@ export interface operations {favourited?: boolean;note?: string;summary?: string;- createdAt?: string | null;+ /** Format: date-time */+ createdAt?: string;/** @enum {string} */crawlPriority?: "low" | "normal";importSessionId?: string;@@ -1208,6 +1255,7 @@ export interface operations {};header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1248,6 +1296,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1286,6 +1335,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1299,13 +1349,16 @@ export interface operations {summary?: string | null;note?: string;title?: string | null;- createdAt?: string | null;+ /** Format: date-time */+ createdAt?: string;/** Format: uri */url?: string;description?: string | null;author?: string | null;publisher?: string | null;+ /** Format: date-time */datePublished?: string | null;+ /** Format: date-time */dateModified?: string | null;text?: string | null;assetContent?: string | null;@@ -1321,7 +1374,9 @@ export interface operations {content: {"application/json": {id: string;+ /** Format: date-time */createdAt: string;+ /** Format: date-time */modifiedAt: string | null;title?: string | null;archived: boolean;@@ -1374,6 +1429,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1388,7 +1444,9 @@ export interface operations {content: {"application/json": {id: string;+ /** Format: date-time */createdAt: string;+ /** Format: date-time */modifiedAt: string | null;title?: string | null;archived: boolean;@@ -1441,6 +1499,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1498,6 +1557,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1555,6 +1615,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1597,6 +1658,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1639,6 +1701,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -1721,7 +1784,9 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];+ /** @description The unique identifier of the asset. */assetId: components["parameters"]["AssetId"];};cookie?: never;@@ -1768,7 +1833,9 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];+ /** @description The unique identifier of the asset. */assetId: components["parameters"]["AssetId"];};cookie?: never;@@ -1892,6 +1959,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];};cookie?: never;@@ -1932,6 +2000,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];};cookie?: never;@@ -1970,6 +2039,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];};cookie?: never;@@ -2031,6 +2101,7 @@ export interface operations {};header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];};cookie?: never;@@ -2071,7 +2142,9 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -2110,7 +2183,9 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the list. */listId: components["parameters"]["ListId"];+ /** @description The unique identifier of the bookmark. */bookmarkId: components["parameters"]["BookmarkId"];};cookie?: never;@@ -2236,6 +2311,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the tag. */tagId: components["parameters"]["TagId"];};cookie?: never;@@ -2276,6 +2352,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the tag. */tagId: components["parameters"]["TagId"];};cookie?: never;@@ -2314,6 +2391,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the tag. */tagId: components["parameters"]["TagId"];};cookie?: never;@@ -2373,6 +2451,7 @@ export interface operations {};header?: never;path: {+ /** @description The unique identifier of the tag. */tagId: components["parameters"]["TagId"];};cookie?: never;@@ -2510,6 +2589,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the highlight. */highlightId: components["parameters"]["HighlightId"];};cookie?: never;@@ -2550,6 +2630,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the highlight. */highlightId: components["parameters"]["HighlightId"];};cookie?: never;@@ -2590,6 +2671,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the highlight. */highlightId: components["parameters"]["HighlightId"];};cookie?: never;@@ -2762,7 +2844,11 @@ export interface operations {requestBody?: {content: {"multipart/form-data": {- file: components["schemas"]["File to be uploaded"];+ /**+ * Format: binary+ * @description File to be uploaded+ */+ file: string;};};};@@ -2792,6 +2878,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the asset. */assetId: components["parameters"]["AssetId"];};cookie?: never;@@ -2816,11 +2903,44 @@ export interface operations {};};};+ getAssetSignedUrl: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description The unique identifier of the asset. */+ assetId: components["parameters"]["AssetId"];+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description A temporary signed URL for downloading the asset and its expiration time. */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["SignedAssetUrl"];+ };+ };+ /** @description Unauthorized — the Bearer token is missing, invalid, or expired. */+ 401: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "text/plain": string;+ };+ };+ };+ };adminUpdateUser: {parameters: {query?: never;header?: never;path: {+ /** @description The ID of the user to update. */userId: string;};cookie?: never;@@ -3083,6 +3203,7 @@ export interface operations {id: string;userId: string;assetId: string | null;+ /** Format: date-time */createdAt: string;size: number;bookmarkCount: number;@@ -3123,6 +3244,7 @@ export interface operations {id: string;userId: string;assetId: string | null;+ /** Format: date-time */createdAt: string;size: number;bookmarkCount: number;@@ -3148,6 +3270,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the backup. */backupId: components["parameters"]["BackupId"];};cookie?: never;@@ -3164,6 +3287,7 @@ export interface operations {id: string;userId: string;assetId: string | null;+ /** Format: date-time */createdAt: string;size: number;bookmarkCount: number;@@ -3198,6 +3322,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the backup. */backupId: components["parameters"]["BackupId"];};cookie?: never;@@ -3236,6 +3361,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the backup. */backupId: components["parameters"]["BackupId"];};cookie?: never;@@ -3248,7 +3374,7 @@ export interface operations {[name: string]: unknown;};content: {- "application/zip": unknown;+ "application/zip": string;};};/** @description Unauthorized — the Bearer token is missing, invalid, or expired. */@@ -3357,6 +3483,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the feed. */feedId: components["parameters"]["FeedId"];};cookie?: never;@@ -3397,6 +3524,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the feed. */feedId: components["parameters"]["FeedId"];};cookie?: never;@@ -3435,6 +3563,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the feed. */feedId: components["parameters"]["FeedId"];};cookie?: never;@@ -3486,6 +3615,7 @@ export interface operations {query?: never;header?: never;path: {+ /** @description The unique identifier of the feed. */feedId: components["parameters"]["FeedId"];};cookie?: never;