@ankimcp/anki-mcp-server
Version:
Model Context Protocol server for Anki - enables AI assistants to interact with your Anki flashcards
290 lines • 15.4 kB
JavaScript
;
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 CollectionStatsTool_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CollectionStatsTool = 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 card_states_utils_1 = require("../../../../utils/card-states.utils.js");
const deck_hierarchy_utils_1 = require("../../../../utils/deck-hierarchy.utils.js");
const stats_utils_1 = require("../../../../utils/stats.utils.js");
let CollectionStatsTool = CollectionStatsTool_1 = class CollectionStatsTool {
ankiClient;
logger = new common_1.Logger(CollectionStatsTool_1.name);
constructor(ankiClient) {
this.ankiClient = ankiClient;
}
async execute(params) {
try {
const { ease_buckets = [2.0, 2.5, 3.0], interval_buckets = [7, 21, 90] } = params;
this.logger.log("Getting collection-wide statistics");
this.logger.log("Fetching deck names and IDs...");
const deckNamesAndIds = await this.ankiClient.invoke("deckNamesAndIds", {});
const deckNames = deckNamesAndIds ? Object.keys(deckNamesAndIds) : [];
if (deckNames.length === 0) {
this.logger.log("No decks found in collection");
const result = {
total_decks: 0,
counts: {
total: 0,
new: 0,
learning: 0,
review: 0,
other: 0,
},
states: (0, card_states_utils_1.emptyCardStateCounts)(),
ease: (0, stats_utils_1.computeDistribution)([], { boundaries: ease_buckets }),
intervals: (0, stats_utils_1.computeDistribution)([], {
boundaries: interval_buckets,
unitSuffix: "d",
}),
per_deck: [],
};
return result;
}
this.logger.log(`Found ${deckNames.length} decks in collection`);
this.logger.log("Fetching statistics for all decks...");
const deckStatsResponse = await this.ankiClient.invoke("getDeckStats", {
decks: deckNames,
});
if (!deckStatsResponse || typeof deckStatsResponse !== "object") {
throw new Error("Invalid getDeckStats response");
}
const perDeckOwnTotal = new Map();
const perDeckStats = new Map();
const missingDecks = [];
for (const deckName of deckNames) {
const deckId = deckNamesAndIds[deckName];
const deckStats = deckId != null ? deckStatsResponse[String(deckId)] : undefined;
if (!deckStats) {
missingDecks.push(deckName);
perDeckOwnTotal.set(deckName, 0);
continue;
}
perDeckOwnTotal.set(deckName, deckStats.total_in_deck ?? 0);
perDeckStats.set(deckName, deckStats);
}
const per_deck = [];
for (const deckName of deckNames) {
const stats = perDeckStats.get(deckName);
const newCount = stats?.new_count ?? 0;
const learning = stats?.learn_count ?? 0;
const review = stats?.review_count ?? 0;
const total = (0, deck_hierarchy_utils_1.rollupDeckTotal)(deckName, perDeckOwnTotal);
const other = Math.max(0, total - newCount - learning - review);
per_deck.push({
deck: deckName,
total,
new: newCount,
learning,
review,
other,
});
}
if (missingDecks.length > 0) {
this.logger.warn(`getDeckStats did not return stats for ${missingDecks.length} deck(s): ` +
`${missingDecks.join(", ")}. Filled with zeros.`);
}
const rootDeckNames = new Set((0, deck_hierarchy_utils_1.getRootDeckNames)(deckNames));
const counts = {
total: 0,
new: 0,
learning: 0,
review: 0,
other: 0,
};
for (const entry of per_deck) {
if (!rootDeckNames.has(entry.deck))
continue;
counts.total += entry.total;
counts.new += entry.new;
counts.learning += entry.learning;
counts.review += entry.review;
counts.other += entry.other;
}
this.logger.log(`Aggregated counts: ${counts.total} total cards across ${rootDeckNames.size} root deck(s) ` +
`(${deckNames.length} total decks including children)`);
this.logger.log("Finding all cards in collection...");
const cardIds = await this.ankiClient.invoke("findCards", {
query: "deck:*",
});
if (!cardIds || cardIds.length === 0) {
this.logger.log("No cards found via findCards; reporting getDeckStats counts with zeroed states");
const result = {
total_decks: deckNames.length,
counts,
states: (0, card_states_utils_1.emptyCardStateCounts)(),
ease: (0, stats_utils_1.computeDistribution)([], { boundaries: ease_buckets }),
intervals: (0, stats_utils_1.computeDistribution)([], {
boundaries: interval_buckets,
unitSuffix: "d",
}),
per_deck,
};
return result;
}
this.logger.log(`Found ${cardIds.length} cards in collection`);
this.logger.log("Counting cards by state...");
const states = await (0, card_states_utils_1.fetchCardStateCounts)(this.ankiClient);
this.logger.log(`Card states: ${states.new} new, ${states.learning} learning, ` +
`${states.review} review, ${states.suspended} suspended, ` +
`${states.buried} buried`);
this.logger.log(`Fetching ease factors for ${cardIds.length} cards...`);
const easeFactorsRaw = await this.ankiClient.invoke("getEaseFactors", {
cards: cardIds,
});
if (!Array.isArray(easeFactorsRaw)) {
throw new Error("Invalid getEaseFactors response: expected array");
}
const easeValues = easeFactorsRaw
.map((e) => e / 1000)
.filter((e) => e > 0);
this.logger.log(`Processed ${easeValues.length} ease values`);
this.logger.log(`Fetching intervals for ${cardIds.length} cards...`);
const intervalsRaw = await this.ankiClient.invoke("getIntervals", {
cards: cardIds,
});
if (!Array.isArray(intervalsRaw)) {
throw new Error("Invalid getIntervals response: expected array");
}
const intervalValues = intervalsRaw.filter((i) => i > 0);
this.logger.log(`Processed ${intervalValues.length} interval values`);
this.logger.log("Computing distributions...");
const ease = (0, stats_utils_1.computeDistribution)(easeValues, {
boundaries: ease_buckets,
});
const intervals = (0, stats_utils_1.computeDistribution)(intervalValues, {
boundaries: interval_buckets,
unitSuffix: "d",
});
const result = {
total_decks: deckNames.length,
counts,
states,
ease,
intervals,
per_deck,
};
this.logger.log(`Successfully retrieved collection statistics: ${deckNames.length} decks, ` +
`${counts.total} total cards, ${ease.count} cards with ease values, ` +
`${intervals.count} review cards`);
return result;
}
catch (error) {
this.logger.error("Failed to get collection statistics", error);
return (0, anki_utils_1.createErrorResponse)(error, {
hint: "This can happen when Anki is not running or AnkiConnect is not reachable",
});
}
}
};
exports.CollectionStatsTool = CollectionStatsTool;
__decorate([
(0, mcp_nest_1.Tool)({
name: "collection_stats",
description: "Get aggregated statistics across all decks in the collection including card counts, ease factor distribution, and interval distribution. " +
"Returns TWO different views that answer different questions: " +
"`counts` and `per_deck` are today's study queue as shown in Anki's deck browser (cards DUE TODAY, capped by each deck's daily new/review limits, suspended/buried excluded); " +
"`states` is the true number of cards in each state (new / learning / review / suspended / buried) across the whole collection, ignoring due dates and daily limits. " +
'To answer "how many cards do I have" use `states`; to answer "what will I study today" use `counts`. ' +
"Per-deck counts are rolled up over descendants (a parent deck includes its children); collection-level `counts` sum the ROOT decks only to avoid double-counting children. " +
"`states` is collection-wide only (it costs 5 additional Anki searches per call) — call the `deckStats` tool for a single deck's true state counts. " +
`For every deck and for the collection: ${card_states_utils_1.DUE_TREE_INVARIANT_NOTE} ` +
"Ease buckets and interval buckets can be customized to focus on specific ranges.",
parameters: zod_1.z.object({
ease_buckets: zod_1.z
.array(zod_1.z.number().positive())
.max(20)
.optional()
.default([2.0, 2.5, 3.0])
.refine((arr) => arr.length === 0 || arr.every((v, i, a) => i === 0 || v > a[i - 1]), {
message: "Bucket boundaries must be in ascending order",
})
.describe("Bucket boundaries for ease factor distribution. Default: [2.0, 2.5, 3.0]. " +
"Example: [2.0, 2.5, 3.0] creates buckets: <2.0, 2.0-2.5, 2.5-3.0, >3.0"),
interval_buckets: zod_1.z
.array(zod_1.z.number().positive())
.max(20)
.optional()
.default([7, 21, 90])
.refine((arr) => arr.length === 0 || arr.every((v, i, a) => i === 0 || v > a[i - 1]), {
message: "Bucket boundaries must be in ascending order",
})
.describe("Bucket boundaries for interval distribution in days. Default: [7, 21, 90]. " +
"Example: [7, 21, 90] creates buckets: <7d, 7-21d, 21-90d, >90d"),
}),
outputSchema: zod_1.z.object({
total_decks: zod_1.z.number(),
counts: (0, card_states_utils_1.dueTreeCountsSchema)({
scope: "the whole collection",
total: "Total cards in the collection, including suspended and buried. " +
"Computed as the sum of ROOT-deck rolled-up totals (decks without " +
"`::` in the name), which prevents double-counting children.",
note: "Summed over ROOT decks only (names without `::`) so that a " +
"parent's rollup is not added on top of its children.",
}),
states: (0, card_states_utils_1.cardStatesSchema)("the whole collection"),
ease: zod_1.z.object({
mean: zod_1.z.number(),
median: zod_1.z.number(),
min: zod_1.z.number(),
max: zod_1.z.number(),
count: zod_1.z.number(),
buckets: zod_1.z.record(zod_1.z.string(), zod_1.z.number()),
}),
intervals: zod_1.z.object({
mean: zod_1.z.number(),
median: zod_1.z.number(),
min: zod_1.z.number(),
max: zod_1.z.number(),
count: zod_1.z.number(),
buckets: zod_1.z.record(zod_1.z.string(), zod_1.z.number()),
}),
per_deck: zod_1.z
.array(zod_1.z.object({
deck: zod_1.z.string().describe('Full deck name, e.g. "German::Verbs".'),
...(0, card_states_utils_1.dueTreeCountsShape)("Total cards in this deck AND all of its descendants, " +
"including suspended and buried."),
}))
.describe("Per-deck breakdown of today's study queue — same due-today, " +
"daily-limit-capped semantics as `counts`, NOT card totals. One " +
"entry per deck; each entry's counts are rolled up over that " +
'deck\'s descendants (entry for "German" includes cards from ' +
'"German::Verbs"). Normally total === new + learning + review + ' +
"other per row, but `other` is clamped at 0 so the sum can exceed " +
"total in rare filtered-deck cases. Per-deck true state counts are " +
"not included here — call the `deckStats` tool for a specific deck."),
}),
annotations: {
title: "Collection Statistics",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
}),
__param(0, (0, microservices_1.Payload)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], CollectionStatsTool.prototype, "execute", null);
exports.CollectionStatsTool = CollectionStatsTool = CollectionStatsTool_1 = __decorate([
(0, mcp_nest_1.McpController)(),
__metadata("design:paramtypes", [anki_connect_client_1.AnkiConnectClient])
], CollectionStatsTool);
//# sourceMappingURL=collection-stats.tool.js.map