UNPKG

@ankimcp/anki-mcp-server

Version:

Model Context Protocol server for Anki - enables AI assistants to interact with your Anki flashcards

191 lines • 10.3 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var UpdateNoteFieldsTool_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.UpdateNoteFieldsTool = void 0; const common_1 = require("@nestjs/common"); const microservices_1 = require("@nestjs/microservices"); const mcp_nest_1 = require("@rekog/mcp-nest"); const zod_1 = require("zod"); const anki_connect_client_1 = require("../../../clients/anki-connect.client.js"); const anki_utils_1 = require("../../../utils/anki.utils.js"); const media_validation_utils_1 = require("../../../utils/media-validation.utils.js"); let UpdateNoteFieldsTool = UpdateNoteFieldsTool_1 = class UpdateNoteFieldsTool { ankiClient; logger = new common_1.Logger(UpdateNoteFieldsTool_1.name); constructor(ankiClient) { this.ankiClient = ankiClient; } async updateNoteFields({ note, }) { try { const fieldCount = Object.keys(note.fields).length; this.logger.log(`Updating ${fieldCount} field(s) for note ID: ${note.id}`); if (fieldCount === 0) { return (0, anki_utils_1.createErrorResponse)(new Error("No fields provided for update"), { noteId: note.id, hint: "No fields were given; an update needs at least one field", }); } if (note.audio) { const urlConfig = (0, media_validation_utils_1.getMediaUrlConfigFromEnv)(); for (const audioItem of note.audio) { const { hostname, resolvedIp } = await (0, media_validation_utils_1.validateMediaUrl)(audioItem.url, urlConfig); this.logger.warn(`updateNoteFields audio URL validation: hostname="${hostname}", resolvedIp="${resolvedIp}"`); audioItem.filename = (0, media_validation_utils_1.sanitizeMediaFilename)(audioItem.filename); } } if (note.picture) { const urlConfig = (0, media_validation_utils_1.getMediaUrlConfigFromEnv)(); for (const pictureItem of note.picture) { const { hostname, resolvedIp } = await (0, media_validation_utils_1.validateMediaUrl)(pictureItem.url, urlConfig); this.logger.warn(`updateNoteFields picture URL validation: hostname="${hostname}", resolvedIp="${resolvedIp}"`); pictureItem.filename = (0, media_validation_utils_1.sanitizeMediaFilename)(pictureItem.filename); } } const notesInfo = await this.ankiClient.invoke("notesInfo", { notes: [note.id], }); if (!notesInfo || notesInfo.length === 0 || !notesInfo[0]) { return (0, anki_utils_1.createErrorResponse)(new Error("Note not found"), { noteId: note.id, hint: "The note ID is invalid or the note has been deleted. findNotes returns valid note IDs.", }); } const currentNote = notesInfo[0]; const modelName = currentNote.modelName; const existingFields = Object.keys(currentNote.fields); const invalidFields = Object.keys(note.fields).filter((field) => !existingFields.includes(field)); if (invalidFields.length > 0) { return (0, anki_utils_1.createErrorResponse)(new Error(`Invalid fields for model "${modelName}"`), { noteId: note.id, modelName, invalidFields, validFields: existingFields, hint: `These fields don't exist in the "${modelName}" model. modelFieldNames lists the valid fields.`, }); } const updateParams = { note: { id: note.id, fields: note.fields, }, }; if (note.audio) { updateParams.note.audio = note.audio; } if (note.picture) { updateParams.note.picture = note.picture; } await this.ankiClient.invoke("updateNoteFields", updateParams); this.logger.log(`Successfully updated note ID: ${note.id}`); const updatedFields = Object.keys(note.fields); return { success: true, noteId: note.id, updatedFields, fieldCount, modelName, message: `Successfully updated ${fieldCount} field${fieldCount === 1 ? "" : "s"} in note`, cssNote: "HTML content is preserved. Model CSS styling remains unchanged.", warning: "Changes do not persist if the note was open in Anki's browser during the update.", hint: "notesInfo returns the note's current field values.", }; } catch (error) { this.logger.error("Failed to update note fields", error); if (error instanceof Error) { if (error.message.includes("not found")) { return (0, anki_utils_1.createErrorResponse)(error, { noteId: note.id, hint: "Note not found. It may have been deleted.", }); } if (error.message.includes("field")) { return (0, anki_utils_1.createErrorResponse)(error, { noteId: note.id, providedFields: Object.keys(note.fields), hint: "Field names have to match exactly (case-sensitive). notesInfo shows the note's current fields.", }); } } return (0, anki_utils_1.createErrorResponse)(error, { noteId: note.id, hint: "This can happen when Anki is not running. Separately, an update to a note that is open in Anki's browser does not persist", }); } } }; exports.UpdateNoteFieldsTool = UpdateNoteFieldsTool; __decorate([ (0, mcp_nest_1.Tool)({ name: "updateNoteFields", description: "Update the fields of an existing note. The given fields' current content is overwritten (HTML supported; the note type's CSS is not touched) and the change is not recorded in Anki's undo history. " + "Optional audio/picture items are downloaded from their URLs and appended to the listed fields as [sound:...] / <img> tags, so repeating a call with media appends them again unless those fields are also overwritten. " + "Known AnkiConnect issue: if the note is open in Anki's Browse window, the call reports success but the fields are not saved.", parameters: zod_1.z.object({ note: zod_1.z.object({ id: zod_1.z .number() .describe("The ID of the note to update. Get this from findNotes or notesInfo."), fields: zod_1.z .record(zod_1.z.string(), zod_1.z.string()) .describe("Fields to update with new content. Only include fields you want to change. " + 'HTML content is supported. Example: {"Front": "<b>New question</b>", "Back": "New answer"}'), audio: zod_1.z .array(zod_1.z.object({ url: zod_1.z.string().describe("URL of the audio file"), filename: zod_1.z.string().describe("Filename to save as"), fields: zod_1.z.array(zod_1.z.string()).describe("Fields to add audio to"), })) .optional() .describe("Optional audio files to add to the note"), picture: zod_1.z .array(zod_1.z.object({ url: zod_1.z.string().describe("URL of the image"), filename: zod_1.z.string().describe("Filename to save as"), fields: zod_1.z.array(zod_1.z.string()).describe("Fields to add image to"), })) .optional() .describe("Optional images to add to the note"), }), }), outputSchema: zod_1.z.object({ success: zod_1.z.boolean(), noteId: zod_1.z.number(), updatedFields: zod_1.z.array(zod_1.z.string()), fieldCount: zod_1.z.number(), modelName: zod_1.z.string(), message: zod_1.z.string(), cssNote: zod_1.z.string(), warning: zod_1.z.string(), hint: zod_1.z.string(), }), annotations: { title: "Update Note Fields", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true, }, }), __param(0, (0, microservices_1.Payload)()), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], UpdateNoteFieldsTool.prototype, "updateNoteFields", null); exports.UpdateNoteFieldsTool = UpdateNoteFieldsTool = UpdateNoteFieldsTool_1 = __decorate([ (0, mcp_nest_1.McpController)(), __metadata("design:paramtypes", [anki_connect_client_1.AnkiConnectClient]) ], UpdateNoteFieldsTool); //# sourceMappingURL=update-note-fields.tool.js.map