Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

Expose template and instruction management over MCP

tianma-if9ce9ffc0b0f9
diff --git a/README.md b/README.md
index 79d6fcbc..8f78dbbf 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ Repository file: [docs/openapi.json](docs/openapi.json).
## MCP
-Create an API token in **Profile** -> **MCP settings**, then give the token or full MCP configuration to your AI Agent. Once connected, the Agent can securely read, organize, and import notes within your account permissions. Repeating the same import will not create duplicate notes.
+Create an API token in **Profile** -> **MCP settings**, then give the token or full MCP configuration to your AI Agent. Once connected, the Agent can securely read, organize, and import notes within your account permissions. MCP also exposes full management of reusable note templates and AI instructions: agents can list, inspect, create, update, and delete both, create a note from a template, and restore missing built-in AI instructions. Template and instruction reads use the `read:memos` scope, while changes use `write:memos`. Repeating the same memo import will not create duplicate notes.
The Remote MCP endpoint supports the stateless `2026-07-28` protocol while retaining the handshake-based 2025 revisions for existing clients.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index fd9019ea..4485d220 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -199,7 +199,7 @@ https://你的域名/api/openapi.json
## MCP
-先在 EdgeEver 左下角 **个人中心** 的 **MCP 设置** 中创建 API Token,再将 Token 或完整 MCP 配置发送给 AI Agent。连接后,Agent 即可在你的授权范围内安全地读取、整理和导入笔记;重复执行同一导入任务也不会创建重复笔记。
+先在 EdgeEver 左下角 **个人中心** 的 **MCP 设置** 中创建 API Token,再将 Token 或完整 MCP 配置发送给 AI Agent。连接后,Agent 即可在你的授权范围内安全地读取、整理和导入笔记。MCP 也开放了完整的笔记模板与 AI 指令管理能力:Agent 可以列出、查看、新建、更新和删除模板与指令,也可以使用模板创建笔记、恢复缺失的内置指令。读取模板和指令需要 `read:memos` 权限,变更需要 `write:memos` 权限;重复执行同一笔记导入任务不会创建重复笔记。
Remote MCP 端点支持无状态的 `2026-07-28` 协议,同时继续兼容现有客户端使用的 2025 握手式协议版本。
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 689009b8..2125f254 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -11,6 +11,10 @@ import {
isSuspiciousMemoOverwrite,
isMemoEditBindingValid,
normalizeTags,
+ AiPromptTemplateCreateSchema,
+ AiPromptTemplateUpdateSchema,
+ TemplateCreateSchema,
+ TemplateUpdateSchema,
type MemoDetail,
type MemoEditSession,
type MemoRevision,
@@ -109,12 +113,18 @@ import {
type TokenScope,
} from "./request-auth";
import { registerTagRoutes } from "./tag-routes";
-import { registerTemplateRoutes } from "./template-routes";
+import { getMemoTemplate, listMemoTemplates, registerTemplateRoutes } from "./template-routes";
import { registerAuthRoutes, type UserRow } from "./auth-routes";
import { registerApiTokenRoutes, type ApiTokenRow } from "./api-token-routes";
import { registerObjectStorageRoutes } from "./object-storage-routes";
import { registerAiRoutes } from "./ai-routes";
import { registerAiPromptRoutes } from "./ai-prompt-routes";
+import {
+ getAiPromptTemplateRow,
+ listAiPromptTemplates,
+ mapAiPromptTemplateRow,
+} from "./ai-prompt-service";
+import { restoreMissingDefaultAiPrompts } from "./ai-prompt-seed";
import { registerResourceRoutes } from "./resource-routes";
import { registerSyncRoutes } from "./sync-routes";
import { registerMemoRoutes } from "./memo-routes";
@@ -625,7 +635,28 @@ app.onError((error, c) => {
export default worker;
-const callMcpTool = async (
+type McpInputSchema<T> = {
+ safeParse: (input: unknown) =>
+ | { success: true; data: T }
+ | { success: false; error: { issues: Array<{ path: PropertyKey[]; message: string }> } };
+};
+
+const parseMcpInput = <T>(schema: McpInputSchema<T>, input: unknown): T => {
+ const result = schema.safeParse(input);
+ if (result.success) return result.data;
+ const message = result.error.issues
+ .map((issue) => `${issue.path.join(".") || "arguments"}: ${issue.message}`)
+ .join("; ");
+ throw new AppError("invalid_params", message, 400);
+};
+
+const assertMcpMutationAllowed = (environment: Bindings) => {
+ if (isDemoMode(environment)) {
+ throw new AppError("forbidden", "Templates and AI instructions cannot be changed in demo mode.", 403);
+ }
+};
+
+export const callMcpTool = async (
c: AppContext,
auth: AuthContext,
name: string,
@@ -1030,6 +1061,240 @@ const callMcpTool = async (
assertScope(auth, "read:memos");
return await getWorkspaceStats(c.env.storage.db, auth.workspaceId);
}
+ case "list_note_templates": {
+ assertScope(auth, "read:memos");
+ return { templates: await listMemoTemplates(c.env.storage.db, auth.workspaceId) };
+ }
+ case "get_note_template": {
+ assertScope(auth, "read:memos");
+ const template = await getMemoTemplate(
+ c.env.storage.db,
+ auth.workspaceId,
+ getRequiredString(args.templateId, "templateId"),
+ );
+ if (!template) throw new AppError("not_found", "Template not found", 404);
+ return { template };
+ }
+ case "create_note_template": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const input = parseMcpInput(TemplateCreateSchema, args);
+ const memo = input.memoId
+ ? await getMemoDetail(c.env.storage.db, auth.workspaceId, input.memoId)
+ : null;
+ if (input.memoId && !memo) throw new AppError("not_found", "Memo not found", 404);
+
+ const id = createId("template");
+ const now = isoNow();
+ const title = memo?.title ?? (input.title?.trim() || null);
+ const contentMarkdown = memo?.contentMarkdown ?? input.contentMarkdown ?? "";
+ const tags = memo?.tags ?? input.tags ?? [];
+ const contentJson = memo?.contentJson ?? markdownToDoc(contentMarkdown);
+ await c.env.storage.db.prepare(
+ `INSERT INTO memo_templates (
+ id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).bind(
+ id,
+ auth.workspaceId,
+ input.name.trim(),
+ input.description?.trim() || null,
+ title,
+ JSON.stringify(contentJson),
+ contentMarkdown,
+ JSON.stringify(tags),
+ now,
+ now,
+ ).run();
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.create", "template", id, {
+ memoId: input.memoId ?? null,
+ });
+ return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, id) };
+ }
+ case "update_note_template": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const templateId = getRequiredString(args.templateId, "templateId");
+ const input = parseMcpInput(TemplateUpdateSchema, args);
+ if (Object.keys(input).length === 0) {
+ throw new AppError("invalid_params", "At least one template field is required.", 400);
+ }
+ const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);
+ if (!current) throw new AppError("not_found", "Template not found", 404);
+
+ const contentMarkdown = input.contentMarkdown ?? current.contentMarkdown;
+ const contentJson = input.contentMarkdown !== undefined
+ ? markdownToDoc(contentMarkdown)
+ : current.contentJson;
+ const now = isoNow();
+ await c.env.storage.db.prepare(
+ `UPDATE memo_templates
+ SET name = ?, description = ?, title = ?, content_json = ?, content_markdown = ?, tags_json = ?, updated_at = ?
+ WHERE id = ? AND workspace_id = ?`,
+ ).bind(
+ input.name ?? current.name,
+ input.description !== undefined ? input.description?.trim() || null : current.description,
+ input.title !== undefined ? input.title?.trim() || null : current.title,
+ JSON.stringify(contentJson),
+ contentMarkdown,
+ JSON.stringify(input.tags ?? current.tags),
+ now,
+ templateId,
+ auth.workspaceId,
+ ).run();
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.update", "template", templateId, {});
+ return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId) };
+ }
+ case "delete_note_template": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const templateId = getRequiredString(args.templateId, "templateId");
+ const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);
+ if (!current) throw new AppError("not_found", "Template not found", 404);
+ await c.env.storage.db.prepare(
+ `DELETE FROM memo_templates WHERE id = ? AND workspace_id = ?`,
+ ).bind(templateId, auth.workspaceId).run();
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.delete", "template", templateId, {});
+ return { ok: true };
+ }
+ case "use_note_template": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const templateId = getRequiredString(args.templateId, "templateId");
+ const template = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);
+ if (!template) throw new AppError("not_found", "Template not found", 404);
+ const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {
+ notebookId: getRequiredString(args.notebookId, "notebookId"),
+ title: template.title ?? undefined,
+ contentMarkdown: template.contentMarkdown,
+ tags: template.tags,
+ }, getAuditActor(c), getActorLabel(c));
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.use", "template", templateId, { memoId: memo.id });
+ return { memo };
+ }
+ case "list_ai_instructions": {
+ assertScope(auth, "read:memos");
+ return {
+ instructions: await listAiPromptTemplates(
+ c.env.storage.db,
+ auth.workspaceId,
+ getOptionalString(args.locale),
+ ),
+ };
+ }
+ case "get_ai_instruction": {
+ assertScope(auth, "read:memos");
+ const row = await getAiPromptTemplateRow(
+ c.env.storage.db,
+ auth.workspaceId,
+ getRequiredString(args.instructionId, "instructionId"),
+ );
+ if (!row) throw new AppError("not_found", "AI instruction not found", 404);
+ return { instruction: mapAiPromptTemplateRow(row, getOptionalString(args.locale)) };
+ }
+ case "create_ai_instruction": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const input = parseMcpInput(AiPromptTemplateCreateSchema, args);
+ const id = createId("aiprompt");
+ const now = isoNow();
+ const actor = getAuditActor(c);
+ await c.env.storage.db.batch([
+ c.env.storage.db.prepare(
+ `INSERT INTO ai_prompt_templates (
+ id, workspace_id, seed_key, action, parameter_kind, result_mode,
+ name, description, instruction,
+ name_customized, description_customized, instruction_customized,
+ created_at, updated_at
+ ) VALUES (?, ?, NULL, 'custom', ?, ?, ?, ?, ?, 1, 1, 1, ?, ?)`,
+ ).bind(
+ id,
+ auth.workspaceId,
+ input.parameterKind,
+ input.resultMode,
+ input.name.trim(),
+ input.description?.trim() || null,
+ input.instruction.trim(),
+ now,
+ now,
+ ),
+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.create", "ai_prompt", id, {}),
+ ]);
+ const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, id);
+ return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };
+ }
+ case "update_ai_instruction": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const instructionId = getRequiredString(args.instructionId, "instructionId");
+ const input = parseMcpInput(AiPromptTemplateUpdateSchema, args);
+ const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);
+ if (!current) throw new AppError("not_found", "AI instruction not found", 404);
+
+ const now = isoNow();
+ const actor = getAuditActor(c);
+ await c.env.storage.db.batch([
+ c.env.storage.db.prepare(
+ `UPDATE ai_prompt_templates
+ SET name = ?, description = ?, instruction = ?,
+ parameter_kind = ?, result_mode = ?,
+ name_customized = ?, description_customized = ?, instruction_customized = ?,
+ updated_at = ?
+ WHERE id = ? AND workspace_id = ?`,
+ ).bind(
+ input.name?.trim() ?? current.name,
+ input.description !== undefined ? input.description?.trim() || null : current.description,
+ input.instruction?.trim() ?? current.instruction,
+ input.parameterKind ?? current.parameter_kind,
+ input.resultMode ?? current.result_mode,
+ input.name !== undefined ? 1 : current.name_customized,
+ input.description !== undefined ? 1 : current.description_customized,
+ input.instruction !== undefined ? 1 : current.instruction_customized,
+ now,
+ instructionId,
+ auth.workspaceId,
+ ),
+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.update", "ai_prompt", instructionId, {}),
+ ]);
+ const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);
+ return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };
+ }
+ case "delete_ai_instruction": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const instructionId = getRequiredString(args.instructionId, "instructionId");
+ const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);
+ if (!current) throw new AppError("not_found", "AI instruction not found", 404);
+ const actor = getAuditActor(c);
+ await c.env.storage.db.batch([
+ c.env.storage.db.prepare(
+ `DELETE FROM ai_prompt_templates WHERE id = ? AND workspace_id = ?`,
+ ).bind(instructionId, auth.workspaceId),
+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.delete", "ai_prompt", instructionId, {}),
+ ]);
+ return { ok: true };
+ }
+ case "restore_default_ai_instructions": {
+ assertScope(auth, "write:memos");
+ assertMcpMutationAllowed(c.env);
+ const result = await restoreMissingDefaultAiPrompts(c.env.storage.db, auth.workspaceId);
+ if (result.restoredCount > 0) {
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.restore_defaults", "workspace", auth.workspaceId, result);
+ }
+ return {
+ ...result,
+ instructions: await listAiPromptTemplates(
+ c.env.storage.db,
+ auth.workspaceId,
+ getOptionalString(args.locale),
+ ),
+ };
+ }
default:
throw new Error(`Unknown tool: ${name}`);
}
diff --git a/apps/api/src/mcp-management-tools.test.mjs b/apps/api/src/mcp-management-tools.test.mjs
new file mode 100644
index 00000000..0f3f0fb3
--- /dev/null
+++ b/apps/api/src/mcp-management-tools.test.mjs
@@ -0,0 +1,173 @@
+import { describe, expect, test } from "bun:test";
+import { globSync, readFileSync } from "node:fs";
+import { Database } from "bun:sqlite";
+import { callMcpTool } from "./index.ts";
+
+class SqliteD1PreparedStatement {
+ constructor(db, sql, bindings = []) {
+ this.db = db;
+ this.sql = sql;
+ this.bindings = bindings;
+ }
+
+ bind(...bindings) {
+ return new SqliteD1PreparedStatement(this.db, this.sql, bindings);
+ }
+
+ async all() {
+ return { results: this.db.query(this.sql).all(...this.bindings), success: true, meta: {} };
+ }
+
+ async first() {
+ return this.db.query(this.sql).get(...this.bindings) ?? null;
+ }
+
+ async run() {
+ this.db.query(this.sql).run(...this.bindings);
+ return { success: true, meta: {} };
+ }
+}
+
+class SqliteD1Database {
+ constructor(db) {
+ this.db = db;
+ }
+
+ prepare(sql) {
+ return new SqliteD1PreparedStatement(this.db, sql);
+ }
+
+ async batch(statements) {
+ return this.db.transaction(() => statements.map((statement) =>
+ this.db.query(statement.sql).run(...statement.bindings)))();
+ }
+}
+
+const createFixture = (scopes = ["read:memos", "write:memos"]) => {
+ const sqlite = new Database(":memory:");
+ for (const migration of globSync("migrations/*.sql").sort()) {
+ sqlite.exec(readFileSync(migration, "utf8"));
+ }
+ sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES (?, ?, 1)")
+ .run("ws_mcp", "MCP workspace");
+ sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES (?, ?, 1)")
+ .run("ws_other", "Other workspace");
+
+ const auth = {
+ kind: "agent",
+ actorType: "agent",
+ actorId: "tok_mcp",
+ username: "mcp-agent",
+ displayName: null,
+ scopes,
+ workspaceId: "ws_mcp",
+ role: "member",
+ };
+ const context = {
+ env: { storage: { db: new SqliteD1Database(sqlite), resources: {} } },
+ get: (key) => key === "auth" ? auth : undefined,
+ };
+ return { sqlite, auth, context };
+};
+
+describe("MCP template and AI instruction management", () => {
+ test("manages note templates within the authenticated workspace", async () => {
+ const { sqlite, auth, context } = createFixture();
+
+ const created = await callMcpTool(context, auth, "create_note_template", {
+ name: "Weekly review",
+ description: "Reusable weekly structure",
+ title: "Week of",
+ contentMarkdown: "## Progress\n\n- ",
+ tags: ["weekly"],
+ });
+ expect(created.template).toMatchObject({
+ name: "Weekly review",
+ contentMarkdown: "## Progress\n\n- ",
+ tags: ["weekly"],
+ });
+
+ sqlite.query(
+ `INSERT INTO memo_templates (
+ id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at
+ ) VALUES ('template_other', 'ws_other', 'Hidden', NULL, NULL, '{"type":"doc","content":[]}', '', '[]', ?, ?)`,
+ ).run(new Date().toISOString(), new Date().toISOString());
+
+ const listed = await callMcpTool(context, auth, "list_note_templates", {});
+ expect(listed.templates.map((template) => template.id)).toEqual([created.template.id]);
+
+ const updated = await callMcpTool(context, auth, "update_note_template", {
+ templateId: created.template.id,
+ name: "Updated weekly review",
+ contentMarkdown: "## Outcomes",
+ });
+ expect(updated.template).toMatchObject({ name: "Updated weekly review", contentMarkdown: "## Outcomes" });
+
+ await expect(callMcpTool(context, auth, "get_note_template", { templateId: "template_other" }))
+ .rejects.toMatchObject({ code: "not_found" });
+ await expect(callMcpTool(context, auth, "update_note_template", { templateId: created.template.id }))
+ .rejects.toMatchObject({ code: "invalid_params" });
+
+ expect(await callMcpTool(context, auth, "delete_note_template", { templateId: created.template.id }))
+ .toEqual({ ok: true });
+ expect((await callMcpTool(context, auth, "list_note_templates", {})).templates).toEqual([]);
+ });
+
+ test("manages custom AI instructions and restores built-ins", async () => {
+ const { auth, context } = createFixture();
+
+ const created = await callMcpTool(context, auth, "create_ai_instruction", {
+ name: "Decision log",
+ description: "Extract decisions",
+ instruction: "Return decisions and owners as a Markdown list.",
+ resultMode: "append",
+ });
+ expect(created.instruction).toMatchObject({
+ origin: "custom",
+ name: "Decision log",
+ parameterKind: "none",
+ resultMode: "append",
+ });
+
+ const updated = await callMcpTool(context, auth, "update_ai_instruction", {
+ instructionId: created.instruction.id,
+ instruction: "Return decisions, owners, and due dates.",
+ parameterKind: "tone",
+ });
+ expect(updated.instruction).toMatchObject({
+ instruction: "Return decisions, owners, and due dates.",
+ parameterKind: "tone",
+ });
+
+ const restored = await callMcpTool(context, auth, "restore_default_ai_instructions", { locale: "zh-CN" });
+ expect(restored.restoredCount).toBeGreaterThan(0);
+ expect(restored.instructions).toEqual(expect.arrayContaining([
+ expect.objectContaining({ origin: "default" }),
+ expect.objectContaining({ id: created.instruction.id }),
+ ]));
+
+ expect(await callMcpTool(context, auth, "delete_ai_instruction", { instructionId: created.instruction.id }))
+ .toEqual({ ok: true });
+ await expect(callMcpTool(context, auth, "get_ai_instruction", { instructionId: created.instruction.id }))
+ .rejects.toMatchObject({ code: "not_found" });
+ });
+
+ test("enforces memo scopes and demo-mode mutation protection", async () => {
+ const readOnly = createFixture(["read:memos"]);
+ await expect(callMcpTool(readOnly.context, readOnly.auth, "create_note_template", {
+ name: "Denied",
+ contentMarkdown: "No",
+ })).rejects.toMatchObject({ code: "forbidden" });
+
+ const writeOnly = createFixture(["write:memos"]);
+ await expect(callMcpTool(writeOnly.context, writeOnly.auth, "list_ai_instructions", {}))
+ .rejects.toMatchObject({ code: "forbidden" });
+
+ const demo = createFixture();
+ demo.context.env.EDGE_EVER_DEMO_MODE = "true";
+ await expect(callMcpTool(demo.context, demo.auth, "create_ai_instruction", {
+ name: "Denied",
+ instruction: "No",
+ })).rejects.toMatchObject({ code: "forbidden" });
+ });
+});
diff --git a/apps/api/src/mcp-tools.test.mjs b/apps/api/src/mcp-tools.test.mjs
index 56c8817e..344df106 100644
--- a/apps/api/src/mcp-tools.test.mjs
+++ b/apps/api/src/mcp-tools.test.mjs
@@ -43,5 +43,18 @@ describe("MCP tool catalog", () => {
name: { type: "string", minLength: 1, maxLength: 80 },
},
});
+ expect(byName.get("list_note_templates")?.annotations).toMatchObject({
+ readOnlyHint: true,
+ destructiveHint: false,
+ });
+ expect(byName.get("delete_note_template")?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: true,
+ });
+ expect(byName.get("restore_default_ai_instructions")?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: true,
+ });
});
});
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index 6e9cfb49..d7fbf641 100644
--- a/apps/api/src/mcp-tools.ts
+++ b/apps/api/src/mcp-tools.ts
@@ -442,6 +442,183 @@ const MCP_TOOL_DEFINITIONS = [
properties: {},
},
},
+ {
+ name: "list_note_templates",
+ description: "List reusable note templates in the authenticated user's workspace, including their Markdown content and tags.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {},
+ },
+ },
+ {
+ name: "get_note_template",
+ description: "Get one reusable note template by its exact EdgeEver template ID.",
+ inputSchema: {
+ type: "object",
+ required: ["templateId"],
+ additionalProperties: false,
+ properties: {
+ templateId: { type: "string", minLength: 1 },
+ },
+ },
+ },
+ {
+ name: "create_note_template",
+ description: "Create a reusable note template from supplied Markdown or an existing memo in the authenticated user's workspace.",
+ inputSchema: {
+ type: "object",
+ required: ["name"],
+ additionalProperties: false,
+ anyOf: [{ required: ["memoId"] }, { required: ["contentMarkdown"] }],
+ properties: {
+ name: { type: "string", minLength: 1, maxLength: 160 },
+ description: { type: "string", maxLength: 500 },
+ memoId: { type: "string", minLength: 1, description: "Existing memo to copy into the template." },
+ title: { type: ["string", "null"], maxLength: 160 },
+ contentMarkdown: { type: "string" },
+ tags: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ {
+ name: "update_note_template",
+ description: "Update the name, description, title, Markdown content, or tags of a reusable note template.",
+ inputSchema: {
+ type: "object",
+ required: ["templateId"],
+ additionalProperties: false,
+ anyOf: [
+ { required: ["name"] },
+ { required: ["description"] },
+ { required: ["title"] },
+ { required: ["contentMarkdown"] },
+ { required: ["tags"] },
+ ],
+ properties: {
+ templateId: { type: "string", minLength: 1 },
+ name: { type: "string", minLength: 1, maxLength: 160 },
+ description: { type: ["string", "null"], maxLength: 500 },
+ title: { type: ["string", "null"], maxLength: 160 },
+ contentMarkdown: { type: "string" },
+ tags: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ {
+ name: "delete_note_template",
+ description: "Permanently delete a reusable note template from the authenticated user's workspace.",
+ inputSchema: {
+ type: "object",
+ required: ["templateId"],
+ additionalProperties: false,
+ properties: {
+ templateId: { type: "string", minLength: 1 },
+ },
+ },
+ },
+ {
+ name: "use_note_template",
+ description: "Create a new memo from a reusable note template in the selected notebook.",
+ inputSchema: {
+ type: "object",
+ required: ["templateId", "notebookId"],
+ additionalProperties: false,
+ properties: {
+ templateId: { type: "string", minLength: 1 },
+ notebookId: { type: "string", minLength: 1 },
+ },
+ },
+ },
+ {
+ name: "list_ai_instructions",
+ description: "List reusable AI instructions in the authenticated user's workspace, including built-in and custom entries.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ locale: { type: "string", description: "Optional locale such as en-US or zh-CN for unmodified built-in instructions." },
+ },
+ },
+ },
+ {
+ name: "get_ai_instruction",
+ description: "Get one reusable AI instruction by its exact EdgeEver instruction ID.",
+ inputSchema: {
+ type: "object",
+ required: ["instructionId"],
+ additionalProperties: false,
+ properties: {
+ instructionId: { type: "string", minLength: 1 },
+ locale: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "create_ai_instruction",
+ description: "Create a custom reusable AI instruction in the authenticated user's workspace.",
+ inputSchema: {
+ type: "object",
+ required: ["name", "instruction"],
+ additionalProperties: false,
+ properties: {
+ name: { type: "string", minLength: 1, maxLength: 80 },
+ description: { type: "string", maxLength: 200 },
+ instruction: { type: "string", minLength: 1, maxLength: 2000 },
+ parameterKind: { type: "string", enum: ["none", "target-language", "tone"], default: "none" },
+ resultMode: { type: "string", enum: ["append", "replace", "both"], default: "both" },
+ locale: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "update_ai_instruction",
+ description: "Update the text or execution behavior of a built-in or custom reusable AI instruction.",
+ inputSchema: {
+ type: "object",
+ required: ["instructionId"],
+ additionalProperties: false,
+ anyOf: [
+ { required: ["name"] },
+ { required: ["description"] },
+ { required: ["instruction"] },
+ { required: ["parameterKind"] },
+ { required: ["resultMode"] },
+ ],
+ properties: {
+ instructionId: { type: "string", minLength: 1 },
+ name: { type: "string", minLength: 1, maxLength: 80 },
+ description: { type: ["string", "null"], maxLength: 200 },
+ instruction: { type: "string", minLength: 1, maxLength: 2000 },
+ parameterKind: { type: "string", enum: ["none", "target-language", "tone"] },
+ resultMode: { type: "string", enum: ["append", "replace", "both"] },
+ locale: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "delete_ai_instruction",
+ description: "Delete a reusable AI instruction. Deleted built-in instructions can be restored later.",
+ inputSchema: {
+ type: "object",
+ required: ["instructionId"],
+ additionalProperties: false,
+ properties: {
+ instructionId: { type: "string", minLength: 1 },
+ },
+ },
+ },
+ {
+ name: "restore_default_ai_instructions",
+ description: "Restore missing built-in AI instructions without overwriting edited instructions or custom entries.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ locale: { type: "string" },
+ },
+ },
+ },
];
const READ_ONLY_MCP_TOOLS = new Set([
@@ -458,6 +635,10 @@ const READ_ONLY_MCP_TOOLS = new Set([
"list_notebooks",
"list_tags",
"get_workspace_stats",
+ "list_note_templates",
+ "get_note_template",
+ "list_ai_instructions",
+ "get_ai_instruction",
]);
const NON_DESTRUCTIVE_MCP_TOOLS = new Set([
"create_memo",
@@ -470,6 +651,12 @@ const NON_DESTRUCTIVE_MCP_TOOLS = new Set([
"move_notebook",
"create_notebook",
"rename_notebook",
+ "create_note_template",
+ "update_note_template",
+ "use_note_template",
+ "create_ai_instruction",
+ "update_ai_instruction",
+ "restore_default_ai_instructions",
]);
const IDEMPOTENT_MCP_TOOLS = new Set([
"restore_memos",
@@ -479,6 +666,9 @@ const IDEMPOTENT_MCP_TOOLS = new Set([
"import_memos",
"move_notebook",
"rename_notebook",
+ "update_note_template",
+ "update_ai_instruction",
+ "restore_default_ai_instructions",
]);
export const MCP_TOOLS = MCP_TOOL_DEFINITIONS.map((tool) => {
diff --git a/apps/api/src/template-routes.ts b/apps/api/src/template-routes.ts
index ab3af658..81b07746 100644
--- a/apps/api/src/template-routes.ts
+++ b/apps/api/src/template-routes.ts
@@ -86,7 +86,7 @@ const getMemoTemplateRow = async (
WHERE id = ? AND workspace_id = ?`
).bind(id, workspaceId).first<MemoTemplateRow>();
-const getMemoTemplate = async (
+export const getMemoTemplate = async (
db: DatabaseAdapter,
workspaceId: string,
id: string
@@ -95,20 +95,26 @@ const getMemoTemplate = async (
return row ? mapMemoTemplateRow(row) : null;
};
+export const listMemoTemplates = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+): Promise<MemoTemplate[]> => {
+ const rows = await db.prepare(
+ `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at
+ FROM memo_templates
+ WHERE workspace_id = ?
+ ORDER BY updated_at DESC, name ASC`,
+ ).bind(workspaceId).all<MemoTemplateRow>();
+ return rows.results.map(mapMemoTemplateRow);
+};
+
export const registerTemplateRoutes = (
app: Hono<AppEnv>,
dependencies: TemplateRouteDependencies
) => {
const { createMemoRecord, getMemoDetail } = dependencies;
app.get("/api/v1/templates", async (c) => {
- const rows = await c.env.storage.db.prepare(
- `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at
- FROM memo_templates
- WHERE workspace_id = ?
- ORDER BY updated_at DESC, name ASC`
- ).bind(getWorkspaceId(c)).all<MemoTemplateRow>();
-
- return c.json({ templates: rows.results.map(mapMemoTemplateRow) });
+ return c.json({ templates: await listMemoTemplates(c.env.storage.db, getWorkspaceId(c)) });
});
app.post("/api/v1/templates", zValidator("json", TemplateCreateSchema), async (c) => {