Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
AI apps (MCP): ask, the calendar, people, the Trash, settings and Markdown export to read; with changes allowed, folders, meetings, notes, recording, a few settings, and meetings brought in from other notes apps (create_meeting, import_meetings), each through the function behind the app's own button. Every change is logged by id, never by name or words; nothing is deleted for good
christianmatded58affc839
diff --git a/app/src/main/index.ts b/app/src/main/index.tsindex 6e148a31..2253a9dc 100644--- a/app/src/main/index.ts+++ b/app/src/main/index.ts@@ -304,6 +304,9 @@ const fakeCallWatch: Watch = (ids, onLine) => {}const macName = () => (isFake() ? process.env.YOGURT_FAKE_FULL_NAME ?? 'Sam Rivera' : macFullName())+/** starting and pausing a recording the way home and the widget do, for AI apps (set once detection starts) */+let recordingControls: { start(o: { eventId?: string; title?: string }): Promise<StartResult>; pause(id: unknown, paused: unknown): boolean } | undefined+/** fake mode's hooks reach the store and the notes through these */let storeRef: Store | undefinedlet indexerRef: { schedule(): Promise<unknown> } | undefined@@ -370,23 +373,25 @@ function startDetection() {prompts.hide(); watcher.cleared(); goTo(`/note/${m.id}`, resume)return { id: m.id, ...(resume ? { resumeRequested: true as const } : {}), ...(alreadyRecording ? { alreadyRecording: true as const } : {}) }}- // home: Start notes for a calendar event (looked up here, never taken from the page), or New note with none+ // home: Start notes for a calendar event (looked up here, never taken from the page), or New note with none; an AI+ // app's start_recording the same way, with its own title if it gave one// gone: the event left the calendar since the page showed it (moved, cancelled); failed: anything else, in plain words on the page- ipcMain.handle('meetings:start', async (_e, eventId: unknown): Promise<StartResult> => {+ const startNotes = async (o: { eventId?: string; title?: string }): Promise<StartResult> => {try {const cur = activeMeeting()if (cur) { goTo(`/note/${cur.id}`); return { id: cur.id, alreadyRecording: true } }let event: CalEvent | null = null- if (typeof eventId === 'string') {- event = (await comingUp()).find((e) => matchesEvent(e, eventId)) ?? null+ if (o.eventId !== undefined) {+ event = (await comingUp()).find((e) => matchesEvent(e, o.eventId!)) ?? nullif (!event) return { error: 'gone' }}- return begin({ title: event?.title ?? '', event, app: null })+ return begin({ title: o.title ?? event?.title ?? '', event, app: null })} catch (e) {console.error('start notes failed', e)return { error: 'failed' }}- })+ }+ ipcMain.handle('meetings:start', (_e, eventId: unknown) => startNotes(typeof eventId === 'string' ? { eventId } : {}))ipcMain.handle('meetings:prepare', async (_e, eventId: unknown, at: unknown): Promise<StartResult> => {if (typeof eventId !== 'string' || typeof at !== 'number' || !Number.isFinite(at) || !Number.isFinite(new Date(at).getTime())) return { error: 'gone' }try {@@ -421,6 +426,7 @@ function startDetection() {return changed}ipcMain.handle('meetings:set-paused', (_e, id: unknown, paused: unknown) => pauseRecording(id, paused))+ recordingControls = { start: startNotes, pause: pauseRecording }ipcMain.handle('meetings:retry-stop-save', (_e, id: unknown) => isId(id) && retryStopSave(id))// the menu bar: open, new note or stop, quit; Yogurt stays there with its window closedconst tray = createTray({@@ -839,15 +845,45 @@ app.whenReady().then(() => {// the mic picker under the note's bar: the mics, the chosen one, and switching while recordinghookMics({ helper: micListHelper(process.platform) === 'system' || isFake() ? runHelper : audioHelper.run, settingsFile, send: (channel, payload) => win?.webContents.send(channel, payload) })hookShare({ store, window: () => win })- hookFolders({ store, changed: () => { win?.webContents.send('folders:changed'); folderSuggestions.refresh() } })+ const foldersChanged = () => { win?.webContents.send('folders:changed'); folderSuggestions.refresh() }+ hookFolders({ store, changed: foldersChanged })// every meeting to one file and back; what an import adds shows up on homehookBackup({ getRecordingPill: () => visibilityOf(loadSettings(settingsFile), platform).showRecordingPill,setRecordingPill: preferences.setRecordingPill, db: store.db, meetingsDir: join(userDataDir(), 'meetings'), window: () => win, recording: () => !!activeMeeting() || !!resumingId,changed: () => { win?.webContents.send('meetings:changed'); win?.webContents.send('conversations:list', conversations.list()); void indexer.refresh(); folderSuggestions.refresh() },beforeExport: () => { notes.retryDrafts(); return notes.pendingDraftId() } })+ // AI apps change things only through the functions behind the app's own buttons+ const noteSaved = (id: string, r: ReturnType<typeof notes.replace>) => { if (r === 'saved') win?.webContents.send('meetings:changed'); return r }void hookMcp({store, profile: userDataDir(), me, version: app.getVersion(),enabled: () => !!loadSettings(settingsFile).aiApps, setEnabled: (on) => { updateSettings(settingsFile, { aiApps: on || undefined }) },+ changesEnabled: () => !!loadSettings(settingsFile).aiAppChanges, setChangesEnabled: (on) => { updateSettings(settingsFile, { aiAppChanges: on || undefined }) },+ app: {+ ask: (question, chips) => conversations.askOnce(question, chips),+ comingUp: () => calendarComingUp(),+ calendarDay: (at) => calendarDay(at),+ settings: () => preferences.read(),+ changed: (what) => { if (what === 'folders') foldersChanged(); else win?.webContents.send('meetings:changed') },+ // a meeting from another notes app: on home, in the library for Ask, and offered a folder like any other+ imported: (id) => { win?.webContents.send('meetings:changed'); void indexer.schedule(); folderSuggestions.schedule(id) },+ rename: (id, title) => !!renameMeeting(id, title),+ setAttendees: (id, people) => setPeople(id, people),+ linkEvent: (id, eventId, day) => linkMeetingEvent(id, eventId, day).catch(() => false),+ unlinkEvent: (id) => !!unlinkEvent(id),+ trash: (id) => trashMeeting(id),+ restore: (id) => restoreMeeting(id),+ setMyNotes: (id, md) => noteSaved(id, notes.replace(id, 'mine', md)),+ setSummary: (id, md) => noteSaved(id, notes.replace(id, 'enhanced', md)),+ rewriteSummary: (id, instruction) => (['waiting', 'writing'].includes(notes.view(id).status) || !writeAgain(id, instruction) ? 'busy' : 'queued'),+ notesReady: () => !!setup.notesPath(),+ startRecording: (o) => recordingControls?.start(o) ?? Promise.resolve({ error: 'failed' as const }),+ pauseRecording: (id, paused) => recordingControls?.pause(id, paused) ?? false,+ stopRecording: (id) => { if (activeMeeting()?.id !== id) return false; stopMeeting(id); return true },+ recording: () => activeMeeting(),+ setJargon: (terms) => preferences.setJargon(terms),+ setSpoken: (v) => preferences.setSpoken(v),+ setSummaryLanguage: (v) => preferences.setSummaryLanguage(v),+ },audio: async (id) => {await rejoined; await recordingSettled(id)return (['me', 'them'] as const).flatMap((track) => { const path = trackFile(meetingDir(id), track, audioKinds); return path ? [{ track, path }] : [] })@@ -866,10 +902,14 @@ app.whenReady().then(() => {ipcMain.on('notes:flush-sync', (e, id: unknown, side: unknown, md: unknown, revision: unknown) => { e.returnValue = saveEdit(id, side, md, revision) })ipcMain.on('notes:kept-edits', (_e, id: unknown) => { if (known(id)) notes.keptEdits(id) })ipcMain.handle('notes:stop', (_e, id: unknown) => { if (known(id)) return notes.stop(id) })- ipcMain.handle('notes:write-again', (_e, id: unknown, note: unknown) => {+ // "Write again", from the note or an AI app; false when it can't start now+ const writeAgain = (id: unknown, note: unknown): boolean => {const instruction = rewriteNote(note)- if (known(id) && instruction !== undefined && !transcriptionBusy(store.meeting(id)?.transcriptionState)) void notes.writeAgain(id, instruction, true)- })+ if (!known(id) || instruction === undefined || transcriptionBusy(store.meeting(id)?.transcriptionState)) return false+ void notes.writeAgain(id, instruction, true)+ return true+ }+ ipcMain.handle('notes:write-again', (_e, id: unknown, note: unknown) => { writeAgain(id, note) })app.on('will-quit', () => engine.dispose())// an earlier quit or crash may have left parts unjoined: try again nowconst rejoined = rejoinInterrupted(join(userDataDir(), 'meetings'), async dir => {@@ -983,18 +1023,27 @@ app.whenReady().then(() => {void indexer.refresh()return true})- ipcMain.handle('meetings:set-attendees', (_e, id: unknown, people: unknown) => { if (isId(id) && setAttendees(id, people)) notes.applyPeople(id) })- ipcMain.handle('meetings:link-event', async (_e, id: unknown, eventId: unknown, day?: unknown) => {+ const setPeople = (id: unknown, people: unknown): boolean => {+ if (!isId(id) || !setAttendees(id, people)) return false+ notes.applyPeople(id)+ return true+ }+ ipcMain.handle('meetings:set-attendees', (_e, id: unknown, people: unknown) => { setPeople(id, people) })+ /** true: linked (null unlinks); an event not on the calendar that day throws */+ const linkMeetingEvent = async (id: unknown, eventId: unknown, day?: unknown): Promise<boolean> => {const m = isId(id) ? store.meeting(id) : undefined- if (!m) return- if (eventId === null) { unlinkEvent(m.id); return }- if (typeof eventId !== 'string') return+ if (!m) return false+ if (eventId === null) return !!unlinkEvent(m.id)+ if (typeof eventId !== 'string') return falseconst at = day ?? m.eventStartedAt ?? m.startedAtif (typeof at !== 'number' || !Number.isFinite(at) || !Number.isFinite(new Date(at).getTime())) throw new Error('Invalid calendar day')const event = (await eventsOn(at, 'link-event')).find((e) => matchesEvent(e, eventId))if (!event) throw new Error('Calendar event unavailable')- if (linkEvent(m.id, event)) notes.applyPeople(m.id)- })+ if (!linkEvent(m.id, event)) return false+ notes.applyPeople(m.id)+ return true+ }+ ipcMain.handle('meetings:link-event', async (_e, id: unknown, eventId: unknown, day?: unknown) => { await linkMeetingEvent(id, eventId, day) })// gone for good, audio too; never while it recordsconst removeForGood = (id: unknown) => id === resumingId ? Promise.resolve('failed' as const) : isId(id) && stopSavePending(id) ? Promise.resolve('save-pending' as const) : deleteMeeting(id, {store, dirOf: meetingDir,@@ -1010,19 +1059,22 @@ app.whenReady().then(() => {})ipcMain.handle('meetings:delete', (_e, id: unknown) => removeForGood(id))// Delete in a list or a note: to the Trash, kept until restored or deleted for good there (30 days at most)- ipcMain.handle('meetings:trash', (_e, id: unknown) => id === resumingId ? 'failed' : isId(id) && stopSavePending(id) ? 'save-pending' : moveToTrash(id, {+ const trashMeeting = (id: unknown) => id === resumingId ? 'failed' as const : isId(id) && stopSavePending(id) ? 'save-pending' as const : moveToTrash(id, {store,moved: (id) => {indexer.forget(id)win?.webContents.send('meetings:changed'); win?.webContents.send('folders:changed')if (route === `/note/${id}`) { route = ''; win?.webContents.send('nav:go', route) }},- }))- ipcMain.handle('meetings:restore', (_e, id: unknown) => {- if (!isId(id) || store.meeting(id)?.trashedAt == null) return+ })+ ipcMain.handle('meetings:trash', (_e, id: unknown) => trashMeeting(id))+ const restoreMeeting = (id: unknown): boolean => {+ if (!isId(id) || store.meeting(id)?.trashedAt == null) return falsestore.restoreMeeting(id); indexer.restored(id)win?.webContents.send('meetings:changed'); win?.webContents.send('folders:changed')- })+ return true+ }+ ipcMain.handle('meetings:restore', (_e, id: unknown) => { restoreMeeting(id) })ipcMain.handle('meetings:trashed', () => store.trashed())ipcMain.handle('meetings:empty-trash', () => emptyTrash({ store, remove: removeForGood }))// a meeting in the Trash for 30 days goes for good: at launch, and twice a day for a Yogurt that stays open@@ -1069,8 +1121,8 @@ app.whenReady().then(() => {win?.webContents.send('calendar:changed')return true})- ipcMain.handle('calendar:day', async (_e, at: unknown, purpose?: unknown) => {- if (typeof at !== 'number' || !Number.isFinite(at) || !Number.isFinite(new Date(at).getTime())) return { status: 'error', events: [] }+ const calendarDay = async (at: unknown, purpose?: unknown) => {+ if (typeof at !== 'number' || !Number.isFinite(at) || !Number.isFinite(new Date(at).getTime())) return { status: 'error' as const, events: [] }const unavailable: string[] = []const events = (await eventsOn(at, purpose === 'link-event' ? 'link-event' : undefined, unavailable)).map((event) => {const meeting = eventIds(event).map((id) => store.meetingForEvent(id)).find(Boolean)@@ -1078,11 +1130,13 @@ app.whenReady().then(() => {return { ...event, attendees: resolvePeople(store.db, event.attendees), ...(note ? { note: { id: note.id, state: note.state, ...(note.source ? { source: note.source } : {}) } } : {}) }})return { status: calendarStatus(), events, unavailable }- })- ipcMain.handle('calendar:coming-up', async () => {+ }+ ipcMain.handle('calendar:day', (_e, at: unknown, purpose?: unknown) => calendarDay(at, purpose))+ const calendarComingUp = async () => {const events = (await comingUp()).map(event => ({ ...event, attendees: resolvePeople(store.db, event.attendees) }))return { status: calendarStatus(), events }- })+ }+ ipcMain.handle('calendar:coming-up', calendarComingUp)// not asked yet: the Mac's own question; turned off: the Mac's settings, where only the person can turn it onipcMain.handle('calendar:links', () => calendarLinks?.list() ?? [])ipcMain.handle('calendar:add-link', async (_e, url: unknown) => {diff --git a/app/src/main/mcp/args.ts b/app/src/main/mcp/args.tsnew file mode 100644index 00000000..15b97929--- /dev/null+++ b/app/src/main/mcp/args.ts@@ -0,0 +1,78 @@+/**+ * What another app's model sends is checked strictly before Yogurt acts on it: a wrong type, a value too long or a+ * list too big is refused in plain words the model can act on, never half-done. Text here goes to that model, in English.+ */++/** a plain answer for the other app's model, not a crash: handle() turns it into an error result */+export class Refusal extends Error {}++export type Args = Record<string, unknown>++/** text, trimmed; undefined when left out. Wrong type, blank (when required) or too long is refused. */+export function str(a: Args, key: string, o: { max: number; required?: boolean; keepSpace?: boolean }): string | undefined {+ const v = a[key]+ if (v === undefined || v === null) {+ if (o.required) throw new Refusal(`${key} is needed.`)+ return undefined+ }+ if (typeof v !== 'string') throw new Refusal(`${key} must be text.`)+ const s = o.keepSpace ? v : v.trim()+ if (o.required && !s.trim()) throw new Refusal(`${key} can't be blank.`)+ if (s.length > o.max) throw new Refusal(`${key} is too long: at most ${o.max} characters.`)+ return s+}++export function bool(a: Args, key: string): boolean | undefined {+ const v = a[key]+ if (v === undefined || v === null) return undefined+ if (typeof v !== 'boolean') throw new Refusal(`${key} must be true or false.`)+ return v+}++/** one of a few words */+export function oneOf<T extends string>(a: Args, key: string, values: readonly T[]): T | undefined {+ const v = a[key]+ if (v === undefined || v === null) return undefined+ if (!values.includes(v as T)) throw new Refusal(`${key} must be one of: ${values.map((x) => JSON.stringify(x)).join(', ')}.`)+ return v as T+}++export function list(a: Args, key: string, o: { max: number; required?: boolean }): unknown[] | undefined {+ const v = a[key]+ if (v === undefined || v === null) {+ if (o.required) throw new Refusal(`${key} is needed.`)+ return undefined+ }+ if (!Array.isArray(v)) throw new Refusal(`${key} must be a list.`)+ if (v.length > o.max) throw new Refusal(`${key} has ${v.length} items: at most ${o.max} in one call.`)+ return v+}++/** an ISO time (or a date) as ms; refused when it isn't one */+export function time(a: Args, key: string, o: { required?: boolean } = {}): number | undefined {+ const s = str(a, key, { max: 64, required: o.required })+ if (s === undefined) return undefined+ const ms = Date.parse(s)+ if (!Number.isFinite(ms)) throw new Refusal(`${key} must be an ISO time, like 2026-11-03T15:00:00Z.`)+ return ms+}++/** "2026-11-03" is that day where the person is (midday, so no time zone moves it a day); a full ISO time is its own day */+export function day(a: Args, key: string, o: { required?: boolean } = {}): number | undefined {+ const s = str(a, key, { max: 64, required: o.required })+ if (s === undefined) return undefined+ const ymd = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)+ const ms = ymd ? new Date(Number(ymd[1]), Number(ymd[2]) - 1, Number(ymd[3]), 12).getTime() : Date.parse(s)+ if (!Number.isFinite(ms)) throw new Refusal(`${key} must be a date, like 2026-11-03.`)+ return ms+}++/** a person, as other apps give them: a name, and an email when they know it */+export function people(v: unknown[], key: string): Array<{ name: string; email: string | null }> {+ return v.map((p, i) => {+ if (!p || typeof p !== 'object') throw new Refusal(`${key}[${i}] must be an object with a name (and an email if known).`)+ const name = str(p as Args, 'name', { max: 200, required: true })!+ const email = str(p as Args, 'email', { max: 200 })+ return { name, email: email || null }+ })+}diff --git a/app/src/main/mcp/changes.ts b/app/src/main/mcp/changes.tsnew file mode 100644index 00000000..e2956361--- /dev/null+++ b/app/src/main/mcp/changes.ts@@ -0,0 +1,223 @@+import { isLocale, LOCALES } from '../../shared/i18n'+import { MAX_TERM, MAX_TERMS } from '../../shared/jargon'+import { REWRITE_NOTE_MAX } from '../../shared/rewriteNote'+import { NOTES_MAX } from '../notes'+import { TITLE_MAX, PEOPLE_MAX } from '../meeting'+import { Refusal, day, list, oneOf, people, str, type Args } from './args'+import type { Ctx, SaveOutcome, Tool } from './server'++/**+ * The changes an AI app can make, only with "Let AI apps make changes" on in Settings: filing, renaming, notes,+ * recording and a few settings. Each goes through the function behind the app's own button. Nothing here deletes a+ * meeting or its audio for good, empties the Trash, or touches privacy, permission or AI-app settings.+ */++const id = { type: 'string', description: 'The meeting id, from list_meetings or search' }+const folder = { type: 'string', description: 'The folder: its id or name, from list_folders' }+/** a change the person may want to confirm first; destructive: it replaces or removes something */+const change = (destructive = false) => ({ readOnlyHint: false, destructiveHint: destructive, idempotentHint: false, openWorldHint: false })+const tool = (name: string, description: string, properties: object, required: string[] = [], destructive = false): Tool =>+ ({ name, description, inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}) }, annotations: change(destructive) })++export const changeTools: Tool[] = [+ tool('create_folder', 'Makes a new folder for filing meetings. Gives its id and name.', { name: { type: 'string', description: 'At most 200 characters' } }, ['name']),+ tool('rename_folder', 'Renames a folder.', { folder, name: { type: 'string', description: 'The new name, at most 200 characters' } }, ['folder', 'name']),+ tool('delete_folder', 'Deletes a folder. Its meetings stay, just no longer filed in it.', { folder }, ['folder'], true),+ tool('add_to_folder', 'Files a meeting in a folder (a meeting can be in several).', { folder, id }, ['folder', 'id']),+ tool('remove_from_folder', 'Takes a meeting out of a folder. The meeting stays.', { folder, id }, ['folder', 'id']),+ tool('accept_folder_suggestion', "Files a meeting in the folder Yogurt suggests for it (get_meeting's suggested_folder).", { id }, ['id']),+ tool('dismiss_folder_suggestion', 'Turns down the folder Yogurt suggests for a meeting, so it stops offering it.', { id }, ['id']),+ tool('rename_meeting', "Gives a meeting the person's own title.", { id, title: { type: 'string', description: 'At most 200 characters' } }, ['id', 'title']),+ tool('set_attendees', 'Sets who was in a meeting, replacing the list. Unedited summaries are written again with the new people.',+ { id, attendees: { type: 'array', description: `At most ${PEOPLE_MAX}`, items: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' } }, required: ['name'] } } }, ['id', 'attendees'], true),+ tool('link_calendar_event', "Links a meeting to a calendar event (event_id from upcoming_meetings or calendar_day): it takes the event's title and people, unless the person set their own.",+ { id, event_id: { type: 'string' }, date: { type: 'string', description: "The event's day, like 2026-11-03 (the meeting's own day when left out)" } }, ['id', 'event_id']),+ tool('unlink_calendar_event', "Unlinks a meeting from its calendar event. Its title, people and notes stay.", { id }, ['id']),+ tool('trash_meeting', 'Moves a meeting to the Trash, where it can be restored for 30 days (restore_meeting). Never while it records.', { id }, ['id'], true),+ tool('restore_meeting', 'Brings a meeting back from the Trash (ids from list_trash).', { id: { type: 'string', description: 'The meeting id, from list_trash' } }, ['id']),+ tool('set_my_notes', "Writes the person's own notes for a meeting (Markdown). mode \"replace\" (default) replaces them, \"append\" adds after them.",+ { id, markdown: { type: 'string' }, mode: { type: 'string', enum: ['replace', 'append'] } }, ['id', 'markdown'], true),+ tool('set_summary', "Replaces Yogurt's written summary of a meeting with this Markdown. It counts as the person's edit, so Yogurt won't rewrite it by itself.",+ { id, markdown: { type: 'string' } }, ['id', 'markdown'], true),+ tool('rewrite_summary', "Has Yogurt write a meeting's summary again from its transcript and notes, like its Write again button, optionally with an instruction (\"shorter\", \"focus on decisions\"). It replaces the summary there is, and takes a while: get_meeting shows it once done.",+ { id, instruction: { type: 'string', description: `At most ${REWRITE_NOTE_MAX} characters` } }, ['id'], true),+ tool('start_recording', "Starts taking notes of a call now: Yogurt records the microphone and the call's sound on this computer and transcribes it. Optional title, or event_id (from upcoming_meetings) to take notes for that calendar event. Only one recording at a time. The person should have asked for it: everyone in the call should know they are recorded.",+ { title: { type: 'string', description: 'At most 200 characters' }, event_id: { type: 'string' } }),+ tool('pause_recording', 'Pauses the recording (id: the meeting recording now, the one recording when left out).', { id }),+ tool('resume_recording', 'Carries on a paused recording.', { id }),+ tool('stop_recording', 'Stops the recording. Yogurt then finishes the transcript and writes the summary.', { id }, [], true),+ tool('set_custom_words', `Sets the custom words Yogurt spells right in transcripts and notes (names, products, acronyms), replacing the list: at most ${MAX_TERMS}, each at most ${MAX_TERM} characters. Gives the list kept.`,+ { words: { type: 'array', items: { type: 'string' } } }, ['words'], true),+ tool('set_spoken_language', 'Sets the language spoken in meetings: "en" (English only, the most accurate for English) or "multi" (any language, heard per meeting).',+ { language: { type: 'string', enum: ['en', 'multi'] } }, ['language']),+ tool('set_summary_language', `Sets the language Yogurt writes new summaries in: a language id (${LOCALES.map((l) => l.id).join(', ')}), or "" for each meeting's own language.`,+ { language: { type: 'string' } }, ['language']),+]++const saved = (what: string, r: SaveOutcome) => {+ if (r === 'saved') return+ throw new Refusal(r === 'busy' ? `Yogurt is writing this meeting's summary right now. Try again once it's done.`+ : r === 'too-long' ? `That ${what} is too long: at most ${NOTES_MAX} characters.` : `Yogurt couldn't save the ${what}. Try again.`)+}++export function changeHandlers({ d, meetingOf, folderOf, summary, log }: Ctx): Record<string, (a: Args) => Promise<string>> {+ const s = d.store+ const folderNamed = (a: Args) => { const f = folderOf(str(a, 'folder', { max: 200, required: true })); if (!f) throw new Refusal('folder is needed.'); return f }+ const name = (a: Args) => str(a, 'name', { max: 200, required: true })!.replace(/\s+/g, ' ')+ const folders = () => { d.app.changed('folders') }+ /** a meeting that may record now: the one asked for, or the one recording */+ const recordingOf = (a: Args) => {+ const want = str(a, 'id', { max: 64 })+ const cur = d.app.recording()+ if (!cur) throw new Refusal('Yogurt is not recording.')+ if (want && want !== cur.id) throw new Refusal(`That meeting is not the one recording. Yogurt is recording ${JSON.stringify(cur.title)} (${cur.id}).`)+ return cur+ }+ const ok = (v: object) => JSON.stringify(v, null, 2)+ return {+ async create_folder(a) {+ const n = name(a)+ const same = s.folders().find((f) => f.name.toLowerCase() === n.toLowerCase())+ if (same) throw new Refusal(`There is already a folder called ${JSON.stringify(same.name)} (id ${same.id}).`)+ const f = s.createFolder(n)+ folders()+ log(`create_folder made ${f.id}`)+ return ok({ id: f.id, name: f.name })+ },+ async rename_folder(a) {+ const f = folderNamed(a), n = name(a)+ s.renameFolder(f.id, n); folders()+ return ok({ id: f.id, name: s.folder(f.id)?.name ?? n })+ },+ async delete_folder(a) {+ const f = folderNamed(a)+ s.deleteFolder(f.id); folders()+ return `Deleted the folder ${JSON.stringify(f.name)}. Its ${f.count} meetings stay.`+ },+ async add_to_folder(a) {+ const f = folderNamed(a), m = meetingOf(a.id)+ s.addToFolder(f.id, m.id); folders()+ return ok(summary(s.meeting(m.id)!))+ },+ async remove_from_folder(a) {+ const f = folderNamed(a), m = meetingOf(a.id)+ s.removeFromFolder(f.id, m.id); folders()+ return ok(summary(s.meeting(m.id)!))+ },+ async accept_folder_suggestion(a) {+ const m = meetingOf(a.id)+ const sug = s.folderSuggestion(m.id)+ const f = !s.foldersOf(m.id).length && sug.state === 'pending' && sug.folderId ? s.folder(sug.folderId) : undefined+ if (!f) throw new Refusal('Yogurt has no folder suggestion for this meeting. add_to_folder files it anywhere.')+ s.addToFolder(f.id, m.id); folders()+ return ok(summary(s.meeting(m.id)!))+ },+ async dismiss_folder_suggestion(a) {+ const m = meetingOf(a.id)+ s.dismissFolderSuggestion(m.id); folders()+ return 'Yogurt no longer suggests a folder for this meeting.'+ },+ async rename_meeting(a) {+ const m = meetingOf(a.id)+ const title = str(a, 'title', { max: TITLE_MAX, required: true })!+ if (!d.app.rename(m.id, title)) throw new Refusal("Yogurt couldn't rename that meeting.")+ return ok(summary(s.meeting(m.id)!))+ },+ async set_attendees(a) {+ const m = meetingOf(a.id)+ const who = people(list(a, 'attendees', { max: PEOPLE_MAX, required: true })!, 'attendees')+ if (!d.app.setAttendees(m.id, who)) throw new Refusal("Yogurt couldn't change who was in that meeting.")+ return ok(summary(s.meeting(m.id)!))+ },+ async link_calendar_event(a) {+ const m = meetingOf(a.id)+ const eventId = str(a, 'event_id', { max: 1024, required: true })!+ if (!(await d.app.linkEvent(m.id, eventId, day(a, 'date')))) throw new Refusal('That event is not on the calendar that day. upcoming_meetings or calendar_day gives the event ids.')+ return ok(summary(s.meeting(m.id)!))+ },+ async unlink_calendar_event(a) {+ const m = meetingOf(a.id)+ if (!m.eventId) throw new Refusal('That meeting is not linked to a calendar event.')+ d.app.unlinkEvent(m.id)+ return ok(summary(s.meeting(m.id)!))+ },+ async trash_meeting(a) {+ const m = meetingOf(a.id)+ const r = d.app.trash(m.id)+ if (r === 'recording') throw new Refusal('That meeting is recording. Stop it first (stop_recording).')+ if (r !== 'trashed') throw new Refusal("Yogurt couldn't move that meeting to the Trash right now. Try again in a moment.")+ return `Moved ${JSON.stringify(m.title)} to the Trash. restore_meeting brings it back for 30 days.`+ },+ async restore_meeting(a) {+ const want = str(a, 'id', { max: 64, required: true })!+ const m = s.meeting(want)+ if (!m || m.trashedAt == null) throw new Refusal(`No meeting with id ${JSON.stringify(want)} in the Trash. list_trash gives the ids.`)+ d.app.restore(m.id)+ return ok(summary(s.meeting(m.id)!))+ },+ async set_my_notes(a) {+ const m = meetingOf(a.id)+ const md = str(a, 'markdown', { max: NOTES_MAX, required: true, keepSpace: true })!+ const mode = oneOf(a, 'mode', ['replace', 'append'] as const) ?? 'replace'+ const was = s.notes(m.id).mine+ saved('notes', d.app.setMyNotes(m.id, mode === 'append' && was.trim() ? `${was.replace(/\s+$/, '')}\n\n${md}` : md))+ return ok({ id: m.id, myNotes: s.notes(m.id).mine })+ },+ async set_summary(a) {+ const m = meetingOf(a.id)+ if (m.state === 'recording') throw new Refusal('That meeting is recording. Its summary is written once it stops.')+ saved('summary', d.app.setSummary(m.id, str(a, 'markdown', { max: NOTES_MAX, required: true, keepSpace: true })!))+ return ok({ id: m.id, summary: s.notes(m.id).enhanced })+ },+ async rewrite_summary(a) {+ const m = meetingOf(a.id)+ if (m.state === 'recording') throw new Refusal('That meeting is recording. Its summary is written once it stops.')+ const instruction = str(a, 'instruction', { max: REWRITE_NOTE_MAX }) ?? ''+ if (d.app.rewriteSummary(m.id, instruction) === 'busy') throw new Refusal('Yogurt is still working on this meeting (its transcript or summary). Try again once it is done.')+ return d.app.notesReady() ? 'Yogurt is writing the summary again. get_meeting shows it once done, usually within a minute or two.'+ : "Yogurt will write the summary once its notes model has downloaded."+ },+ async start_recording(a) {+ const title = str(a, 'title', { max: TITLE_MAX })+ const eventId = str(a, 'event_id', { max: 1024 })+ const cur = d.app.recording()+ if (cur) throw new Refusal(`Yogurt is already recording ${JSON.stringify(cur.title)} (${cur.id}). Stop it first (stop_recording).`)+ const r = await d.app.startRecording({ ...(title ? { title } : {}), ...(eventId ? { eventId } : {}) })+ if ('error' in r) throw new Refusal(r.error === 'gone' ? 'That event is not coming up on the calendar any more. upcoming_meetings gives the events.' : "Yogurt couldn't start recording. Try again.")+ log(`start_recording made ${r.id}`)+ return ok({ ...summary(s.meeting(r.id)!), recording: true })+ },+ async pause_recording(a) {+ const m = recordingOf(a)+ if (!d.app.pauseRecording(m.id, true)) throw new Refusal('The recording is already paused.')+ return `Paused recording ${JSON.stringify(m.title)}.`+ },+ async resume_recording(a) {+ const m = recordingOf(a)+ if (!d.app.pauseRecording(m.id, false)) throw new Refusal('The recording is not paused.')+ return `Recording ${JSON.stringify(m.title)} again.`+ },+ async stop_recording(a) {+ const m = recordingOf(a)+ if (!d.app.stopRecording(m.id)) throw new Refusal("Yogurt couldn't stop the recording. Try again.")+ return `Stopped recording ${JSON.stringify(m.title)} (${m.id}). Yogurt is finishing the transcript and writing the summary: get_meeting shows them once done.`+ },+ async set_custom_words(a) {+ const words = list(a, 'words', { max: MAX_TERMS, required: true })!+ if (words.some((w) => typeof w !== 'string')) throw new Refusal('words must be a list of text.')+ return ok({ custom_words: d.app.setJargon(words as string[]) })+ },+ async set_spoken_language(a) {+ const v = oneOf(a, 'language', ['en', 'multi'] as const)+ if (!v) throw new Refusal('language is needed: "en" or "multi".')+ d.app.setSpoken(v)+ return `Meetings are now heard as ${v === 'en' ? 'English only' : 'any language'}.`+ },+ async set_summary_language(a) {+ const v = str(a, 'language', { max: 16 })+ if (v === undefined || (v !== '' && !isLocale(v))) throw new Refusal(`language must be one of: ${LOCALES.map((l) => `${l.id} (${l.english})`).join(', ')}, or "" for each meeting's own language.`)+ d.app.setSummaryLanguage(v)+ return v ? `New summaries are written in ${LOCALES.find((l) => l.id === v)!.english}.` : "New summaries are written in each meeting's own language."+ },+ }+}diff --git a/app/src/main/mcp/importMeeting.ts b/app/src/main/mcp/importMeeting.tsnew file mode 100644index 00000000..920f932a--- /dev/null+++ b/app/src/main/mcp/importMeeting.ts@@ -0,0 +1,118 @@+import { NOTES_MAX } from '../notes'+import { TITLE_MAX, PEOPLE_MAX } from '../meeting'+import { Refusal, bool, list, people, str, time, type Args } from './args'+import type { Ctx, Tool } from './server'+import { parseTranscript, timedLines, toSegments, type ImportLine } from './transcriptImport'++/**+ * Meetings brought in from other notes apps (Granola, Otter, Fireflies, …) through an AI app that read them there.+ * They have no audio; they show, search and answer in Ask like meetings recorded here (source "import").+ */++/** the most lines one meeting brings, and one call across a batch */+export const IMPORT_LINES_MAX = 20_000+export const IMPORT_BATCH_MAX = 50+const BATCH_LINES_MAX = 50_000+const LINE_MAX = 10_000+const TEXT_MAX = 2_000_000++const meetingProps = {+ title: { type: 'string', description: `At most ${TITLE_MAX} characters` },+ started_at: { type: 'string', description: 'When it started, ISO time (2026-11-03T15:00:00Z)' },+ ended_at: { type: 'string', description: 'When it ended, ISO time; from the transcript when left out' },+ attendees: { type: 'array', description: `Who was in it, at most ${PEOPLE_MAX}`, items: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' } }, required: ['name'] } },+ transcript: { type: 'string', description: 'The transcript as text, as the other app exports it: "[mm:ss] Name: words", "Name (00:12:34): words", "Name: words", or a "Name 0:05" line with the words under it. Words with no name stay unnamed.' },+ transcript_lines: { type: 'array', description: `The transcript as lines instead, at most ${IMPORT_LINES_MAX}`, items: { type: 'object', properties: { start_ms: { type: 'number' }, end_ms: { type: 'number' }, speaker: { type: 'string' }, text: { type: 'string' } }, required: ['text'] } },+ summary: { type: 'string', description: "The other app's summary (Markdown), kept as the meeting's summary" },+ my_notes: { type: 'string', description: "The person's own notes (Markdown)" },+ folder: { type: 'string', description: 'A folder to file it in: its id or name, from list_folders' },+ create_folder: { type: 'boolean', description: 'Make the folder when there is none by that name' },+ write_summary: { type: 'boolean', description: 'Have Yogurt write the summary from the transcript, instead of giving one' },+ source_id: { type: 'string', description: "The meeting's id in the other app: the same one is never brought in twice" },+}+const required = ['title', 'started_at']+const adding = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }+export const importTools: Tool[] = [+ { name: 'create_meeting', description: "Brings one meeting into Yogurt from another notes app (Granola, Otter, Fireflies, …): title, start, people, the transcript (text or lines), and the other app's summary or Yogurt's own (write_summary). It has no recording. It shows in Yogurt, in search and in ask like a meeting recorded there. Gives its id.",+ inputSchema: { type: 'object', properties: meetingProps, required }, annotations: adding },+ { name: 'import_meetings', description: `Brings several meetings in at once, each as create_meeting takes it: at most ${IMPORT_BATCH_MAX} a call. Gives each one's id or why it was not brought in.`,+ inputSchema: { type: 'object', properties: { meetings: { type: 'array', items: { type: 'object', properties: meetingProps, required } } }, required: ['meetings'] }, annotations: adding },+]++/** lines given as JSON, checked one by one */+function linesOf(v: unknown[]): ImportLine[] {+ return v.map((l, i) => {+ if (!l || typeof l !== 'object') throw new Refusal(`transcript_lines[${i}] must be an object with text.`)+ const a = l as Args+ const ms = (key: string) => {+ const x = a[key]+ if (x === undefined || x === null) return null+ if (typeof x !== 'number' || !Number.isFinite(x) || x < 0) throw new Refusal(`transcript_lines[${i}].${key} must be a number of ms from the start, 0 or more.`)+ return Math.round(x)+ }+ const speaker = str(a, 'speaker', { max: 200 })+ return { startMs: ms('start_ms'), endMs: ms('end_ms'), speaker: speaker || null, text: str(a, 'text', { max: LINE_MAX, required: true })! }+ })+}++export function importHandlers({ d, folderOf, log }: Ctx): Record<string, (a: Args) => Promise<string>> {+ const s = d.store+ /** one meeting, checked whole before anything is saved */+ const check = (a: Args) => {+ const title = str(a, 'title', { max: TITLE_MAX, required: true })!.replace(/\s+/g, ' ')+ const startedAt = time(a, 'started_at', { required: true })!+ const endedAt = time(a, 'ended_at')+ if (endedAt != null && endedAt < startedAt) throw new Refusal('ended_at is before started_at.')+ const attendees = people(list(a, 'attendees', { max: PEOPLE_MAX }) ?? [], 'attendees')+ const text = str(a, 'transcript', { max: TEXT_MAX, keepSpace: true })+ const given = list(a, 'transcript_lines', { max: IMPORT_LINES_MAX })+ if (text && given) throw new Refusal('Give transcript or transcript_lines, not both.')+ const lines = given ? linesOf(given) : text ? parseTranscript(text) : []+ if (lines.length > IMPORT_LINES_MAX) throw new Refusal(`The transcript has ${lines.length} lines: at most ${IMPORT_LINES_MAX}.`)+ const summary = str(a, 'summary', { max: NOTES_MAX, keepSpace: true })+ const mine = str(a, 'my_notes', { max: NOTES_MAX, keepSpace: true })+ const writeSummary = bool(a, 'write_summary') === true+ if (writeSummary && summary?.trim()) throw new Refusal('Give a summary or write_summary, not both.')+ if (writeSummary && !lines.length && !mine?.trim()) throw new Refusal('write_summary needs a transcript or my_notes to write from.')+ if (!lines.length && !summary?.trim() && !mine?.trim()) throw new Refusal('Give a transcript, a summary or my_notes: a meeting with nothing in it is not brought in.')+ const sourceId = str(a, 'source_id', { max: 200 })+ const createFolder = bool(a, 'create_folder') === true+ const folderName = str(a, 'folder', { max: 200 })+ let folder: ReturnType<typeof folderOf>+ try { folder = folderOf(folderName) } catch (e) { if (!(e instanceof Refusal) || !createFolder) throw e }+ return { title, startedAt, endedAt, attendees, lines, summary: summary?.trim() ? summary : null, mine: mine ?? '', writeSummary, sourceId, folder, newFolder: !folder && createFolder ? folderName : undefined }+ }+ const save = (m: ReturnType<typeof check>) => {+ const already = m.sourceId ? s.meetingFromSource('import', m.sourceId) : undefined+ if (already) return { id: already.id, title: already.title, already_imported: true }+ const timed = timedLines(m.lines)+ const meeting = s.createMeeting({ title: m.title, titleSource: 'user', startedAt: m.startedAt, endedAt: m.endedAt ?? m.startedAt + (timed.at(-1)?.endMs ?? 0),+ eventId: null, app: null, attendees: m.attendees, keepAttendees: true, state: 'done', source: 'import', ...(m.sourceId ? { sourceId: m.sourceId } : {}) })+ try {+ if (timed.length) s.addSegments(toSegments(meeting.id, timed, d.me()))+ // the other app's summary counts as edited, so new people never have it rewritten by itself+ s.setNotes(meeting.id, { mine: m.mine, enhanced: m.summary, edited: m.summary != null })+ const f = m.folder ?? (m.newFolder ? s.folders().find((x) => x.name.toLowerCase() === m.newFolder!.toLowerCase()) ?? s.createFolder(m.newFolder) : undefined)+ if (f) s.addToFolder(f.id, meeting.id)+ log(`create_meeting made ${meeting.id}: ${timed.length} lines${m.summary ? ', a summary' : ''}${f ? `, in ${f.id}` : ''}`)+ d.app.imported(meeting.id)+ if (f) d.app.changed('folders')+ if (m.writeSummary) d.app.rewriteSummary(meeting.id, '')+ return { id: meeting.id, title: meeting.title, start: new Date(meeting.startedAt).toISOString(), lines: timed.length, folder: f ? { id: f.id, name: f.name } : null,+ summary: m.summary ? 'given' : m.writeSummary ? (d.app.notesReady() ? 'Yogurt is writing it' : 'Yogurt writes it once its notes model has downloaded') : 'none' }+ } catch (e) { s.deleteMeeting(meeting.id); throw e }+ }+ return {+ async create_meeting(a) { return JSON.stringify(save(check(a)), null, 2) },+ async import_meetings(a) {+ const all = list(a, 'meetings', { max: IMPORT_BATCH_MAX, required: true })!+ const checked = all.map((m, i) => {+ if (!m || typeof m !== 'object' || Array.isArray(m)) return { index: i, error: 'Each meeting must be an object, as create_meeting takes it.' }+ try { return { index: i, meeting: check(m as Args) } } catch (e) { if (e instanceof Refusal) return { index: i, error: e.message }; throw e }+ })+ const total = checked.reduce((n, c) => n + ('meeting' in c && c.meeting ? c.meeting.lines.length : 0), 0)+ if (total > BATCH_LINES_MAX) throw new Refusal(`These meetings have ${total} transcript lines together: at most ${BATCH_LINES_MAX} a call. Send fewer at a time.`)+ return JSON.stringify(checked.map((c) => ('meeting' in c && c.meeting ? { index: c.index, ...save(c.meeting) } : c)), null, 2)+ },+ }+}diff --git a/app/src/main/mcp/index.ts b/app/src/main/mcp/index.tsindex c6482ed0..f7442ea1 100644--- a/app/src/main/mcp/index.ts+++ b/app/src/main/mcp/index.ts@@ -4,7 +4,7 @@ import { existsSync, renameSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { helperFile } from '../../shared/platform'import type { Store } from '../store'-import { createMcp } from './server'+import { createMcp, type McpApp } from './server'import { helperCopyPath, installHelper, LAUNCH_FILE, launchCommand, mcpAddress, PIPE_FILE } from './paths'import { serveMcp } from './socket'@@ -39,11 +39,15 @@ function copyHelper(profile: string): string | undefined {export async function hookMcp(d: {/** the profile folder: the socket (Mac, Linux) or the pipe's name (Windows) is there, for the helper */store: Store; profile: string; enabled: () => boolean; setEnabled: (on: boolean) => void; me: () => string; version: string+ /** "Let AI apps make changes": off unless the person turned it on */+ changesEnabled: () => boolean; setChangesEnabled: (on: boolean) => void+ /** the app's own actions, for the tools that ask or change something */+ app: McpAppaudio: (id: string) => Promise<Array<{ track: 'me' | 'them'; path: string }>>/** Settings is told when apps come and go */send: (clients: string[]) => void}) {- const mcp = createMcp({ store: d.store, enabled: d.enabled, me: d.me, version: d.version, audio: d.audio, platform: process.platform })+ const mcp = createMcp({ store: d.store, enabled: d.enabled, changesEnabled: d.changesEnabled, me: d.me, version: d.version, audio: d.audio, app: d.app, platform: process.platform })let server: Awaited<ReturnType<typeof serveMcp>> | undefinedconst address = mcpAddress(process.platform, d.profile, randomBytes(16).toString('hex'))try {@@ -54,8 +58,9 @@ export async function hookMcp(d: {const launch = launchCommand(process.platform, app.isPackaged, process.execPath, process.env)if (launch) { try { writeWhole(join(d.profile, LAUNCH_FILE), launch) } catch (e) { console.error('mcp: could not record how to open Yogurt', e) } }const copy = copyHelper(d.profile)- const status = () => ({ enabled: d.enabled(), clients: server?.clients() ?? [], command: copy ?? mcpHelperPath() })+ const status = () => ({ enabled: d.enabled(), changes: d.changesEnabled(), clients: server?.clients() ?? [], command: copy ?? mcpHelperPath() })ipcMain.handle('mcp:status', status)ipcMain.handle('mcp:set', (_e, on: unknown) => { d.setEnabled(on === true); return status() })+ ipcMain.handle('mcp:set-changes', (_e, on: unknown) => { d.setChangesEnabled(on === true); return status() })return { close: () => server?.close() }}diff --git a/app/src/main/mcp/server.ts b/app/src/main/mcp/server.tsindex 7ba74ed9..1528f1e3 100644--- a/app/src/main/mcp/server.ts+++ b/app/src/main/mcp/server.ts@@ -1,65 +1,140 @@import { AUDIO_SPEAKER } from '../../shared/audioUpload'-import type { Meeting, Store } from '../store'+import type { ContextChip } from '../../shared/askContext'+import { toMarkdownFile } from '../../shared/exportNotes'+import type { LibrarySource, StartResult } from '../../shared/types'+import type { CalEvent, CalendarStatus } from '../calendar'+import type { Meeting, Person, Store } from '../store'+import { Refusal, str, list, oneOf, day, type Args } from './args'+import { changeTools, changeHandlers } from './changes'+import { importTools, importHandlers } from './importMeeting'/**- * Yogurt as an MCP server, so an AI app on this Mac (Claude, Cursor, …) can read the person's meetings: JSON-RPC- * messages in, answers out (socket.ts carries them; the yogurt-mcp helper connects the app to it). Reading only.+ * Yogurt as an MCP server, so an AI app on this Mac (Claude, Cursor, …) can use the person's meetings: JSON-RPC+ * messages in, answers out (socket.ts carries them; the yogurt-mcp helper connects the app to it).* Off until the person turns it on in Settings: until then every tool says where to turn it on and gives nothing.+ * Reading is all it does unless the person also lets AI apps make changes; then each change goes through the same+ * functions the app's own buttons use. Nothing is ever deleted for good: meetings go to the Trash.* Text here goes to the other app's model, never to Yogurt's interface, so it is not translated.*/type Track = 'me' | 'them'+export type SaveOutcome = 'saved' | 'busy' | 'too-long' | 'failed'+/** what the app does for AI apps: the functions behind its own buttons (index.ts), so nothing is done twice over */+export type McpApp = {+ ask(question: string, chips: ContextChip[]): Promise<{ unavailable: 'model' | 'recording' } | { answer: string; sources: LibrarySource[]; stopped?: true }>+ comingUp(): Promise<{ status: CalendarStatus; events: CalEvent[] }>+ calendarDay(at: number): Promise<{ status: CalendarStatus; events: CalEvent[] }>+ settings(): { myName: string; locale: string; spoken: 'en' | 'multi'; summaryLanguage: string; jargon: string[]; stopWhenCallEnds: boolean; keepRecordings: boolean }+ /** the windows hear that meetings or folders changed */+ changed(what: 'meetings' | 'folders'): void+ /** a meeting came in from another app: shown, searched and read for Ask like one recorded here */+ imported(id: string): void+ rename(id: string, title: string): boolean+ setAttendees(id: string, people: Person[]): boolean+ linkEvent(id: string, eventId: string, day?: number): Promise<boolean>+ unlinkEvent(id: string): boolean+ trash(id: string): 'trashed' | 'recording' | 'missing' | 'failed' | 'save-pending'+ restore(id: string): boolean+ setMyNotes(id: string, md: string): SaveOutcome+ setSummary(id: string, md: string): SaveOutcome+ /** "Write again", with the person's instruction if any */+ rewriteSummary(id: string, instruction: string): 'queued' | 'busy'+ notesReady(): boolean+ startRecording(o: { title?: string; eventId?: string }): Promise<StartResult>+ pauseRecording(id: string, paused: boolean): boolean+ stopRecording(id: string): boolean+ recording(): Meeting | null+ setJargon(terms: string[]): string[]+ setSpoken(v: 'en' | 'multi'): boolean+ setSummaryLanguage(v: string): boolean+}export type McpDeps = {- store: Pick<Store, 'meeting' | 'meetings' | 'segments' | 'notes' | 'search' | 'folders' | 'foldersOf' | 'folderMeetingIds'>+ store: Storeenabled: () => boolean+ /** Settings' "Let AI apps make changes": off unless the person turned it on */+ changesEnabled: () => boolean/** the person using Yogurt, by name: "You" means nothing to another app */me: () => stringversion: string/** a finished meeting's audio files (none while it records) */audio: (id: string) => Promise<Array<{ track: Track; path: string }>>+ app: McpApp/** the computer, for the words other apps' models read (a Mac when left out) */platform?: string+ /** main.log, which goes in public issues: ids and outcomes only, never names or words */+ log?: (line: string) => void}export type Mcp = { handle(msg: unknown): Promise<object | null> }+export type Tool = { name: string; description: string; inputSchema: object; annotations: object }/** newest first: the app asked for one of these, it gets that one; otherwise the newest */const VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']-const id = { type: 'string', description: 'The meeting id, from list_meetings or search' }-const folder = { type: 'string', description: 'Only meetings in this folder: its id or name, from list_folders' }+export const idArg = { type: 'string', description: 'The meeting id, from list_meetings or search' }+export const folderArg = { type: 'string', description: 'A folder: its id or name, from list_folders' }+const inFolder = { type: 'string', description: 'Only meetings in this folder: its id or name, from list_folders' }+const person = { type: 'string', description: 'Only meetings with this person: their name or email, from list_people' }const readOnly = { readOnlyHint: true, destructiveHint: false, openWorldHint: false }-/** The tools, in this computer's words: a Mac records AAC in .m4a, Windows and Linux Ogg Opus (a backup can bring either) */-export const mcpTools = (platform: string) => [+/** The reading tools, in this computer's words: a Mac records AAC in .m4a, Windows and Linux Ogg Opus (a backup can bring either) */+const readTools = (platform: string): Tool[] => [{ name: 'list_folders', description: 'The folders the person files meetings in: id, name and how many meetings each holds. Pass a folder to list_meetings or search to read only its meetings.',inputSchema: { type: 'object', properties: {} } },- { name: 'list_meetings', description: 'Meetings recorded in Yogurt, newest first: id, title, start and end (ISO times), people invited (attendees: name and email from the calendar), call app, and the folders it is in. Optional query finds meetings by words in their title, transcript or notes; optional folder keeps only that folder\'s meetings.',- inputSchema: { type: 'object', properties: { query: { type: 'string' }, folder, limit: { type: 'number', description: 'Most to return (default 20, at most 100)' }, before: { type: 'string', description: 'Only meetings that started before this ISO time, to page back' } } } },- { name: 'get_meeting', description: "One meeting: its details, its attendees with their emails, the calendar event it is linked to (calendar_event: title, start, end, calendar; null when none), the notes the person typed (myNotes) and Yogurt's written summary (Markdown).",- inputSchema: { type: 'object', properties: { id }, required: ['id'] } },+ { name: 'list_meetings', description: 'Meetings recorded in Yogurt, newest first: id, title, start and end (ISO times), people invited (attendees: name and email from the calendar), call app, and the folders it is in. Optional query finds meetings by words in their title, transcript or notes; optional folder keeps only that folder\'s meetings; optional person keeps only meetings with them.',+ inputSchema: { type: 'object', properties: { query: { type: 'string' }, folder: inFolder, person, limit: { type: 'number', description: 'Most to return (default 20, at most 100)' }, before: { type: 'string', description: 'Only meetings that started before this ISO time, to page back' } } } },+ { name: 'get_meeting', description: "One meeting: its details, its attendees with their emails, the calendar event it is linked to (calendar_event: title, start, end, calendar; null when none), the folder Yogurt suggests for it (suggested_folder, null when none), the notes the person typed (myNotes) and Yogurt's written summary (Markdown).",+ inputSchema: { type: 'object', properties: { id: idArg }, required: ['id'] } },{ name: 'get_transcript', description: 'What was said in a meeting, line by line with who said it. format "text" (default): "[mm:ss] Name: words" lines. format "lines": JSON with start_ms, end_ms, speaker, is_me and text. "Them" is the other side of the call when the call app gave no name.',- inputSchema: { type: 'object', properties: { id, format: { type: 'string', enum: ['text', 'lines'] } }, required: ['id'] } },- { name: 'search', description: 'Finds words across every meeting (titles, transcripts, notes): meeting id, title, start and a snippet with the matched words in **bold**.',- inputSchema: { type: 'object', properties: { query: { type: 'string' }, folder, limit: { type: 'number', description: 'Most meetings to return (default 20, at most 100)' } }, required: ['query'] } },+ inputSchema: { type: 'object', properties: { id: idArg, format: { type: 'string', enum: ['text', 'lines'] } }, required: ['id'] } },+ { name: 'search', description: 'Finds words across every meeting (titles, transcripts, notes): meeting id, title, start and a snippet with the matched words in **bold**. Optional person keeps only meetings with them.',+ inputSchema: { type: 'object', properties: { query: { type: 'string' }, folder: inFolder, person, limit: { type: 'number', description: 'Most meetings to return (default 20, at most 100)' } }, required: ['query'] } },+ { name: 'ask', description: "Yogurt answers a question from the person's meetings itself, on this computer, with numbered sources ([1], [2]) naming the meeting and the moment. Optional folder or meeting_ids limit what it reads. Slower than search (it writes an answer); use it for questions that need meetings read and put together.",+ inputSchema: { type: 'object', properties: { question: { type: 'string' }, folder: { type: 'string', description: 'Only meetings in this folder' }, meeting_ids: { type: 'array', items: { type: 'string' }, description: 'Only these meetings (at most 40)' } }, required: ['question'] } },+ { name: 'list_people', description: "The people in the person's meetings: name and email (null when the calendar gave none). Pass one as person to list_meetings or search.",+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Most to return (default 200, at most 1000)' } } } },+ { name: 'upcoming_meetings', description: "What is on the person's calendar for the rest of today and tomorrow, soonest first: event_id, title, start, end, calendar, meeting_link (the call's address, null when none), attendees, and meeting_id when Yogurt already has notes for it.",+ inputSchema: { type: 'object', properties: {} } },+ { name: 'calendar_day', description: "The events on one day of the person's calendar, earliest first, the same way upcoming_meetings gives them.",+ inputSchema: { type: 'object', properties: { date: { type: 'string', description: 'The day, like 2026-11-03' } }, required: ['date'] } },+ { name: 'list_trash', description: 'Meetings in the Trash: id, title, start and when they were moved there. They are deleted for good 30 days after. restore_meeting brings one back.',+ inputSchema: { type: 'object', properties: {} } },+ { name: 'get_settings', description: "Yogurt's settings that shape notes: the person's name, the interface language, the language spoken in meetings, the language summaries are written in, custom words spelled right in transcripts, whether recording stops when a call ends, and whether audio is kept.",+ inputSchema: { type: 'object', properties: {} } },+ { name: 'export_meeting', description: "A meeting as one Markdown document, exactly as Yogurt's Export Markdown saves it: title, date, people, the notes, and the transcript. side \"summary\" (default) uses Yogurt's summary, \"my_notes\" the person's own notes.",+ inputSchema: { type: 'object', properties: { id: idArg, side: { type: 'string', enum: ['summary', 'my_notes'] } }, required: ['id'] } },{ name: 'get_audio', description: platform === 'darwin'? "A meeting's recording as files on this Mac: one per side (track me: the person's microphone; them: the other side of the call), AAC in .m4a. Gives paths, which apps on this Mac can open.": "A meeting's recording as files on this computer: one per side (track me: the person's microphone; them: the other side of the call), Ogg Opus in .ogg (AAC in .m4a for a meeting recorded on a Mac). Gives paths, which apps on this computer can open.",- inputSchema: { type: 'object', properties: { id }, required: ['id'] } },+ inputSchema: { type: 'object', properties: { id: idArg }, required: ['id'] } },].map((t) => ({ ...t, annotations: readOnly }))+export const mcpTools = (platform: string): Tool[] => [...readTools(platform), ...changeTools, ...importTools]export const MCP_TOOLS = mcpTools('darwin')+/** the tools that change something: only with "Let AI apps make changes" on */+const CHANGES = new Set([...changeTools, ...importTools].map((t) => t.name))-class Refusal extends Error {}--const iso = (ms: number | null) => (ms == null ? null : new Date(ms).toISOString())+export const iso = (ms: number | null | undefined) => (ms == null ? null : new Date(ms).toISOString())const clock = (ms: number) => { const s = Math.floor(ms / 1000); const h = Math.floor(s / 3600), m = Math.floor(s / 60) % 60, sec = s % 60; const p = (n: number) => String(n).padStart(2, '0'); return h ? `${h}:${p(m)}:${p(sec)}` : `${p(m)}:${p(sec)}` }-const limitOf = (v: unknown) => (typeof v === 'number' && v >= 1 ? Math.min(100, Math.floor(v)) : 20)+const limitOf = (v: unknown, def = 20, max = 100) => (typeof v === 'number' && v >= 1 ? Math.min(max, Math.floor(v)) : def)const text = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)+/** only ids go in the log: a meeting's or folder's id is a UUID, a name is not */+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++/** what the change and import tools share with the reading ones */+export type Ctx = {+ d: McpDeps+ meetingOf: (v: unknown) => Meeting+ folderOf: (v: unknown) => ReturnType<Store['folders']>[number] | undefined+ summary: (m: Meeting) => object+ log: (line: string) => void+}export function createMcp(d: McpDeps): Mcp {const mac = (d.platform ?? 'darwin') === 'darwin'const listed = mcpTools(d.platform ?? 'darwin')+ const log = d.log ?? ((line: string) => console.info('MCP', line))// the calendar's people with their emails (null when the calendar gave none): another app can write to them or match themconst summary = (m: Meeting) => ({ id: m.id, title: m.title, start: iso(m.startedAt), end: iso(m.endedAt), people: m.attendees.map((a) => a.name),attendees: m.attendees.map((a) => ({ name: a.name, email: a.email ?? null })), app: m.app, recording: m.state === 'recording',+ ...(m.source === 'import' ? { imported: true } : {}),folders: d.store.foldersOf(m.id).map((f) => ({ id: f.id, name: f.name })) })/** a folder by id or name (any case); an unknown one names the folders there are */const folderOf = (v: unknown) => {@@ -70,6 +145,16 @@ export function createMcp(d: McpDeps): Mcp {if (!f) throw new Refusal(`No folder ${JSON.stringify(want)}. The folders are: ${all.map((x) => x.name).join(', ') || 'none yet'}.`)return f}+ /** a person by email or full name (any case); an unknown one names a few people there are */+ const personOf = (v: unknown): Person | undefined => {+ const want = text(v)?.toLowerCase()+ if (!want) return undefined+ const all = d.store.searchPeople()+ const p = all.find((x) => x.email?.toLowerCase() === want) ?? all.find((x) => x.name.trim().toLowerCase() === want)+ if (p) return p+ const close = all.filter((x) => want.split(/\s+/).some((w) => x.name.toLowerCase().includes(w) || x.email?.toLowerCase().includes(w))).slice(0, 10)+ throw new Refusal(`No one called ${JSON.stringify(text(v))} is in the meetings. ${close.length ? `Close: ${close.map((x) => x.email ? `${x.name} <${x.email}>` : x.name).join(', ')}.` : 'list_people gives everyone.'}`)+ }/** the calendar event the meeting is linked to, as last read (it stays without calendar access); null for none */const calendarEvent = (m: Meeting) => (m.eventId? { title: m.eventTitle ?? null, start: iso(m.eventStartedAt ?? null), end: iso(m.eventEndedAt ?? null), calendar: m.eventCalendarName ?? null }@@ -80,9 +165,29 @@ export function createMcp(d: McpDeps): Mcp {if (!m || m.trashedAt != null) throw new Refusal(`No meeting with id ${JSON.stringify(v ?? null)}. list_meetings or search gives the ids.`)return m}+ /** the folder Yogurt suggests for a meeting not filed yet, as the note's header offers it */+ const suggestedFolder = (m: Meeting) => {+ if (d.store.foldersOf(m.id).length) return null+ const s = d.store.folderSuggestion(m.id)+ const f = s.state === 'pending' && s.folderId ? d.store.folder(s.folderId) : undefined+ return f ? { id: f.id, name: f.name } : null+ }const who = (speaker: string | null, track: Track) => (speaker === AUDIO_SPEAKER ? 'Audio' : track === 'me' || speaker === 'me' ? d.me() || 'You' : speaker || 'Them')+ const events = (r: { status: CalendarStatus; events: CalEvent[] }) => {+ if (!r.events.length && r.status !== 'granted') {+ return r.status === 'unsupported' ? 'Yogurt has no calendar on this computer. The person can add a calendar link in Yogurt: Settings, Calendars.'+ : `Yogurt can't read the calendar (${r.status === 'error' ? 'reading it failed' : 'it has no access'}). The person can connect it in Yogurt: Settings, Calendars.`+ }+ return JSON.stringify(r.events.map((e) => {+ const note = [e.id, ...(e.aliases ?? [])].map((id) => d.store.meetingForEvent(id)).find((m) => m && m.trashedAt == null)+ return { event_id: e.id, title: e.title, start: iso(e.start), end: iso(e.end), calendar: e.calendar?.name ?? null, meeting_link: e.url?.trim() || null,+ attendees: e.attendees.map((a) => ({ name: a.name, email: a.email ?? null })), meeting_id: note?.id ?? null }+ }), null, 2)+ }+ /** a person narrows search the way search's people chips do (all their meetings, newest first, before the limit) */+ const searchIn = (q: string, limit: number, folder?: string, p?: Person) => (p ? d.store.search(q, Infinity, folder, { people: [p] }) : d.store.search(q, limit, folder))- const tools: Record<string, (a: Record<string, unknown>) => Promise<string>> = {+ const tools: Record<string, (a: Args) => Promise<string>> = {async list_folders() {return JSON.stringify(d.store.folders().map((f) => ({ id: f.id, name: f.name, meetings: f.count })), null, 2)},@@ -90,18 +195,20 @@ export function createMcp(d: McpDeps): Mcp {const limit = limitOf(a.limit)const q = text(a.query)const f = folderOf(a.folder)+ const p = personOf(a.person)const before = text(a.before) ? Date.parse(String(a.before)) : undefined- const found = q- ? d.store.search(q, limit, f?.id).map((h) => d.store.meeting(h.meetingId)).filter((m): m is Meeting => !!m && (before == null || m.startedAt < before))+ const earlier = (m: Meeting | undefined): m is Meeting => !!m && (before == null || Number.isNaN(before) || m.startedAt < before)+ const found = q || p+ ? searchIn(q ?? '', limit, f?.id, p).map((h) => d.store.meeting(h.meetingId)).filter(earlier).slice(0, limit): f- ? d.store.folderMeetingIds(f.id).map((mid) => d.store.meeting(mid)).filter((m): m is Meeting => !!m && (before == null || Number.isNaN(before) || m.startedAt < before)).slice(0, limit)+ ? d.store.folderMeetingIds(f.id).map((mid) => d.store.meeting(mid)).filter(earlier).slice(0, limit): d.store.meetings({ before: Number.isNaN(before) ? undefined : before, limit })return JSON.stringify(found.map(summary), null, 2)},async get_meeting(a) {const m = meetingOf(a.id)const n = d.store.notes(m.id)- return JSON.stringify({ ...summary(m), calendar_event: calendarEvent(m), myNotes: n.mine, summary: n.enhanced }, null, 2)+ return JSON.stringify({ ...summary(m), calendar_event: calendarEvent(m), suggested_folder: suggestedFolder(m), myNotes: n.mine, summary: n.enhanced }, null, 2)},async get_transcript(a) {const m = meetingOf(a.id)@@ -112,11 +219,49 @@ export function createMcp(d: McpDeps): Mcp {async search(a) {const q = text(a.query)if (!q) throw new Refusal('search needs a query.')- return JSON.stringify(d.store.search(q, limitOf(a.limit), folderOf(a.folder)?.id).flatMap((h) => {+ const limit = limitOf(a.limit)+ return JSON.stringify(searchIn(q, limit, folderOf(a.folder)?.id, personOf(a.person)).slice(0, limit).flatMap((h) => {const m = d.store.meeting(h.meetingId)return m ? [{ meeting_id: m.id, title: m.title, start: iso(m.startedAt), snippet: h.parts.map((p) => (p.hit ? `**${p.text}**` : p.text)).join('') || h.snippet }] : []}), null, 2)},+ async ask(a) {+ const question = str(a, 'question', { max: 4000, required: true })!+ const f = folderOf(a.folder)+ const ids = (list(a, 'meeting_ids', { max: 40 }) ?? []).map((id) => meetingOf(id).id)+ const chips: ContextChip[] = [...(f ? [{ kind: 'folder' as const, id: f.id }] : []), ...[...new Set(ids)].map((id) => ({ kind: 'meeting' as const, id }))]+ const got = await d.app.ask(question, chips)+ if ('unavailable' in got) {+ throw new Refusal(got.unavailable === 'model'+ ? "Yogurt's notes model is still downloading, so it can't answer questions yet. Use search and get_transcript instead, or ask again later."+ : `Yogurt is recording a meeting, and on this ${mac ? 'Mac' : 'computer'} it answers questions once the recording ends. Use search and get_transcript meanwhile.`)+ }+ return JSON.stringify({+ answer: got.answer, ...(got.stopped ? { note: 'The answer took too long and was stopped; this is what was written.' } : {}),+ sources: got.sources.map((s) => ({ n: s.n, meeting_id: s.meetingId, title: s.title, start: iso(s.startedAt), at: s.atMs == null ? null : clock(s.atMs), excerpt: s.excerpt?.slice(0, 600) ?? null })),+ }, null, 2)+ },+ async list_people(a) {+ return JSON.stringify(d.store.searchPeople().slice(0, limitOf(a.limit, 200, 1000)).map((p) => ({ name: p.name, email: p.email ?? null })), null, 2)+ },+ async upcoming_meetings() { return events(await d.app.comingUp()) },+ async calendar_day(a) { return events(await d.app.calendarDay(day(a, 'date', { required: true })!)) },+ async list_trash() {+ return JSON.stringify(d.store.trashed().map((m) => ({ id: m.id, title: m.title, start: iso(m.startedAt), trashed_at: iso(m.trashedAt) })), null, 2)+ },+ async get_settings() {+ const s = d.app.settings()+ return JSON.stringify({ my_name: s.myName, interface_language: s.locale,+ spoken_language: s.spoken === 'multi' ? 'multi (any language, heard per meeting)' : 'en (English only)',+ summary_language: s.summaryLanguage || "each meeting's own language", custom_words: s.jargon,+ stop_recording_when_call_ends: s.stopWhenCallEnds, keep_audio_recordings: s.keepRecordings }, null, 2)+ },+ async export_meeting(a) {+ const m = meetingOf(a.id)+ const n = d.store.notes(m.id)+ const side = oneOf(a, 'side', ['summary', 'my_notes'] as const) ?? 'summary'+ return toMarkdownFile(m, side === 'summary' && n.enhanced != null ? n.enhanced : n.mine, d.store.segments(m.id))+ },async get_audio(a) {const m = meetingOf(a.id)if (m.state === 'recording') throw new Refusal('This meeting is still being recorded. Its audio is ready once it stops.')@@ -124,10 +269,17 @@ export function createMcp(d: McpDeps): Mcp {return JSON.stringify({ files }, null, 2)},}+ const ctx: Ctx = { d, meetingOf, folderOf, summary, log }+ Object.assign(tools, changeHandlers(ctx), importHandlers(ctx))const ok = (msgId: unknown, result: object) => ({ jsonrpc: '2.0', id: msgId, result })const fail = (msgId: unknown, code: number, message: string) => ({ jsonrpc: '2.0', id: msgId ?? null, error: { code, message } })const said = (msgId: unknown, body: string, isError = false) => ok(msgId, { content: [{ type: 'text', text: body }], ...(isError ? { isError: true } : {}) })+ /** a change, by tool and the ids it named: what happened, for main.log */+ const logged = (name: string, a: Args, outcome: string) => {+ const ids = Object.values(a).filter((v): v is string => typeof v === 'string' && UUID.test(v))+ log(`${name} ${outcome}${ids.length ? ` ${ids.join(' ')}` : ''}`)+ }return {async handle(msg) {@@ -141,7 +293,8 @@ export function createMcp(d: McpDeps): Mcp {protocolVersion: VERSIONS.includes(String(asked)) ? asked : VERSIONS[0],capabilities: { tools: {} },serverInfo: { name: 'yogurt', title: 'Yogurt', version: d.version },- instructions: `Yogurt holds the person's meeting notes, transcripts and recordings on this ${mac ? 'Mac' : 'computer'}. Use list_meetings or search to find a meeting, then get_meeting, get_transcript or get_audio.`,+ instructions: `Yogurt holds the person's meeting notes, transcripts and recordings on this ${mac ? 'Mac' : 'computer'}. Use list_meetings or search to find a meeting, then get_meeting, get_transcript or get_audio.`+ + " With changes allowed in Yogurt's Settings, it can also file and edit meetings, take notes of a call, and bring in meetings from other notes apps (create_meeting).",})}if (method === 'ping') return ok(msgId, {})@@ -149,11 +302,22 @@ export function createMcp(d: McpDeps): Mcp {if (method === 'tools/call') {const name = String(params?.name ?? '')const tool = tools[name]+ const a = params?.arguments && typeof params.arguments === 'object' && !Array.isArray(params.arguments) ? params.arguments as Args : {}if (!tool) return said(msgId, `Yogurt has no tool called ${name}.`, true)if (!d.enabled()) return said(msgId, 'Yogurt has connecting AI apps turned off. The person can turn it on in Yogurt: Settings, AI apps.', true)- try { return said(msgId, await tool((params?.arguments as Record<string, unknown>) ?? {})) } catch (e) {- if (e instanceof Refusal) return said(msgId, e.message, true)+ const change = CHANGES.has(name)+ if (change && !d.changesEnabled()) {+ logged(name, a, 'refused: changes off')+ return said(msgId, 'Yogurt lets AI apps read meetings but not change them. The person can allow changes in Yogurt: Settings, AI apps, "Let AI apps make changes".', true)+ }+ try {+ const body = await tool(a)+ if (change) logged(name, a, 'ok')+ return said(msgId, body)+ } catch (e) {+ if (e instanceof Refusal) { if (change) logged(name, a, 'refused'); return said(msgId, e.message, true) }console.error(`mcp: ${name} failed`, e)+ if (change) logged(name, a, 'failed')return said(msgId, `Yogurt couldn't do that (${name}). Try again.`, true)}}diff --git a/app/src/main/settings.ts b/app/src/main/settings.tsindex 6958d3ab..fc638dd1 100644--- a/app/src/main/settings.ts+++ b/app/src/main/settings.ts@@ -32,6 +32,8 @@ export type Settings = { theme?: 'light' | 'dark'; language?: string; /** what taxAsked?: boolean/** AI apps on this Mac (Claude, Cursor, …) may read meetings through MCP; off unless the person turned it on */aiApps?: boolean+ /** those AI apps may also change meetings, notes and a few settings (never delete for good); off unless turned on */+ aiAppChanges?: boolean/** a recording stops by itself when its call ends; on unless turned off (false: ask first) */stopWhenCallEnds?: boolean/** a quiet reminder to ask everyone before recording; on unless turned off */diff --git a/app/test/mcp.test.ts b/app/test/mcp.test.tsindex 23abb803..fa29151a 100644--- a/app/test/mcp.test.ts+++ b/app/test/mcp.test.ts@@ -1,52 +1,13 @@-import { afterEach, describe, expect, it } from 'vitest'-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { writeFileSync } from 'node:fs'import { connect } from 'node:net'-import { tmpdir } from 'node:os'import { join } from 'node:path'-import { openStore, type Store } from '../src/main/store'-import { createMcp, MCP_TOOLS, type Mcp } from '../src/main/mcp/server'+import { MCP_TOOLS } from '../src/main/mcp/server'+import { setup, call, json } from './mcpRig'import { serveMcp } from '../src/main/mcp/socket'import { mcpAddress } from '../src/main/mcp/paths'import { randomBytes } from 'node:crypto'-const dirs: string[] = []-const stores: Store[] = []-afterEach(() => {- stores.splice(0).forEach((s) => s.close())- dirs.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }))-})-const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'yogurt-mcp-')); dirs.push(d); return d }--function setup(o: { enabled?: boolean; platform?: string } = {}) {- const dir = tmp()- const store = openStore(join(dir, 'yogurt.db')); stores.push(store)- const base = { endedAt: null, eventId: null, app: 'Zoom', state: 'done' as const }- const older = store.createMeeting({ ...base, title: 'Budget review', startedAt: Date.parse('2026-11-01T17:00:00Z'), endedAt: Date.parse('2026-11-01T17:25:00Z'), attendees: [{ name: 'Ann Lee', email: '[email protected]' }] })- const newer = store.createMeeting({ ...base, title: 'Launch plan', startedAt: Date.parse('2026-11-02T16:00:00Z'), attendees: [] })- store.addSegments([- { meetingId: older.id, track: 'me', startMs: 5_000, endMs: 7_000, text: 'Can we keep travel flat?', speaker: 'me' },- { meetingId: older.id, track: 'them', startMs: 65_000, endMs: 68_000, text: 'Travel spend is down a little.', speaker: 'Ann Lee' },- { meetingId: older.id, track: 'them', startMs: 70_000, endMs: 71_000, text: 'Sure.', speaker: null },- { meetingId: older.id, track: 'me', startMs: 72_000, endMs: 73_000, text: 'an echo', speaker: 'me', hidden: true },- ])- store.setNotes(older.id, { mine: 'travel flat', enhanced: '## Budget\n- Travel stays flat.' })- const audioDir = join(dir, 'meetings', older.id); mkdirSync(audioDir, { recursive: true })- writeFileSync(join(audioDir, 'me.m4a'), 'x'); writeFileSync(join(audioDir, 'them.m4a'), 'x')- let on = o.enabled ?? true- const clients: string[] = []- const mcp = createMcp({- store, enabled: () => on, me: () => 'Sam Rivera', version: '0.1.0', platform: o.platform,- audio: async (id) => id === older.id ? [{ track: 'me', path: join(audioDir, 'me.m4a') }, { track: 'them', path: join(audioDir, 'them.m4a') }] : [],- })- return { store, mcp, older, newer, dir, clients, turn: (v: boolean) => { on = v } }-}--const call = async (mcp: Mcp, name: string, args: Record<string, unknown> = {}) => {- const r = await mcp.handle({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name, arguments: args } }) as { result: { content: Array<{ text: string }>; isError?: boolean } }- return { text: r.result.content.map((c) => c.text).join('\n'), isError: !!r.result.isError }-}-const json = async (mcp: Mcp, name: string, args: Record<string, unknown> = {}) => JSON.parse((await call(mcp, name, args)).text)-describe('the MCP server', () => {it('says who it is and that it has tools, in the protocol version the app asked for when it knows it', async () => {const { mcp } = setup()@@ -55,12 +16,20 @@ describe('the MCP server', () => {const odd = await mcp.handle({ jsonrpc: '2.0', id: 2, method: 'initialize', params: { protocolVersion: '1999-01-01' } }) as { result: { protocolVersion: string } }expect(odd.result.protocolVersion).toBe('2025-06-18')})- it('lists its tools, all of them only reading', async () => {+ it('lists its tools: the reading ones read only, the rest marked as changes, and removing or replacing ones as destructive', async () => {const { mcp } = setup()- const r = await mcp.handle({ jsonrpc: '2.0', id: 3, method: 'tools/list' }) as { result: { tools: Array<{ name: string; annotations: { readOnlyHint: boolean } }> } }- expect(r.result.tools.map((t) => t.name)).toEqual(['list_folders', 'list_meetings', 'get_meeting', 'get_transcript', 'search', 'get_audio'])- expect(r.result.tools.every((t) => t.annotations.readOnlyHint)).toBe(true)- expect(MCP_TOOLS).toHaveLength(6)+ const r = await mcp.handle({ jsonrpc: '2.0', id: 3, method: 'tools/list' }) as { result: { tools: Array<{ name: string; annotations: { readOnlyHint: boolean; destructiveHint: boolean } }> } }+ const tools = r.result.tools+ const reading = ['list_folders', 'list_meetings', 'get_meeting', 'get_transcript', 'search', 'ask', 'list_people', 'upcoming_meetings', 'calendar_day', 'list_trash', 'get_settings', 'export_meeting', 'get_audio']+ expect(tools.filter((t) => t.annotations.readOnlyHint).map((t) => t.name)).toEqual(reading)+ expect(tools.filter((t) => !t.annotations.readOnlyHint).map((t) => t.name)).toEqual(['create_folder', 'rename_folder', 'delete_folder', 'add_to_folder', 'remove_from_folder',+ 'accept_folder_suggestion', 'dismiss_folder_suggestion', 'rename_meeting', 'set_attendees', 'link_calendar_event', 'unlink_calendar_event', 'trash_meeting', 'restore_meeting',+ 'set_my_notes', 'set_summary', 'rewrite_summary', 'start_recording', 'pause_recording', 'resume_recording', 'stop_recording', 'set_custom_words', 'set_spoken_language',+ 'set_summary_language', 'create_meeting', 'import_meetings'])+ expect(tools.filter((t) => t.annotations.destructiveHint).map((t) => t.name)).toEqual(['delete_folder', 'set_attendees', 'trash_meeting', 'set_my_notes', 'set_summary', 'rewrite_summary', 'stop_recording', 'set_custom_words'])+ // never anything that deletes for good+ expect(tools.map((t) => t.name).filter((n) => /empty|purge|delete_meeting|delete_audio|forever/.test(n))).toEqual([])+ expect(MCP_TOOLS).toEqual(tools)})it("tells other apps' models about the Mac on a Mac, and about Ogg files on Windows and Linux", async () => {const audioText = async (platform?: string) => {@@ -70,7 +39,7 @@ describe('the MCP server', () => {return [init.result.instructions, list.result.tools.find((t) => t.name === 'get_audio')!.description]}const mac = "A meeting's recording as files on this Mac: one per side (track me: the person's microphone; them: the other side of the call), AAC in .m4a. Gives paths, which apps on this Mac can open."- expect(await audioText()).toEqual(["Yogurt holds the person's meeting notes, transcripts and recordings on this Mac. Use list_meetings or search to find a meeting, then get_meeting, get_transcript or get_audio.", mac])+ expect(await audioText()).toEqual([expect.stringMatching(/^Yogurt holds the person's meeting notes, transcripts and recordings on this Mac\. Use list_meetings or search to find a meeting, then get_meeting, get_transcript or get_audio\./), mac])expect(await audioText('darwin')).toEqual(await audioText())for (const p of ['win32', 'linux']) {const [instructions, audio] = await audioText(p)diff --git a/app/test/mcpChanges.test.ts b/app/test/mcpChanges.test.tsnew file mode 100644index 00000000..5a711dff--- /dev/null+++ b/app/test/mcpChanges.test.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from 'vitest'+import { MCP_TOOLS } from '../src/main/mcp/server'+import { setup, call, json, EVENT } from './mcpRig'++const reading = new Set(MCP_TOOLS.filter((t) => (t.annotations as { readOnlyHint: boolean }).readOnlyHint).map((t) => t.name))+const changing = MCP_TOOLS.map((t) => t.name).filter((n) => !reading.has(n))++describe('changes from AI apps, while the person has not allowed them', () => {+ it.each(changing)('%s changes nothing and says where to allow changes', async (name) => {+ const { mcp, store, older, calls, logs } = setup({ changes: false })+ const before = JSON.stringify([store.meetings({ limit: 10 }), store.folders(), store.notes(older.id)])+ const r = await call(mcp, name, { id: older.id, folder: 'x', name: 'x', title: 'x', markdown: 'x', started_at: '2026-11-01T00:00:00Z', summary: 'x', meetings: [] })+ expect(r).toEqual({ isError: true, text: expect.stringContaining('"Let AI apps make changes"') })+ expect(JSON.stringify([store.meetings({ limit: 10 }), store.folders(), store.notes(older.id)])).toBe(before)+ expect(calls).toEqual([])+ expect(logs).toEqual([`${name} refused: changes off ${older.id}`])+ })+ it('reading still works', async () => {+ const { mcp } = setup({ changes: false })+ expect((await json(mcp, 'list_meetings')).length).toBe(2)+ })+ it('with AI apps off altogether, the off message comes first', async () => {+ const { mcp } = setup({ enabled: false, changes: true })+ expect((await call(mcp, 'create_folder', { name: 'Sales' })).text).toContain('connecting AI apps turned off')+ })+})++describe('folders, with changes allowed', () => {+ it('makes, renames and deletes a folder (its meetings stay), and tells the windows', async () => {+ const { mcp, store, older, calls, logs } = setup({ changes: true })+ const f = await json(mcp, 'create_folder', { name: ' Sales ' })+ expect(f).toEqual({ id: expect.any(String), name: 'Sales' })+ expect(await call(mcp, 'create_folder', { name: 'sales' })).toMatchObject({ isError: true, text: expect.stringContaining('already a folder') })+ expect(await json(mcp, 'rename_folder', { folder: 'Sales', name: 'Deals' })).toEqual({ id: f.id, name: 'Deals' })+ expect((await json(mcp, 'add_to_folder', { folder: f.id, id: older.id })).folders).toEqual([{ id: f.id, name: 'Deals' }])+ expect((await json(mcp, 'remove_from_folder', { folder: 'deals', id: older.id })).folders).toEqual([])+ expect((await call(mcp, 'delete_folder', { folder: 'Deals' })).text).toContain('stay')+ expect(store.folders()).toEqual([])+ expect(store.meeting(older.id)).toBeDefined()+ expect(calls.filter((c) => c[0] === 'changed')).toHaveLength(5)+ // ids only in the log, never the names+ expect(logs).toContain(`create_folder made ${f.id}`)+ expect(logs.join('\n')).not.toMatch(/Sales|Deals/)+ })+ it('refuses a bad folder or name in plain words, listing the folders there are', async () => {+ const { mcp, store, older } = setup({ changes: true })+ store.createFolder('Finance')+ expect(await call(mcp, 'add_to_folder', { folder: 'Sales', id: older.id })).toMatchObject({ isError: true, text: expect.stringContaining('Finance') })+ expect(await call(mcp, 'create_folder', { name: 'x'.repeat(201) })).toMatchObject({ isError: true, text: expect.stringContaining('at most 200') })+ expect(await call(mcp, 'create_folder', { name: 42 })).toMatchObject({ isError: true, text: 'name must be text.' })+ expect(await call(mcp, 'create_folder', { name: ' ' })).toMatchObject({ isError: true, text: "name can't be blank." })+ })+ it("accepts or dismisses Yogurt's folder suggestion", async () => {+ const { mcp, store, older, newer } = setup({ changes: true })+ const f = store.createFolder('Finance')+ expect(await call(mcp, 'accept_folder_suggestion', { id: older.id })).toMatchObject({ isError: true, text: expect.stringContaining('no folder suggestion') })+ store.saveFolderSuggestion(older.id, { folderId: f.id, confidence: 0.9 }, 'v')+ expect((await json(mcp, 'accept_folder_suggestion', { id: older.id })).folders).toEqual([{ id: f.id, name: 'Finance' }])+ expect(store.folderSuggestion(older.id).state).toBe('accepted')+ store.saveFolderSuggestion(newer.id, { folderId: f.id, confidence: 0.9 }, 'v')+ await call(mcp, 'dismiss_folder_suggestion', { id: newer.id })+ expect(store.folderSuggestion(newer.id).state).toBe('dismissed')+ })+})++describe('meetings, with changes allowed', () => {+ it("renames, sets who was there and links a calendar event through the app's own functions", async () => {+ const { mcp, older, calls } = setup({ changes: true })+ expect((await json(mcp, 'rename_meeting', { id: older.id, title: 'Q4 budget' })).title).toBe('Q4 budget')+ expect(await call(mcp, 'rename_meeting', { id: older.id, title: 'x'.repeat(201) })).toMatchObject({ isError: true })+ expect((await json(mcp, 'set_attendees', { id: older.id, attendees: [{ name: 'Bo Park' }, { name: 'Ann Lee', email: '[email protected]' }] })).attendees)+ .toEqual([{ name: 'Bo Park', email: null }, { name: 'Ann Lee', email: '[email protected]' }])+ expect(await call(mcp, 'set_attendees', { id: older.id, attendees: [{ email: '[email protected]' }] })).toMatchObject({ isError: true, text: 'name is needed.' })+ expect(await call(mcp, 'set_attendees', { id: older.id, attendees: Array.from({ length: 101 }, () => ({ name: 'A' })) })).toMatchObject({ isError: true, text: expect.stringContaining('at most 100') })+ await json(mcp, 'link_calendar_event', { id: older.id, event_id: EVENT.id, date: '2026-11-21' })+ expect(calls).toContainEqual(['linkEvent', older.id, EVENT.id, expect.any(Number)])+ expect(await call(mcp, 'link_calendar_event', { id: older.id, event_id: 'gone' })).toMatchObject({ isError: true, text: expect.stringContaining('not on the calendar') })+ await json(mcp, 'unlink_calendar_event', { id: older.id })+ expect(calls).toContainEqual(['unlinkEvent', older.id])+ })+ it('moves a meeting to the Trash and back, never while it records', async () => {+ const { mcp, store, older } = setup({ changes: true })+ expect((await call(mcp, 'trash_meeting', { id: older.id })).text).toContain('restore_meeting')+ expect(store.meeting(older.id)?.trashedAt).toBeDefined()+ expect(await call(mcp, 'get_meeting', { id: older.id })).toMatchObject({ isError: true })+ expect(await call(mcp, 'restore_meeting', { id: 'nope' })).toMatchObject({ isError: true, text: expect.stringContaining('list_trash') })+ expect((await json(mcp, 'restore_meeting', { id: older.id })).id).toBe(older.id)+ expect(store.meeting(older.id)?.trashedAt).toBeUndefined()+ const busy = setup({ changes: true, app: { trash: () => 'recording' } })+ expect(await call(busy.mcp, 'trash_meeting', { id: busy.older.id })).toMatchObject({ isError: true, text: expect.stringContaining('stop_recording') })+ })+})++describe('notes, with changes allowed', () => {+ it("replaces or adds to the person's notes, and replaces the summary", async () => {+ const { mcp, older } = setup({ changes: true })+ expect((await json(mcp, 'set_my_notes', { id: older.id, markdown: '- call Ann back', mode: 'append' })).myNotes).toBe('travel flat\n\n- call Ann back')+ expect((await json(mcp, 'set_my_notes', { id: older.id, markdown: 'fresh' })).myNotes).toBe('fresh')+ expect((await json(mcp, 'set_summary', { id: older.id, markdown: '## New\n- Done.' })).summary).toBe('## New\n- Done.')+ expect(await call(mcp, 'set_my_notes', { id: older.id, markdown: 'x', mode: 'merge' })).toMatchObject({ isError: true, text: expect.stringContaining('"replace", "append"') })+ })+ it('says so while the summary is being written', async () => {+ const { mcp, older } = setup({ changes: true, app: { setSummary: () => 'busy' } })+ expect(await call(mcp, 'set_summary', { id: older.id, markdown: 'x' })).toMatchObject({ isError: true, text: expect.stringContaining('writing') })+ })+ it('has the summary written again, with an instruction', async () => {+ const { mcp, older, calls } = setup({ changes: true })+ expect((await call(mcp, 'rewrite_summary', { id: older.id, instruction: 'shorter' })).text).toContain('writing the summary again')+ expect(calls).toContainEqual(['rewriteSummary', older.id, 'shorter'])+ expect(await call(mcp, 'rewrite_summary', { id: older.id, instruction: 'x'.repeat(241) })).toMatchObject({ isError: true })+ })+})++describe('recording, with changes allowed', () => {+ it('starts, pauses, resumes and stops a recording through the same functions as the app', async () => {+ const { mcp, calls } = setup({ changes: true })+ for (const t of ['pause_recording', 'resume_recording', 'stop_recording']) expect(await call(mcp, t)).toMatchObject({ isError: true, text: 'Yogurt is not recording.' })+ const m = await json(mcp, 'start_recording', { title: 'Standup' })+ expect(m).toMatchObject({ title: 'Standup', recording: true })+ expect(await call(mcp, 'start_recording')).toMatchObject({ isError: true, text: expect.stringContaining('already recording') })+ await call(mcp, 'pause_recording')+ await call(mcp, 'resume_recording', { id: m.id })+ expect(await call(mcp, 'stop_recording', { id: 'other' })).toMatchObject({ isError: true, text: expect.stringContaining('not the one recording') })+ expect((await call(mcp, 'stop_recording')).text).toContain('Stopped recording')+ expect(calls.filter((c) => /Recording$/.test(c[0]))).toEqual([['startRecording', { title: 'Standup' }], ['pauseRecording', m.id, true], ['pauseRecording', m.id, false], ['stopRecording', m.id]])+ })+ it('takes notes for a calendar event, and says when the event is gone', async () => {+ const { mcp, calls } = setup({ changes: true })+ await json(mcp, 'start_recording', { event_id: EVENT.id })+ expect(calls).toContainEqual(['startRecording', { eventId: EVENT.id }])+ const gone = setup({ changes: true, app: { startRecording: async () => ({ error: 'gone' }) } })+ expect(await call(gone.mcp, 'start_recording', { event_id: 'x' })).toMatchObject({ isError: true, text: expect.stringContaining('not coming up') })+ })+})++describe('settings, with changes allowed', () => {+ it('sets custom words, the spoken language and the summary language, and nothing else', async () => {+ const { mcp, calls } = setup({ changes: true })+ expect(await json(mcp, 'set_custom_words', { words: ['Acme', 'Kubernetes'] })).toEqual({ custom_words: ['Acme', 'Kubernetes'] })+ expect(await call(mcp, 'set_custom_words', { words: [1] })).toMatchObject({ isError: true })+ await call(mcp, 'set_spoken_language', { language: 'multi' })+ expect(await call(mcp, 'set_spoken_language', { language: 'fr' })).toMatchObject({ isError: true })+ await call(mcp, 'set_summary_language', { language: 'de' })+ await call(mcp, 'set_summary_language', { language: '' })+ expect(await call(mcp, 'set_summary_language', { language: 'klingon' })).toMatchObject({ isError: true, text: expect.stringContaining('de (German)') })+ expect(calls).toEqual([['setJargon', ['Acme', 'Kubernetes']], ['setSpoken', 'multi'], ['setSummaryLanguage', 'de'], ['setSummaryLanguage', '']])+ expect(MCP_TOOLS.map((t) => t.name).filter((n) => /privacy|permission|ai_apps|mcp|keep_recordings|delete_audio/.test(n))).toEqual([])+ })+})diff --git a/app/test/mcpImport.test.ts b/app/test/mcpImport.test.tsnew file mode 100644index 00000000..8335826a--- /dev/null+++ b/app/test/mcpImport.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest'+import { setup, call, json } from './mcpRig'++const granola = {+ title: 'Vendor call', started_at: '2026-10-20T14:00:00Z', attendees: [{ name: 'Ann Lee', email: '[email protected]' }, { name: 'Raj Patel' }],+ transcript: '[00:05] Sam Rivera: Shall we start?\n[00:09] Raj Patel: The rollout slips to March.\n[00:20] Okay.',+ summary: '## Rollout\n- Moves to March.', my_notes: 'ask about March',+}++describe('bringing meetings in from other notes apps', () => {+ it('creates a finished meeting with its transcript, notes and summary, shown and searchable like one recorded here', async () => {+ const { mcp, store, calls } = setup({ changes: true })+ const got = await json(mcp, 'create_meeting', granola)+ expect(got).toMatchObject({ title: 'Vendor call', start: '2026-10-20T14:00:00.000Z', lines: 3, folder: null, summary: 'given' })+ const m = store.meeting(got.id)!+ expect(m).toMatchObject({ source: 'import', app: null, state: 'done', titleSource: 'user', startedAt: Date.parse('2026-10-20T14:00:00Z'), attendees: [{ name: 'Ann Lee', email: '[email protected]' }, { name: 'Raj Patel', email: null }] })+ // ends where the transcript does+ expect(m.endedAt).toBe(m.startedAt + store.segments(m.id).at(-1)!.endMs)+ expect(store.segments(m.id).map((s) => [s.track, s.speaker, s.startMs, s.text])).toEqual([+ ['me', 'me', 5_000, 'Shall we start?'], ['them', 'Raj Patel', 9_000, 'The rollout slips to March.'], ['them', null, 20_000, 'Okay.']])+ expect(store.notes(m.id)).toEqual({ mine: 'ask about March', enhanced: '## Rollout\n- Moves to March.', edited: true })+ expect(store.search('rollout', 10).map((h) => h.meetingId)).toContain(m.id)+ expect(calls).toContainEqual(['imported', m.id])+ expect((await json(mcp, 'get_meeting', { id: m.id })).imported).toBe(true)+ expect((await call(mcp, 'get_transcript', { id: m.id })).text).toBe('[00:05] Sam Rivera: Shall we start?\n[00:09] Raj Patel: The rollout slips to March.\n[00:20] Them: Okay.')+ })+ it('reads the other text shapes, and lines given as JSON', async () => {+ const { mcp, store } = setup({ changes: true })+ const named = await json(mcp, 'create_meeting', { title: 'A', started_at: '2026-10-21T10:00:00Z', transcript: 'Ann Lee (00:00:04): Hi.\nBo Park (00:01:02): Hello.' })+ expect(store.segments(named.id).map((s) => [s.speaker, s.startMs])).toEqual([['Ann Lee', 4_000], ['Bo Park', 62_000]])+ const plain = await json(mcp, 'create_meeting', { title: 'B', started_at: '2026-10-21T11:00:00Z', transcript: 'Ann Lee: Hi.\nMe: Hello back.' })+ expect(store.segments(plain.id).map((s) => [s.track, s.speaker, s.startMs])).toEqual([['them', 'Ann Lee', 0], ['me', 'me', 1_000]])+ const lines = await json(mcp, 'create_meeting', { title: 'C', started_at: '2026-10-21T12:00:00Z', ended_at: '2026-10-21T12:30:00Z',+ transcript_lines: [{ start_ms: 1000, end_ms: 2500, speaker: 'Ann Lee', text: 'One.' }, { text: 'Two.' }] })+ expect(store.segments(lines.id).map((s) => [s.speaker, s.startMs, s.endMs])).toEqual([['Ann Lee', 1000, 2500], [null, 2500, 3500]])+ expect(store.meeting(lines.id)!.endedAt).toBe(Date.parse('2026-10-21T12:30:00Z'))+ })+ it('files it in a folder by name, making the folder when asked', async () => {+ const { mcp, store } = setup({ changes: true })+ expect(await call(mcp, 'create_meeting', { ...granola, folder: 'Vendors' })).toMatchObject({ isError: true, text: expect.stringContaining('No folder') })+ const got = await json(mcp, 'create_meeting', { ...granola, folder: 'Vendors', create_folder: true })+ expect(got.folder).toEqual({ id: expect.any(String), name: 'Vendors' })+ expect(store.foldersOf(got.id).map((f) => f.name)).toEqual(['Vendors'])+ const again = await json(mcp, 'create_meeting', { ...granola, folder: 'vendors', create_folder: true })+ expect(again.folder.id).toBe(got.folder.id)+ expect(store.folders()).toHaveLength(1)+ })+ it('has Yogurt write the summary instead, when asked', async () => {+ const { mcp, store, calls } = setup({ changes: true })+ const { summary: _, ...rest } = granola+ const got = await json(mcp, 'create_meeting', { ...rest, write_summary: true })+ expect(got.summary).toBe('Yogurt is writing it')+ expect(store.notes(got.id).enhanced).toBeNull()+ expect(calls).toContainEqual(['rewriteSummary', got.id, ''])+ expect(await call(mcp, 'create_meeting', { ...granola, write_summary: true })).toMatchObject({ isError: true, text: expect.stringContaining('not both') })+ })+ it('brings the same meeting in once, by its id in the other app', async () => {+ const { mcp, store } = setup({ changes: true })+ const first = await json(mcp, 'create_meeting', { ...granola, source_id: 'gr-1' })+ expect(await json(mcp, 'create_meeting', { ...granola, source_id: 'gr-1' })).toEqual({ id: first.id, title: 'Vendor call', already_imported: true })+ expect(store.meetings({ limit: 10 })).toHaveLength(3)+ })+ it('checks everything strictly before saving anything', async () => {+ const { mcp, store } = setup({ changes: true })+ const bad: Array<[Record<string, unknown>, string]> = [+ [{ ...granola, title: undefined }, 'title is needed.'],+ [{ ...granola, title: 'x'.repeat(201) }, 'at most 200'],+ [{ ...granola, started_at: 'yesterday' }, 'ISO time'],+ [{ ...granola, ended_at: '2026-10-19T00:00:00Z' }, 'before started_at'],+ [{ ...granola, transcript: undefined, summary: undefined, my_notes: undefined }, 'nothing in it'],+ [{ ...granola, transcript_lines: [{ text: 'x' }] }, 'not both'],+ [{ ...granola, transcript: undefined, transcript_lines: [{ start_ms: -1, text: 'x' }] }, 'start_ms'],+ [{ ...granola, transcript: undefined, transcript_lines: Array.from({ length: 20_001 }, () => ({ text: 'x' })) }, 'at most 20000'],+ [{ ...granola, attendees: 'Ann' }, 'must be a list'],+ ]+ for (const [args, says] of bad) expect(await call(mcp, 'create_meeting', args)).toMatchObject({ isError: true, text: expect.stringContaining(says) })+ expect(store.meetings({ limit: 10 })).toHaveLength(2)+ })+ it('brings in several at once, saying which could not come in and why', async () => {+ const { mcp, store } = setup({ changes: true })+ const got = await json(mcp, 'import_meetings', { meetings: [granola, { title: 'No start' }, { ...granola, title: 'Second' }] })+ expect(got).toEqual([expect.objectContaining({ index: 0, id: expect.any(String) }), { index: 1, error: 'started_at is needed.' }, expect.objectContaining({ index: 2, title: 'Second' })])+ expect(store.meetings({ limit: 10 })).toHaveLength(4)+ expect(await call(mcp, 'import_meetings', { meetings: Array.from({ length: 51 }, () => granola) })).toMatchObject({ isError: true, text: expect.stringContaining('at most 50') })+ })+ it('logs ids and counts, never titles, names or words', async () => {+ const { mcp, logs } = setup({ changes: true })+ const got = await json(mcp, 'create_meeting', { ...granola, folder: 'Vendors', create_folder: true })+ expect(logs.some((l) => l.startsWith(`create_meeting made ${got.id}: 3 lines, a summary, in `))).toBe(true)+ expect(logs.join('\n')).not.toMatch(/Vendor|Raj|Ann|March|rollout/i)+ })+})diff --git a/app/test/mcpRead.test.ts b/app/test/mcpRead.test.tsnew file mode 100644index 00000000..c01ad885--- /dev/null+++ b/app/test/mcpRead.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import { setup, call, json, EVENT } from './mcpRig'++describe('reading more through MCP', () => {+ it("ask gives Yogurt's own answer with its sources, read from the folder or meetings named", async () => {+ const { mcp, store, older, calls } = setup()+ const f = store.createFolder('Finance')+ const got = await json(mcp, 'ask', { question: 'What happened to travel?', folder: 'finance', meeting_ids: [older.id] })+ expect(got).toEqual({ answer: 'Travel stays flat [1].', sources: [{ n: 1, meeting_id: older.id, title: 'Budget review', start: '2026-11-01T17:00:00.000Z', at: '01:05', excerpt: 'Travel spend is down a little.' }] })+ expect(calls).toContainEqual(['ask', 'What happened to travel?', [{ kind: 'folder', id: f.id }, { kind: 'meeting', id: older.id }]])+ })+ it('ask says plainly when the notes model is not there yet, or a recording needs the room', async () => {+ for (const unavailable of ['model', 'recording'] as const) {+ const { mcp } = setup({ app: { ask: async () => ({ unavailable }) } })+ const r = await call(mcp, 'ask', { question: 'Anything?' })+ expect(r).toMatchObject({ isError: true, text: expect.stringContaining(unavailable === 'model' ? 'still downloading' : 'recording') })+ }+ })+ it('ask needs a question, and meetings that are there', async () => {+ const { mcp } = setup()+ expect(await call(mcp, 'ask', {})).toMatchObject({ isError: true, text: 'question is needed.' })+ expect(await call(mcp, 'ask', { question: 'x', meeting_ids: ['nope'] })).toMatchObject({ isError: true, text: expect.stringContaining('No meeting') })+ expect(await call(mcp, 'ask', { question: 'x'.repeat(4001) })).toMatchObject({ isError: true, text: expect.stringContaining('too long') })+ })+ it('gives what is coming up and one day of the calendar, with call links and the note there is for an event', async () => {+ const { mcp, store, calls } = setup()+ const note = store.createMeeting({ title: 'Pricing sync', startedAt: EVENT.start, endedAt: null, eventId: EVENT.id, app: null, attendees: [], state: 'prepared' })+ const want = [{ event_id: 'evt-9', title: 'Pricing sync', start: '2026-11-21T15:00:00.000Z', end: '2026-11-21T15:30:00.000Z', calendar: 'Work', meeting_link: 'https://meet.example.com/abc',+ attendees: [{ name: 'Dana Smith', email: '[email protected]' }], meeting_id: note.id }]+ expect(await json(mcp, 'upcoming_meetings')).toEqual(want)+ expect(await json(mcp, 'calendar_day', { date: '2026-11-21' })).toEqual(want)+ const asked = calls.find((c) => c[0] === 'calendarDay')![1] as number+ expect([new Date(asked).getFullYear(), new Date(asked).getMonth(), new Date(asked).getDate()]).toEqual([2026, 10, 21])+ expect(await call(mcp, 'calendar_day', { date: 'next week' })).toMatchObject({ isError: true, text: expect.stringContaining('must be a date') })+ })+ it('says where to connect a calendar when it has none', async () => {+ const { mcp } = setup({ app: { comingUp: async () => ({ status: 'denied', events: [] }) } })+ expect(await call(mcp, 'upcoming_meetings')).toMatchObject({ isError: false, text: expect.stringContaining('Settings, Calendars') })+ })+ it('lists the people in meetings, and narrows list_meetings and search to one of them by name or email', async () => {+ const { mcp, older } = setup()+ expect(await json(mcp, 'list_people')).toEqual([{ name: 'Ann Lee', email: '[email protected]' }])+ expect((await json(mcp, 'list_meetings', { person: '[email protected]' })).map((m: { id: string }) => m.id)).toEqual([older.id])+ expect((await json(mcp, 'list_meetings', { person: 'ann lee' })).map((m: { id: string }) => m.id)).toEqual([older.id])+ expect((await json(mcp, 'search', { query: 'travel', person: 'Ann Lee' })).map((h: { meeting_id: string }) => h.meeting_id)).toEqual([older.id])+ const r = await call(mcp, 'list_meetings', { person: 'Ann Smith' })+ expect(r).toMatchObject({ isError: true, text: expect.stringContaining('Ann Lee <[email protected]>') })+ })+ it('lists the Trash, which other reading tools never show', async () => {+ const { mcp, store, older } = setup()+ store.trashMeeting(older.id, Date.parse('2026-11-10T09:00:00Z'))+ expect(await json(mcp, 'list_trash')).toEqual([{ id: older.id, title: 'Budget review', start: '2026-11-01T17:00:00.000Z', trashed_at: '2026-11-10T09:00:00.000Z' }])+ })+ it('gives the settings that shape notes', async () => {+ const { mcp } = setup()+ expect(await json(mcp, 'get_settings')).toEqual({ my_name: 'Sam Rivera', interface_language: 'en', spoken_language: 'en (English only)', summary_language: "each meeting's own language",+ custom_words: ['Acme'], stop_recording_when_call_ends: true, keep_audio_recordings: false })+ })+ it("exports a meeting as the same Markdown Export Markdown saves, with either side's notes", async () => {+ const { mcp, older } = setup()+ const md = (await call(mcp, 'export_meeting', { id: older.id })).text+ expect(md).toMatch(/^# Budget review\n/)+ expect(md).toContain('With: Ann Lee')+ expect(md).toContain('- Travel stays flat.')+ expect(md).toContain('Travel spend is down a little.')+ expect((await call(mcp, 'export_meeting', { id: older.id, side: 'my_notes' })).text).toContain('travel flat')+ expect(await call(mcp, 'export_meeting', { id: older.id, side: 'both' })).toMatchObject({ isError: true })+ })+ it('says which folder Yogurt suggests for a meeting not filed yet', async () => {+ const { mcp, store, older } = setup()+ const f = store.createFolder('Finance')+ store.saveFolderSuggestion(older.id, { folderId: f.id, confidence: 0.9 }, 'v')+ expect((await json(mcp, 'get_meeting', { id: older.id })).suggested_folder).toEqual({ id: f.id, name: 'Finance' })+ store.addToFolder(f.id, older.id)+ expect((await json(mcp, 'get_meeting', { id: older.id })).suggested_folder).toBeNull()+ })+})diff --git a/app/test/mcpRig.ts b/app/test/mcpRig.tsnew file mode 100644index 00000000..0cfb6b37--- /dev/null+++ b/app/test/mcpRig.ts@@ -0,0 +1,86 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach } from 'vitest'+import { openStore, type Store } from '../src/main/store'+import { createMcp, type Mcp, type McpApp } from '../src/main/mcp/server'+import type { CalEvent } from '../src/main/calendar'++/** A made-up Yogurt for the MCP tests: a real store with two meetings, and the app's actions recorded as calls. */+const dirs: string[] = []+const stores: Store[] = []+afterEach(() => {+ stores.splice(0).forEach((s) => s.close())+ dirs.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }))+})+const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'yogurt-mcp-')); dirs.push(d); return d }++export const EVENT: CalEvent = { id: 'evt-9', title: 'Pricing sync', start: Date.parse('2026-11-21T15:00:00Z'), end: Date.parse('2026-11-21T15:30:00Z'),+ attendees: [{ name: 'Dana Smith', email: '[email protected]' }], url: 'https://meet.example.com/abc', calendar: { id: 'c1', name: 'Work', source: 'iCloud' } }++export function setup(o: { enabled?: boolean; changes?: boolean; platform?: string; app?: Partial<McpApp> } = {}) {+ const dir = tmp()+ const store = openStore(join(dir, 'yogurt.db')); stores.push(store)+ const base = { endedAt: null, eventId: null, app: 'Zoom', state: 'done' as const }+ const older = store.createMeeting({ ...base, title: 'Budget review', startedAt: Date.parse('2026-11-01T17:00:00Z'), endedAt: Date.parse('2026-11-01T17:25:00Z'), attendees: [{ name: 'Ann Lee', email: '[email protected]' }] })+ const newer = store.createMeeting({ ...base, title: 'Launch plan', startedAt: Date.parse('2026-11-02T16:00:00Z'), attendees: [] })+ store.addSegments([+ { meetingId: older.id, track: 'me', startMs: 5_000, endMs: 7_000, text: 'Can we keep travel flat?', speaker: 'me' },+ { meetingId: older.id, track: 'them', startMs: 65_000, endMs: 68_000, text: 'Travel spend is down a little.', speaker: 'Ann Lee' },+ { meetingId: older.id, track: 'them', startMs: 70_000, endMs: 71_000, text: 'Sure.', speaker: null },+ { meetingId: older.id, track: 'me', startMs: 72_000, endMs: 73_000, text: 'an echo', speaker: 'me', hidden: true },+ ])+ store.setNotes(older.id, { mine: 'travel flat', enhanced: '## Budget\n- Travel stays flat.' })+ const audioDir = join(dir, 'meetings', older.id); mkdirSync(audioDir, { recursive: true })+ writeFileSync(join(audioDir, 'me.m4a'), 'x'); writeFileSync(join(audioDir, 'them.m4a'), 'x')+ let on = o.enabled ?? true+ let changes = o.changes ?? false+ const calls: Array<[string, ...unknown[]]> = []+ const logs: string[] = []+ let recording: ReturnType<Store['meeting']> | null = null+ const rec = <A extends unknown[], R>(name: string, fn: (...a: A) => R) => (...a: A): R => { calls.push([name, ...a]); return fn(...a) }+ const app: McpApp = {+ ask: rec('ask', async () => ({ answer: 'Travel stays flat [1].', sources: [{ n: 1, meetingId: older.id, title: 'Budget review', startedAt: older.startedAt, atMs: 65_000, excerpt: 'Travel spend is down a little.' }] })),+ comingUp: rec('comingUp', async () => ({ status: 'granted' as const, events: [EVENT] })),+ calendarDay: rec('calendarDay', async () => ({ status: 'granted' as const, events: [EVENT] })),+ settings: () => ({ myName: 'Sam Rivera', locale: 'en', spoken: 'en', summaryLanguage: '', jargon: ['Acme'], stopWhenCallEnds: true, keepRecordings: false }),+ changed: rec('changed', () => {}),+ imported: rec('imported', () => {}),+ rename: rec('rename', (id: string, title: string) => { store.updateMeeting(id, { title, titleSource: 'user' }); return true }),+ setAttendees: rec('setAttendees', (id: string, people) => { store.updateMeeting(id, { attendees: people, keepAttendees: true }); return true }),+ linkEvent: rec('linkEvent', async (id: string, eventId: string) => { if (eventId !== EVENT.id) return false; store.updateMeeting(id, { eventId }); return true }),+ unlinkEvent: rec('unlinkEvent', (id: string) => { store.updateMeeting(id, { eventId: null }); return true }),+ trash: rec('trash', (id: string) => { store.trashMeeting(id); return 'trashed' as const }),+ restore: rec('restore', (id: string) => { store.restoreMeeting(id); return true }),+ setMyNotes: rec('setMyNotes', (id: string, md: string) => { store.setNotes(id, { mine: md }); return 'saved' as const }),+ setSummary: rec('setSummary', (id: string, md: string) => { store.setNotes(id, { enhanced: md, edited: true }); return 'saved' as const }),+ rewriteSummary: rec('rewriteSummary', () => 'queued' as const),+ notesReady: () => true,+ startRecording: rec('startRecording', async (s: { title?: string }) => {+ recording = store.createMeeting({ ...base, state: 'recording', title: s.title ?? 'Meeting', startedAt: Date.now(), attendees: [] })+ return { id: recording.id }+ }),+ pauseRecording: rec('pauseRecording', () => true),+ stopRecording: rec('stopRecording', () => { recording = null; return true }),+ recording: () => recording ?? null,+ setJargon: rec('setJargon', (terms: string[]) => terms),+ setSpoken: rec('setSpoken', () => true),+ setSummaryLanguage: rec('setSummaryLanguage', () => true),+ ...o.app,+ }+ const mcp = createMcp({+ store, enabled: () => on, changesEnabled: () => changes, me: () => 'Sam Rivera', version: '0.1.0', platform: o.platform, app, log: (l) => logs.push(l),+ audio: async (id) => id === older.id ? [{ track: 'me', path: join(audioDir, 'me.m4a') }, { track: 'them', path: join(audioDir, 'them.m4a') }] : [],+ })+ return { store, mcp, older, newer, dir, calls, logs, turn: (v: boolean) => { on = v }, allowChanges: (v: boolean) => { changes = v } }+}++export const call = async (mcp: Mcp, name: string, args: Record<string, unknown> = {}) => {+ const r = await mcp.handle({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name, arguments: args } }) as { result: { content: Array<{ text: string }>; isError?: boolean } }+ return { text: r.result.content.map((c) => c.text).join('\n'), isError: !!r.result.isError }+}+export const json = async (mcp: Mcp, name: string, args: Record<string, unknown> = {}) => {+ const r = await call(mcp, name, args)+ if (r.isError) throw new Error(`${name} refused: ${r.text}`)+ return JSON.parse(r.text)+}