-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
325 lines (293 loc) · 8.55 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { YankiConnect } from "yanki-connect";
const client = new YankiConnect();
interface Card {
cardId: number;
question: string;
answer: string;
due: number;
}
/**
* Create an MCP server with capabilities for resources (to get Anki cards),
* and tools (to answer cards, create new cards and get cards).
*/
const server = new Server(
{
name: "anki-server",
version: "1.0.0",
},
{
capabilities: {
resources: {},
tools: {},
},
}
);
/**
* Handler for listing Anki cards as resources.
* Cards are exposed as a resource with:
* - An anki:// URI scheme plus a filter
* - JSON MIME type
* - All resources return a list of cards under different filters
*/
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "anki://search/deckcurrent",
mimeType: "application/json",
name: "Current Deck",
description: "Current Anki deck"
},
{
uri: "anki://search/isdue",
mimeType: "application/json",
name: "Due cards",
description: "Cards in review and learning waiting to be studied"
},
{
uri: "anki://search/isnew",
mimiType: "application/json",
name: "New cards",
description: "All unseen cards"
}
]
};
});
/**
* Filters Anki cards based on selected resource
*/
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const url = new URL(request.params.uri);
const query = url.pathname.split("/").pop();
if (!query) {
throw new Error("Invalid resource URI");
}
const cards = await findCardsAndOrder(query);
return {
contents: [{
uri: request.params.uri,
mimeType: "application/json",
text: JSON.stringify(cards)
}]
};
});
// Returns a list of cards ordered by due date
async function findCardsAndOrder(query: string): Promise<Card[]> {
const cardIds = await client.card.findCards({
query: formatQuery(query)
});
const cards: Card[] = (await client.card.cardsInfo({ cards: cardIds })).map(card => ({
cardId: card.cardId,
question: cleanWithRegex(card.question),
answer: cleanWithRegex(card.answer),
due: card.due
})).sort((a: Card, b: Card) => a.due - b.due);
return cards;
}
// Formats the uri to be a proper query
function formatQuery(query: string): string {
if (query.startsWith("deck")) {
return `deck:${query.slice(4)}`;
}
if (query.startsWith("is")) {
return `is:${query.slice(2)}`;
}
return query;
}
// Strip away formatting that isn't necessary
function cleanWithRegex(htmlString: string): string {
return htmlString
// Remove style tags and their content
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
// Replace divs with newlines
.replace(/<div[^>]*>/g, '\n')
// Remove all HTML tags
.replace(/<[^>]+>/g, ' ')
// Remove anki play tags
.replace(/\[anki:play:[^\]]+\]/g, '')
// Convert HTML entities
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
// Clean up whitespace but preserve newlines
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
.join('\n');
}
/**
* Handler that lists available tools.
*/
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "update_cards",
description: "After the user answers cards you've quizzed them on, use this tool to mark them answered and update their ease",
inputSchema: {
type: "object",
properties: {
answers: {
type: "array",
items: {
type: "object",
properties: {
cardId: {
type: "number",
description: "Id of the card to answer"
},
ease: {
type: "number",
description: "Ease of the card between 1 (Again) and 4 (Easy)"
}
}
}
}
},
}
},
{
name: "add_card",
description: "Create a new flashcard in Anki for the user. Must use HTML formatting only. IMPORTANT FORMATTING RULES:\n1. Must use HTML tags for ALL formatting - NO markdown\n2. Use <br> for ALL line breaks\n3. For code blocks, use <pre> with inline CSS styling\n4. Example formatting:\n - Line breaks: <br>\n - Code: <pre style=\"background-color: transparent; padding: 10px; border-radius: 5px;\">\n - Lists: <ol> and <li> tags\n - Bold: <strong>\n - Italic: <em>",
inputSchema: {
type: "object",
properties: {
front: {
type: "string",
description: "The front of the card. Must use HTML formatting only."
},
back: {
type: "string",
description: "The back of the card. Must use HTML formatting only."
}
},
required: ["front", "back"]
}
},
{
name: "get_due_cards",
description: "Returns a given number (num) of cards due for review.",
inputSchema: {
type: "object",
properties: {
num: {
type: "number",
description: "Number of due cards to get"
}
},
required: ["num"]
},
},
{
name: "get_new_cards",
description: "Returns a given number (num) of new and unseen cards.",
inputSchema: {
type: "object",
properties: {
num: {
type: "number",
description: "Number of new cards to get"
}
},
required: ["num"]
},
}
]
};
});
/**
* Handler for the update_cards, add_card, get_due_cards and get_new_cards tools.
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (!args) {
throw new Error(`No arguments provided for tool: ${name}`);
}
switch (name) {
case "update_cards": {
const answers = args.answers as { cardId: number; ease: number }[];
const result = await client.card.answerCards({ answers: answers });
const successfulCards = answers
.filter((_, index) => result[index])
.map(card => card.cardId);
const failedCards = answers.filter((_, index) => !result[index]);
if (failedCards.length > 0) {
const failedCardIds = failedCards.map(card => card.cardId);
throw new Error(`Failed to update cards with IDs: ${failedCardIds.join(', ')}`);
}
return {
content: [{
type: "text",
text: `Updated cards ${successfulCards.join(", ")}`
}]
};
}
case "add_card": {
const front = String(args.front);
const back = String(args.back);
const note = {
note: {
deckName: 'Default',
fields: {
Back: back,
Front: front,
},
modelName: 'Basic',
},
};
const noteId = await client.note.addNote(note);
const cardId = (await client.card.findCards({ query: `nid:${noteId}` }))[0];
return {
content: [{
type: "text",
text: `Created card with id ${cardId}`
}]
};
}
case "get_due_cards": {
const num = Number(args.num);
const cards = await findCardsAndOrder("is:due");
return {
content: [{
type: "text",
text: JSON.stringify(cards.slice(0, num))
}]
};
}
case "get_new_cards": {
const num = Number(args.num);
const cards = await findCardsAndOrder("is:new");
return {
content: [{
type: "text",
text: JSON.stringify(cards.slice(0, num))
}]
};
}
default:
throw new Error("Unknown tool");
}
});
/**
* Start the server using stdio transport.
* This allows the server to communicate via standard input/output streams.
*/
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch((error) => {
console.error("Server error:", error);
process.exit(1);
});