langmail-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,431 +0,0 @@
1
- // search_contacts tool — resolves a name, partial name, address, or
2
- // organization to known contacts from the collected address book (kept up
3
- // by the calendar tools, and by whatever else collects into it) plus any
4
- // personal address books, ranked by the read-time scoring in src/contacts.
5
- // Judgments
6
- // (relationship label, ranking, relative ages) are computed here, tool-side;
7
- // what the caller gets raw is the concrete recent-interaction list, hydrated
8
- // from the content-free record ids stored on the card.
9
- import { z } from "zod";
10
- import { discoverAccount, fetchEvents, } from "../caldav/client.js";
11
- import { addressCandidates, bestAddress, COLLECTED_BOOK_NAME, hasRole, isRolePhrase, normalizeRole, rankCards, readCollected, readOrganization, relationshipFor, relativeAge, SHOWN_INTERACTIONS, sourceOf, } from "../contacts/index.js";
12
- import { parseEvents } from "../ical/index.js";
13
- import { accountIdForContacts, addressBookList, authorizationHeader, contactCardGet, contactCardPage, emailGet, } from "../jmap/index.js";
14
- import { READ_ONLY } from "./annotations.js";
15
- import { birthdayLine, profileLines, rolesLine } from "./contact-format.js";
16
- import { errorResult, textResult } from "./result.js";
17
- const searchContactsShape = {
18
- context: z
19
- .enum(["work", "private", "any"])
20
- .default("any")
21
- .describe("Biases address ranking when a person has addresses in several contexts. " +
22
- "`work` prefers organization-domain addresses; `private` prefers " +
23
- "personal-domain addresses. Never filters a person out entirely."),
24
- limit: z
25
- .number()
26
- .int()
27
- .min(1)
28
- .max(25)
29
- .default(5)
30
- .describe("Maximum number of matching people."),
31
- query: z
32
- .string()
33
- .min(1)
34
- .max(200)
35
- .describe("Name, partial name, email address, organization, or what the person is to the user " +
36
- '("lawyer", "my landlord"). Matched against display names, organizations, addresses, ' +
37
- "address domains, and the roles stored on contacts."),
38
- response_format: z
39
- .enum(["concise", "detailed"])
40
- .default("concise")
41
- .describe("`concise` returns name, contact id, roles, best address, confidence, relationship, " +
42
- "the birthday when stored, and the last interactions. `detailed` adds all known addresses with their " +
43
- "own confidence, phone numbers, postal addresses, the note, where the record " +
44
- "came from, and interaction record ids (for chaining into get_email or " +
45
- "list_calendar_events), plus excluded relay addresses."),
46
- };
47
- export const searchContactsInput = z.object(searchContactsShape);
48
- // The search reads every card in the account and decides the match itself
49
- // (`matchesQuery`), rather than asking the server to filter. Stalwart's
50
- // query cannot reach a role (`text` does not search `titles`, and there is
51
- // no title condition),
52
- // its filtered ids come back unranked, so a window of them can drop the best
53
- // match, and its name, email and text conditions go through a search index
54
- // that misses a card for a moment after it is written. An unfiltered page
55
- // has none of these limits.
56
- //
57
- // Ids per page, and per full get below: Stalwart's default
58
- // `maxObjectsInGet` is 500.
59
- const PAGE = 500;
60
- // Upper bound on the cards one search reads. Past it the result says the
61
- // rest of the book was not searched.
62
- const CARD_CAP = 50_000;
63
- // Pages in flight at once. Stalwart advertises four concurrent requests per
64
- // account (`maxConcurrentRequests`; 1.1.0 refused only past eight), and an
65
- // agent may run two searches at once while another client writes to the
66
- // same account.
67
- const PARALLEL_PAGES = 2;
68
- // What `matchesQuery` reads. The rest of a card (the collected interaction
69
- // log above all) is read only for the matches.
70
- const MATCH_PROPERTIES = ["id", "name", "organizations", "emails", "titles"];
71
- // The ids of every card that matches the query, in the book's order, and
72
- // whether the sweep stopped at CARD_CAP with cards left unread. On a
73
- // 5,000-card book that is one page, then five rounds of two pages.
74
- const sweepBook = async (deps, ctx, query) => {
75
- const seen = new Set();
76
- const matched = [];
77
- const read = async (at, limit) => {
78
- const page = await deps.contactCardPage({
79
- ...ctx,
80
- apiUrl: "",
81
- limit,
82
- position: at,
83
- properties: MATCH_PROPERTIES,
84
- });
85
- for (const card of page.cards) {
86
- // A card read twice (a page re-read after a short one) counts once.
87
- if (!seen.has(card.id)) {
88
- seen.add(card.id);
89
- if (matchesQuery(card, query)) {
90
- matched.push(card.id);
91
- }
92
- }
93
- }
94
- return page;
95
- };
96
- const first = await read(0, PAGE);
97
- const { total } = first;
98
- // A server whose query limit is below PAGE returns shorter pages that are
99
- // not the end, so the first page's length is the page size from here on.
100
- const size = first.returned;
101
- const end = Math.min(total ?? Number.POSITIVE_INFINITY, CARD_CAP);
102
- let position = first.returned;
103
- let done = first.returned === 0 || (total !== undefined && position >= total);
104
- while (!done && position < end) {
105
- const starts = [];
106
- for (let at = position; at < end && starts.length < PARALLEL_PAGES; at += size) {
107
- starts.push(at);
108
- }
109
- const requests = starts.map((at) => ({
110
- at,
111
- limit: Math.min(size, CARD_CAP - at),
112
- }));
113
- const pages = await Promise.all(requests.map((r) => read(r.at, r.limit)));
114
- const shortAt = pages.findIndex((page, i) => page.returned < (requests[i]?.limit ?? 0));
115
- const short = pages[shortAt];
116
- const request = requests[shortAt];
117
- if (short && request) {
118
- // The end of the book, or a server trimming a page: carry on right
119
- // after what came back, until a page comes back empty.
120
- position = request.at + short.returned;
121
- done = short.returned === 0;
122
- }
123
- else {
124
- position = (starts.at(-1) ?? position) + size;
125
- }
126
- done ||= total !== undefined && position >= total;
127
- }
128
- return { capped: !done && position >= CARD_CAP, matched };
129
- };
130
- // Full cards for the sweep's matches, read in gets of at most PAGE ids.
131
- const getInPages = async (deps, ctx, ids) => {
132
- const cards = [];
133
- for (let i = 0; i < ids.length; i += PAGE) {
134
- cards.push(...(await deps.contactCardGet({
135
- ...ctx,
136
- apiUrl: "",
137
- ids: ids.slice(i, i + PAGE),
138
- })));
139
- }
140
- return cards;
141
- };
142
- // What matches, over the fields the description promises: display name,
143
- // organization, address, address domain, and role (`hasRole`, which drops a
144
- // leading "my " from the query). Notes are not among them: every collected
145
- // card carries the same machine-written note text, so a note hit would
146
- // answer "Collection" with the whole book.
147
- const matchesQuery = (card, query) => hasRole(card, query) ||
148
- matchesByName(card, query) ||
149
- matchesByAddress(card, query);
150
- const matchesByName = (card, query) => {
151
- const q = withoutMy(query);
152
- return (card.name?.full?.toLowerCase().includes(q) === true ||
153
- Object.values(card.organizations ?? {}).some((o) => o.name?.toLowerCase().includes(q)));
154
- };
155
- const matchesByAddress = (card, query) => {
156
- const q = withoutMy(query);
157
- return Object.values(card.emails ?? {}).some((e) => {
158
- const address = e.address.toLowerCase();
159
- return address.includes(q) || (address.split("@")[1] ?? "").includes(q);
160
- });
161
- };
162
- // How the agent gets from "my lawyer" to a person the first time, before a
163
- // role is stored. A role is recorded only on the user's word: a guess would
164
- // send their mail to the wrong person.
165
- const roleHint = 'If the query is what the person is to the user (e.g. "my lawyer"), find them with search_emails, ' +
166
- "confirm with the user who it is, then record it with update_contact `addedRoles` " +
167
- "(or create_contact `roles`) so the next request takes one lookup.";
168
- // `capped` is true when the sweep stopped at CARD_CAP, where a match may be
169
- // out of sight.
170
- const emptyResultText = (query, capped) => `No contact matched "${query}" in the collected address book (built from mail headers and calendar attendees) or the personal address books${capped ? "" : ", and no contact has it as a role"}. ` +
171
- "If you know part of the address or the organization, search for that instead. " +
172
- `${roleHint} ` +
173
- "If the person has only contacted the user via LinkedIn or another platform, no email address exists in this account's data.";
174
- // "my lawyer" is matched as "lawyer" everywhere, so a domain like
175
- // `smithlawyer.example` still turns up, flagged by the note below.
176
- const withoutMy = normalizeRole;
177
- // Hydrated, relative-dated prose for one interaction tuple.
178
- const interactionLine = (tuple, subjects, eventTitles, now) => {
179
- const age = relativeAge(tuple.date, now);
180
- if (tuple.channel === "calendar") {
181
- const title = eventTitles.get(tuple.recordId);
182
- return `${age} — calendar: ${title ?? "(event no longer available)"}`;
183
- }
184
- const subject = subjects.get(tuple.recordId);
185
- const verb = tuple.direction === "outgoing" ? "email sent" : "email received";
186
- return `${age} — ${verb}: ${subject ?? "(message no longer available)"}`;
187
- };
188
- // One batched Email/get for the subjects and one calendar pass for the
189
- // titles — only for the matched people (at most `limit`), never for the
190
- // whole book, and never per interaction line.
191
- const hydrate = async (deps, auth, tuples) => {
192
- const emailIds = [
193
- ...new Set(tuples.filter((t) => t.channel === "email").map((t) => t.recordId)),
194
- ];
195
- const eventUids = [
196
- ...new Set(tuples.filter((t) => t.channel === "calendar").map((t) => t.recordId)),
197
- ];
198
- const subjects = new Map();
199
- let eventTitles = new Map();
200
- if (emailIds.length > 0) {
201
- try {
202
- const mailAccountId = await deps.resolveMailAccountId(auth.authorization);
203
- const records = await deps.emailGet({
204
- accountId: mailAccountId,
205
- apiUrl: "",
206
- authorization: auth.authorization,
207
- ids: emailIds,
208
- });
209
- for (const r of records) {
210
- subjects.set(r.id, r.subject ?? null);
211
- }
212
- }
213
- catch {
214
- // Best-effort: lines degrade to "(message no longer available)".
215
- }
216
- }
217
- if (eventUids.length > 0) {
218
- try {
219
- eventTitles = await deps.fetchEventTitles(auth.token, eventUids);
220
- }
221
- catch {
222
- // Best-effort: lines degrade to "(event no longer available)".
223
- }
224
- }
225
- return { eventTitles, subjects };
226
- };
227
- const confidenceOf = (card, args) => bestAddress(card, args.context);
228
- const concisePerson = (card, ext, args, hydrated, now, index) => {
229
- const best = confidenceOf(card, args);
230
- const lines = ext.interactions
231
- .slice(0, SHOWN_INTERACTIONS)
232
- .map((t) => ` - ${interactionLine(t, hydrated.subjects, hydrated.eventTitles, now)}`);
233
- const organization = readOrganization(card);
234
- const roles = rolesLine(card);
235
- const birthday = birthdayLine(card);
236
- return [
237
- `${index + 1}. ${card.name?.full ?? best?.address ?? "(unnamed)"}`,
238
- // The handle create_contact/update_contact/delete_contact address the
239
- // record by — in the concise format too, so editing a contact never
240
- // costs an extra detailed round-trip.
241
- ` contact_id: ${card.id}`,
242
- ...(organization ? [` organization: ${organization}`] : []),
243
- ...(roles ? [roles] : []),
244
- // One short line, only when stored: "when is Robin's birthday" should
245
- // not need the detailed format.
246
- ...(birthday ? [birthday] : []),
247
- ` best_address: ${best?.address ?? "(none)"} (${best?.context ?? "unknown"})`,
248
- ` address_confidence: ${best?.confidence ?? "weak"} | relationship: ${relationshipFor(ext, now)}`,
249
- ...(lines.length > 0 ? [" last_interactions:", ...lines] : []),
250
- ].join("\n");
251
- };
252
- const detailedPerson = (card, ext, args, hydrated, now, index, collectedBookId) => {
253
- const parts = [concisePerson(card, ext, args, hydrated, now, index)];
254
- const candidates = addressCandidates(card);
255
- if (candidates.length > 0) {
256
- parts.push(" addresses:");
257
- for (const c of candidates) {
258
- const preferred = c.preferred ? ", preferred" : "";
259
- const seen = c.lastSeen
260
- ? `, last seen ${relativeAge(c.lastSeen, now)}`
261
- : "";
262
- parts.push(` - ${c.address} (${c.context}, ${c.confidence}${preferred}${seen})`);
263
- }
264
- }
265
- // The authored half of the record — phones, postal addresses, note. Only
266
- // in the detailed format: an agent resolving a name before drafting mail
267
- // has no use for a street address, and the concise format is what that
268
- // call reads. The birthday is already on the concise block above.
269
- parts.push(...profileLines(card, { birthday: false }));
270
- // Provenance, because `confidence` means different things across sources:
271
- // on a derived address it is an inference from headers, on an authored one
272
- // it is the user's own assertion.
273
- parts.push(` source: ${sourceOf(card, collectedBookId)}`);
274
- const withIds = ext.interactions.map((t) => ` - ${interactionLine(t, hydrated.subjects, hydrated.eventTitles, now)} [${t.channel === "email" ? "email id" : "event uid"}: ${t.recordId}]`);
275
- if (withIds.length > 0) {
276
- parts.push(" interaction_records:", ...withIds);
277
- }
278
- if (ext.relays && ext.relays.length > 0) {
279
- parts.push(` excluded_relays: ${ext.relays.join(", ")} (relay addresses, not usable for direct contact)`);
280
- }
281
- return parts.join("\n");
282
- };
283
- // What rendering one contact in the detailed format needs beyond the card:
284
- // the subject and title lookups for its interaction lines.
285
- const LIST_NUMBER = /^1\. /u;
286
- // One contact in the detailed format, exactly as search_contacts prints it —
287
- // what merge_contacts returns, so the agent checks a merge in the same shape
288
- // it found the cards in.
289
- export const renderDetailedContact = async (deps, auth, card, collectedBookId) => {
290
- const ext = readCollected(card);
291
- const hydrated = await hydrate(deps, auth, ext.interactions);
292
- const args = {
293
- context: "any",
294
- limit: 1,
295
- query: "",
296
- response_format: "detailed",
297
- };
298
- // One contact, so no list number in front of it.
299
- return detailedPerson(card, ext, args, hydrated, new Date(), 0, collectedBookId).replace(LIST_NUMBER, "");
300
- };
301
- export const searchContacts = async (deps, ctx) => {
302
- const { args, token } = ctx;
303
- const query = args.query.trim();
304
- if (query.length === 0) {
305
- return errorResult("query must not be empty.");
306
- }
307
- const authorization = authorizationHeader(token);
308
- const accountId = await deps.resolveAccountId(authorization);
309
- // Only the detailed format prints `source`, which needs the Collected
310
- // book's id.
311
- const detailed = args.response_format === "detailed";
312
- const [sweep, books] = await Promise.all([
313
- sweepBook(deps, { accountId, authorization }, query),
314
- detailed
315
- ? deps.addressBookList({ accountId, apiUrl: "", authorization })
316
- : Promise.resolve([]),
317
- ]);
318
- const collectedBookId = books.find((b) => b.name === COLLECTED_BOOK_NAME)?.id;
319
- const matched = await getInPages(deps, { accountId, authorization }, sweep.matched);
320
- const capNote = sweep.capped
321
- ? `\n\nOnly the first ${CARD_CAP} cards of the address books were searched; a contact past them may be missing.`
322
- : "";
323
- if (matched.length === 0) {
324
- return textResult(`${emptyResultText(query, sweep.capped)}${capNote}`);
325
- }
326
- // The people the user named this way come first: a role is the user's own
327
- // word for who they mean, which a name or domain hit ("Lawrence",
328
- // `lawhouse.example` for "lawyer") is not.
329
- const now = new Date();
330
- const roleHolders = matched.filter((c) => hasRole(c, query));
331
- const ranked = [
332
- ...rankCards(roleHolders, now),
333
- ...rankCards(matched.filter((c) => !hasRole(c, query)), now),
334
- ];
335
- const page = ranked.slice(0, args.limit);
336
- const shown = args.response_format === "detailed" ? undefined : SHOWN_INTERACTIONS;
337
- const tuples = page.flatMap((card) => {
338
- const interactions = readCollected(card).interactions;
339
- return shown === undefined ? interactions : interactions.slice(0, shown);
340
- });
341
- const hydrated = await hydrate(deps, { authorization, token }, tuples);
342
- const sections = page.map((card, i) => detailed
343
- ? detailedPerson(card, readCollected(card), args, hydrated, now, i, collectedBookId)
344
- : concisePerson(card, readCollected(card), args, hydrated, now, i));
345
- // Every match is counted, unless the sweep stopped at its cap.
346
- const atLeast = sweep.capped ? "at least " : "";
347
- const truncationNote = ranked.length > args.limit
348
- ? `\n\nShowing the top ${args.limit} of ${atLeast}${ranked.length} matches — narrow the query (add a surname, address fragment, or organization) to disambiguate.`
349
- : "";
350
- const relayNote = page.some((card) => (readCollected(card).relays?.length ?? 0) > 0)
351
- ? "\n\nNote: relay addresses (e.g. LinkedIn digests) were excluded as unusable; detailed format lists them."
352
- : "";
353
- const noRoleNote = roleHolders.length === 0 && isRolePhrase(query)
354
- ? `\n\n${sweep.capped ? "None of the people above has" : "No contact has"} "${withoutMy(query)}" as a role: the people above matched by name, organization or address only. ${roleHint}`
355
- : "";
356
- return textResult(`${page.length} person(s) matched:\n\n${sections.join("\n\n")}${noRoleNote}${relayNote}${truncationNote}${capNote}`);
357
- };
358
- // --- live-deps wiring ----------------------------------------------------
359
- export const makeLiveDeps = (live, caldav) => ({
360
- addressBookList: async (p) => addressBookList({
361
- ...p,
362
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
363
- }),
364
- contactCardGet: async (p) => contactCardGet({
365
- ...p,
366
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
367
- }),
368
- contactCardPage: async (p) => contactCardPage({
369
- ...p,
370
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
371
- }),
372
- emailGet: async (p) => emailGet({ ...p, apiUrl: (await live.getSession(p.authorization)).apiUrl }),
373
- fetchEventTitles: async (token, uids) => {
374
- // One discovery and at most one read per calendar, default first,
375
- // stopping as soon as every UID is resolved — the whole point of the
376
- // batch shape (a per-UID lookup re-read every collection).
377
- const wanted = new Set(uids);
378
- const titles = new Map();
379
- const account = await discoverAccount(caldav, token);
380
- const urls = [
381
- ...(account.defaultCalendarUrl ? [account.defaultCalendarUrl] : []),
382
- ...account.calendars
383
- .map((c) => c.url)
384
- .filter((u) => u !== account.defaultCalendarUrl),
385
- ];
386
- for (const calendarUrl of urls) {
387
- if (titles.size === wanted.size) {
388
- break;
389
- }
390
- for (const object of await fetchEvents(caldav, { calendarUrl, token })) {
391
- for (const event of parseEvents(object.data)) {
392
- if (wanted.has(event.uid) && !titles.has(event.uid) && event.title) {
393
- titles.set(event.uid, event.title);
394
- }
395
- }
396
- }
397
- }
398
- return titles;
399
- },
400
- resolveAccountId: async (authorization) => accountIdForContacts(await live.getSession(authorization)),
401
- resolveMailAccountId: live.resolveAccountId,
402
- });
403
- // --- MCP registration ----------------------------------------------------
404
- export const registerSearchContacts = (server, deps,
405
- // Bearer threaded per request — see mcp/handler.ts.
406
- getToken) => {
407
- server.registerTool("search_contacts", {
408
- annotations: READ_ONLY,
409
- description: "Resolve a person's name, partial name, email address, organization, or what " +
410
- 'they are to the user ("my lawyer", "my landlord") to known contacts. People ' +
411
- "holding that role come first, the rest are ranked by interaction recency and frequency. Sources " +
412
- "include the collected address book maintained from mail headers (both " +
413
- "directions, including Sent) and calendar attendees and organizers, plus " +
414
- "the user's personal address books, and contacts written with " +
415
- "create_contact. Use this before creating events or drafting mail when only " +
416
- "a name is known, and before create_contact or update_contact to get the " +
417
- "contact_id. Returns for each contact its roles, one or more addresses with a " +
418
- "confidence level, the birthday when one is stored, and recent " +
419
- "interactions; the detailed format adds phone numbers, postal addresses " +
420
- "and the note. Do not use it to enumerate all contacts; a query is " +
421
- 'required, and for "whose birthday is coming up" use ' +
422
- "list_upcoming_birthdays instead. If several plausible people match, " +
423
- "present the candidates to the user rather than guessing; when two of them " +
424
- "are the same person or organization, merge_contacts folds them into one.",
425
- inputSchema: z.object(searchContactsShape),
426
- title: "Search contacts",
427
- }, (args) => searchContacts(deps, {
428
- args: searchContactsInput.parse(args),
429
- token: getToken(),
430
- }));
431
- };