index.ts
File: typescript-server/src/index.ts. Copy it with the button on the code block, or download it as part of the typescript-server template: typescript-server.zip.
#!/usr/bin/env nodeimport { realpathSync } from "node:fs";import { readFile, writeFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import { McpServer } from "@modelcontextprotocol/server";import { serveStdio } from "@modelcontextprotocol/server/stdio";import { z } from "zod";
// stdout carries the MCP protocol. Log only to stderr.const log = (...args: unknown[]) => console.error("[notes]", ...args);
const NOTES_FILE = process.env.NOTES_FILE ?? join(homedir(), ".notes-mcp.json");
export interface Note { title: string; body: string; created: string;}
export async function loadNotes(): Promise<Note[]> { try { return JSON.parse(await readFile(NOTES_FILE, "utf8")) as Note[]; } catch (err) { if ((err as NodeJS.ErrnoException).code === "ENOENT") return []; throw err; }}
export async function saveNotes(notes: Note[]): Promise<void> { await writeFile(NOTES_FILE, JSON.stringify(notes, null, 2), "utf8");}
/** Case-insensitive match on title or body, newest first. */export function searchNotes(notes: Note[], query: string, limit: number): Note[] { const q = query.toLowerCase(); return notes .filter((n) => `${n.title} ${n.body}`.toLowerCase().includes(q)) .sort((a, b) => b.created.localeCompare(a.created)) .slice(0, limit);}
/** Registers every tool, resource and prompt. `serveStdio` calls this once per connection. */export function createServer(): McpServer { const server = new McpServer({ name: "notes", version: "0.1.0" });
server.registerTool( "search_notes", { title: "Search notes", description: "Search saved notes by keyword in the title or body. Matching is a case-insensitive substring match. " + "Returns up to `limit` matches, newest first, each with its title, creation time, and the first 200 characters of the body. " + "Use this before add_note to avoid creating duplicates.", inputSchema: z.object({ query: z.string().min(1).describe("Keyword or phrase, case-insensitive"), limit: z.number().int().min(1).max(20).default(5).describe("Maximum results (1-20)"), }), annotations: { readOnlyHint: true, openWorldHint: false }, }, async ({ query, limit }) => { const hits = searchNotes(await loadNotes(), query, limit); const text = hits.length ? hits.map((n) => `- ${n.title} (${n.created}): ${n.body.slice(0, 200)}`).join("\n") : `No notes match "${query}". Try a broader keyword.`; return { content: [{ type: "text", text }] }; }, );
server.registerTool( "add_note", { title: "Add note", description: "Save a new note with a title and a Markdown body. Titles are unique (case-insensitive): if a note with the same title exists, " + "the call fails and nothing is changed. Existing notes are never overwritten or deleted. Returns a confirmation with the saved title.", inputSchema: z.object({ title: z.string().min(1).max(120).describe("Unique note title"), body: z.string().min(1).max(10_000).describe("Note content (Markdown allowed)"), }), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, }, async ({ title, body }) => { const notes = await loadNotes(); if (notes.some((n) => n.title.toLowerCase() === title.toLowerCase())) { return { isError: true, content: [{ type: "text", text: `A note titled "${title}" already exists. Choose a different title or use search_notes to find it.` }], }; } notes.push({ title, body, created: new Date().toISOString() }); await saveNotes(notes); log(`saved note "${title}"`); return { content: [{ type: "text", text: `Saved note "${title}".` }] }; }, );
server.registerResource( "all-notes", "notes://all", { title: "All notes", description: "Every saved note as JSON", mimeType: "application/json" }, async (uri) => ({ contents: [{ uri: uri.href, text: JSON.stringify(await loadNotes(), null, 2) }] }), );
server.registerPrompt( "weekly-review", { title: "Weekly review", description: "Summarise this week's notes", argsSchema: z.object({ focus: z.string().optional().describe("Optional topic to focus on") }), }, ({ focus }) => ({ messages: [ { role: "user", content: { type: "text", text: `Search my notes from this week and write a weekly review${focus ? ` focused on ${focus}` : ""}.`, }, }, ], }), );
return server;}
// Start only when run directly (node build/index.js, npx), not when imported by tests.const isMain = process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);if (isMain) { // Serves both protocol eras: 2026-07-28 clients and legacy clients that open with `initialize`. serveStdio(createServer); log(`running on stdio (NOTES_FILE=${NOTES_FILE})`);}