Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(mcp): add tools to import, list, rename and delete media

spacesdrive99d27a26fa27
diff --git a/backend/mcp/registry.ts b/backend/mcp/registry.ts
index 1c142ca..f4cd45f 100644
--- a/backend/mcp/registry.ts
+++ b/backend/mcp/registry.ts
@@ -1,11 +1,12 @@
import { ANALYTICS_TOOLS } from './tools/analyticsTools.ts';
+import { MEDIA_TOOLS } from './tools/mediaTools.ts';
import { SCHEDULED_POST_TOOLS } from './tools/scheduledPostTools.ts';
import { SETTINGS_TOOLS } from './tools/settingsTools.ts';
import type { AnyTool } from './tool.ts';
import type { ServerIdentity } from '../lib/mcp/protocol.ts';
// every tool the MCP endpoint offers, in the order tools/list returns them; read-only callers see only the read tools
-export const MCP_TOOLS: readonly AnyTool[] = [...ANALYTICS_TOOLS, ...SETTINGS_TOOLS, ...SCHEDULED_POST_TOOLS];
+export const MCP_TOOLS: readonly AnyTool[] = [...ANALYTICS_TOOLS, ...SETTINGS_TOOLS, ...MEDIA_TOOLS, ...SCHEDULED_POST_TOOLS];
export function mcpServerIdentity(version: string): ServerIdentity {
return {
diff --git a/backend/mcp/tools/mediaTools.ts b/backend/mcp/tools/mediaTools.ts
new file mode 100644
index 0000000..9c5813a
--- /dev/null
+++ b/backend/mcp/tools/mediaTools.ts
@@ -0,0 +1,73 @@
+import { READ_ONLY, defineTool } from '../tool.ts';
+import { idProperty, objectSchema, pageOf, pageProperties, parsePage, requiredId, withConfirmation } from '../schemas.ts';
+import { MAX_MEDIA_LABEL_LENGTH, parseMediaImport, parseMediaLabel } from '../../validators/mediaValidators.ts';
+import type { Page } from '../schemas.ts';
+import type { MediaImport } from '../../services/mediaService.ts';
+
+const labelProperty = { type: 'string', maxLength: MAX_MEDIA_LABEL_LENGTH, description: 'A short name to find the file by later' };
+
+export const listMedia = defineTool<{ page: Page }>({
+ name: 'list_media',
+ title: 'List media',
+ description: 'Lists the images and videos you imported into Twiligent, newest first, with the public https address to schedule a post with.',
+ inputSchema: objectSchema({ ...pageProperties }),
+ annotations: READ_ONLY,
+ permission: 'read',
+ parse: args => ({ page: parsePage(args) }),
+ async run({ page }, { services, principal }) {
+ const { items, nextCursor, total } = pageOf(await services.media.list(principal.userId), page);
+ return { media: items, nextCursor, total };
+ },
+});
+
+export const importMediaFromUrl = defineTool<MediaImport>({
+ name: 'import_media_from_url',
+ title: 'Import media from a URL',
+ description: 'Copies an image or video from a public https address into the instance\'s Cloudinary storage, so it has a stable address Instagram can publish from. Cloudinary downloads the file, not Twiligent. Large videos may take longer than a tool call allows; Cloudinary\'s plan limits apply (100 MB per video on the free plan).',
+ inputSchema: objectSchema({
+ url: { type: 'string', format: 'uri', maxLength: 2048, description: 'The public https address of the file' },
+ resourceType: { type: 'string', enum: ['image', 'video'] },
+ label: labelProperty,
+ }, ['url', 'resourceType']),
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ permission: 'write',
+ parse: args => parseMediaImport(args),
+ async run(input, { services, principal }) {
+ return { media: await services.media.importFromUrl(principal.userId, input) };
+ },
+});
+
+export const updateMedia = defineTool<{ mediaId: string; label: string }>({
+ name: 'update_media',
+ title: 'Rename media',
+ description: 'Changes the label of one of your imported files.',
+ inputSchema: objectSchema({ mediaId: idProperty('media'), label: labelProperty }, ['mediaId', 'label']),
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ permission: 'write',
+ parse: args => ({ mediaId: requiredId(args, 'mediaId', 'media'), label: parseMediaLabel(args) }),
+ async run({ mediaId, label }, { services, principal }) {
+ return { media: await services.media.updateLabel(principal.userId, mediaId, label) };
+ },
+});
+
+export const deleteMedia = defineTool<{ mediaId: string }>({
+ name: 'delete_media',
+ title: 'Delete media',
+ description: 'Deletes one of your imported files. A post already scheduled with its address will fail to publish. When the instance has a Cloudinary API secret the file is deleted from Cloudinary too; otherwise only Twiligent\'s record goes and the result says so. Asks for a confirmation first.',
+ inputSchema: withConfirmation(objectSchema({ mediaId: idProperty('media') }, ['mediaId'])),
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
+ permission: 'write',
+ needsConfirmation: () => true,
+ describe: ({ mediaId }) => `Delete media ${mediaId}; a post scheduled with it would fail to publish.`,
+ parse: args => ({ mediaId: requiredId(args, 'mediaId', 'media') }),
+ async run({ mediaId }, { services, principal }) {
+ const { removedFromCloudinary } = await services.media.remove(principal.userId, mediaId);
+ return {
+ deleted: mediaId,
+ removedFromCloudinary,
+ note: removedFromCloudinary ? undefined : 'The file is still on Cloudinary: this instance has no Cloudinary API secret to delete it with. Its address keeps working until the owner deletes it in the Cloudinary console.',
+ };
+ },
+});
+
+export const MEDIA_TOOLS = [listMedia, importMediaFromUrl, updateMedia, deleteMedia];
diff --git a/backend/tests/mcp/mediaTools.test.ts b/backend/tests/mcp/mediaTools.test.ts
new file mode 100644
index 0000000..d75977b
--- /dev/null
+++ b/backend/tests/mcp/mediaTools.test.ts
@@ -0,0 +1,55 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { MEDIA_TOOLS, deleteMedia, importMediaFromUrl, listMedia, updateMedia } from '../../mcp/tools/mediaTools.ts';
+import { ValidationError } from '../../lib/errors.ts';
+import type { Services } from '../../container.ts';
+import type { ToolContext } from '../../mcp/tool.ts';
+import type { MediaService } from '../../services/mediaService.ts';
+import type { MediaAsset } from '../../../shared/types/media.ts';
+
+function asset(id: string): MediaAsset {
+ return { id, resourceType: 'image', url: `https://res.cloudinary.com/demo/image/upload/${id}.jpg`, format: 'jpg', bytes: 1, width: 1, height: 1, durationSeconds: null, label: '', createdAt: '2026-11-05T00:00:00Z' };
+}
+
+function context(canDelete: boolean): ToolContext & { removed: string[] } {
+ const removed: string[] = [];
+ const media: Pick<MediaService, 'list' | 'remove'> = {
+ list: async userId => (userId === 'user-1' ? [asset('a'), asset('b'), asset('c')] : []),
+ async remove(_userId, id) {
+ removed.push(id);
+ return { removedFromCloudinary: canDelete };
+ },
+ };
+ return { services: { media } as unknown as Services, principal: { userId: 'user-1', permission: 'write', via: 'token:t1' }, removed };
+}
+
+test('only listing is a read tool, and only deleting asks for a confirmation', () => {
+ assert.deepEqual(MEDIA_TOOLS.map(tool => [tool.name, tool.permission]), [
+ ['list_media', 'read'], ['import_media_from_url', 'write'], ['update_media', 'write'], ['delete_media', 'write'],
+ ]);
+ assert.equal(deleteMedia.needsConfirmation?.({ mediaId: 'a' }), true);
+ assert.equal(importMediaFromUrl.needsConfirmation, undefined);
+ assert.equal(updateMedia.annotations.destructiveHint, false);
+});
+
+test('listing pages through the caller\'s media', async () => {
+ const page = await listMedia.run(listMedia.parse({ limit: 2 }), context(false)) as { media: MediaAsset[]; nextCursor: string; total: number };
+ assert.deepEqual(page.media.map(item => item.id), ['a', 'b']);
+ assert.equal(page.nextCursor, '2');
+ assert.equal(page.total, 3);
+});
+
+test('a delete without the Cloudinary secret says the file is still on Cloudinary', async () => {
+ const ctx = context(false);
+ const result = await deleteMedia.run({ mediaId: 'a' }, ctx) as { removedFromCloudinary: boolean; note?: string };
+ assert.deepEqual(ctx.removed, ['a']);
+ assert.equal(result.removedFromCloudinary, false);
+ assert.match(result.note ?? '', /still on Cloudinary/);
+ const full = await deleteMedia.run({ mediaId: 'b' }, context(true)) as { note?: string };
+ assert.equal(full.note, undefined);
+});
+
+test('imports refuse anything but a public https address before calling the service', () => {
+ assert.throws(() => importMediaFromUrl.parse({ url: 'http://example.com/a.jpg', resourceType: 'image' }), ValidationError);
+ assert.throws(() => updateMedia.parse({ label: 'x' }), ValidationError);
+});