@access-mcp/announcements 0.1.0 → 0.3.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.
package/src/server.ts CHANGED
@@ -1,6 +1,22 @@
1
- import { BaseAccessServer } from "@access-mcp/shared";
1
+ import { BaseAccessServer, Tool, Resource, CallToolResult, DrupalAuthProvider } from "@access-mcp/shared";
2
+ import { CallToolRequest, ReadResourceRequest, ReadResourceResult, GetPromptResult, Prompt } from "@modelcontextprotocol/sdk/types.js";
3
+ import { createRequire } from "module";
4
+ const require = createRequire(import.meta.url);
5
+ const { version } = require("../package.json");
6
+
7
+ // ============================================================================
8
+ // Types
9
+ // ============================================================================
10
+
11
+ interface SearchAnnouncementsArgs {
12
+ query?: string;
13
+ tags?: string;
14
+ date?: string;
15
+ limit?: number;
16
+ }
2
17
 
3
18
  interface AnnouncementFilters {
19
+ query?: string;
4
20
  tags?: string;
5
21
  ag?: string;
6
22
  affiliation?: string;
@@ -8,130 +24,361 @@ interface AnnouncementFilters {
8
24
  relative_end_date?: string;
9
25
  start_date?: string;
10
26
  end_date?: string;
27
+ date?: string;
11
28
  limit?: number;
12
29
  }
13
30
 
14
31
  interface Announcement {
32
+ uuid?: string; // Added in API v2.2 update
15
33
  title: string;
16
34
  body: string;
17
- field_published_date: string;
18
- custom_announcement_ag: string;
19
- custom_announcement_tags: string;
20
- field_affiliation: string;
35
+ published_date: string;
36
+ affinity_group: string | string[];
37
+ tags: string | string[]; // API returns comma-separated string, we convert to array
38
+ affiliation: string;
39
+ summary?: string;
40
+ }
41
+
42
+ interface CreateAnnouncementArgs {
43
+ title: string;
44
+ body: string;
45
+ summary?: string;
46
+ published_date?: string;
47
+ tags?: string[];
48
+ affiliation?: string;
49
+ affinity_group?: string;
50
+ external_link?: { uri: string; title?: string };
51
+ where_to_share?: string[];
21
52
  }
22
53
 
54
+ interface UpdateAnnouncementArgs {
55
+ uuid: string;
56
+ title?: string;
57
+ body?: string;
58
+ summary?: string;
59
+ published_date?: string;
60
+ tags?: string[];
61
+ affinity_group?: string;
62
+ external_link?: { uri: string; title?: string };
63
+ where_to_share?: string[];
64
+ }
65
+
66
+ interface DeleteAnnouncementArgs {
67
+ uuid: string;
68
+ confirmed: boolean;
69
+ }
70
+
71
+ interface GetMyAnnouncementsArgs {
72
+ limit?: number;
73
+ }
74
+
75
+ // ============================================================================
76
+ // Server
77
+ // ============================================================================
78
+
23
79
  export class AnnouncementsServer extends BaseAccessServer {
80
+ private drupalAuth?: DrupalAuthProvider;
81
+ private tagCache: Map<string, string> = new Map(); // name -> uuid
82
+ private tagCacheExpiry?: Date;
83
+ private static TAG_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
84
+
24
85
  constructor() {
25
- super("access-announcements", "0.1.0", "https://support.access-ci.org");
86
+ super("access-announcements", version, "https://support.access-ci.org");
26
87
  }
27
88
 
28
- protected getTools() {
89
+ /**
90
+ * Get or create the Drupal auth provider for JSON:API write operations.
91
+ * Requires DRUPAL_API_URL, DRUPAL_USERNAME, and DRUPAL_PASSWORD env vars.
92
+ */
93
+ private getDrupalAuth(): DrupalAuthProvider {
94
+ if (!this.drupalAuth) {
95
+ const baseUrl = process.env.DRUPAL_API_URL;
96
+ const username = process.env.DRUPAL_USERNAME;
97
+ const password = process.env.DRUPAL_PASSWORD;
98
+
99
+ if (!baseUrl || !username || !password) {
100
+ throw new Error(
101
+ "CRUD operations require DRUPAL_API_URL, DRUPAL_USERNAME, and DRUPAL_PASSWORD environment variables"
102
+ );
103
+ }
104
+
105
+ this.drupalAuth = new DrupalAuthProvider(baseUrl, username, password);
106
+ }
107
+ return this.drupalAuth;
108
+ }
109
+
110
+ protected getTools(): Tool[] {
29
111
  return [
112
+ // Read operations (existing)
30
113
  {
31
- name: "get_announcements",
32
- description: "Search ACCESS support announcements about system maintenance, service updates, outages, and community news. Use this when users ask about recent announcements, service status, or need to filter by dates, tags, or affinity groups.",
114
+ name: "search_announcements",
115
+ description: "Search ACCESS announcements (news, updates, notifications). Read-only view of public announcements. For managing your own announcements (update/delete), use get_my_announcements which returns UUIDs. Returns {total, items: [{title, summary, body, published_date, tags, affiliation, affinity_group}]}.",
33
116
  inputSchema: {
34
117
  type: "object",
35
118
  properties: {
119
+ query: {
120
+ type: "string",
121
+ description: "Full-text search across title, body, and summary"
122
+ },
36
123
  tags: {
37
124
  type: "string",
38
- description: "Filter by specific topics (comma-separated). Real examples: 'gpu,nvidia', 'machine-learning,ai', 'maintenance,downtime', 'training,workshop', 'allocation-users', 'data-science', 'cloud-computing', 'bridges-2,anvil'"
125
+ description: "Filter by topics: gpu, ml, hpc"
39
126
  },
40
- ag: {
41
- type: "string",
42
- description: "Filter by system/community affinity group. Real examples: 'ACCESS Support', 'DELTA', 'Anvil', 'Bridges-2', 'CSSN (Computational Science Support Network)', 'Open OnDemand', 'Pegasus'"
127
+ date: {
128
+ type: "string",
129
+ description: "Time period filter: today, this_week (last 7 days), this_month (last 30 days), past (last year)",
130
+ enum: ["today", "this_week", "this_month", "past"]
43
131
  },
44
- affiliation: {
132
+ limit: {
133
+ type: "number",
134
+ description: "Max results (default: 25)",
135
+ default: 25
136
+ }
137
+ }
138
+ }
139
+ },
140
+ // CRUD operations (new)
141
+ {
142
+ name: "create_announcement",
143
+ description: `Create a new ACCESS announcement (saved as draft for staff review).
144
+
145
+ BEFORE CALLING:
146
+ 1. Call get_announcement_context first to get tags, check coordinator status, and tailor the conversation.
147
+ 2. Gather information - either conversationally OR by parsing pasted content:
148
+ - title (required): Clear, specific headline
149
+ - body (required): Full content with details, dates, links. HTML supported.
150
+ - summary (required): 1-2 sentence teaser for listings
151
+ - tags (recommended): 1-6 tags help users find it
152
+ - affiliation (optional): "ACCESS Collaboration" or "Community" (default)
153
+ - external_link (if relevant): URL and link text for external references
154
+ 3. IF user is a coordinator (check get_announcement_context response):
155
+ - affinity_group: Ask which group to associate with
156
+ - where_to_share: Ask preferences (defaults: Announcements page + Bi-Weekly Digest)
157
+
158
+ WORKFLOW:
159
+ If user pastes content (event description, draft text, etc.):
160
+ 1. Call get_announcement_context
161
+ 2. Parse the pasted content to extract title, body, dates, links, etc.
162
+ 3. Match content to available tags from context
163
+ 4. Ask only about missing/unclear fields
164
+ 5. If coordinator: ask about affinity group and where to share
165
+ 6. Show preview and get confirmation
166
+ 7. Create the announcement
167
+
168
+ If user describes what they want conversationally:
169
+ 1. Call get_announcement_context
170
+ 2. Guide them through providing title, body, summary
171
+ 3. Suggest relevant tags from context
172
+ 4. If coordinator: ask about affinity group and where to share
173
+ 5. Show preview and get confirmation
174
+ 6. Create the announcement
175
+
176
+ PREVIEW FORMAT (show before creating):
177
+ ---
178
+ **Title:** [title]
179
+ **Summary:** [summary or "None provided"]
180
+ **Body:**
181
+ [body content, truncate if very long]
182
+
183
+ **Tags:** [tag1, tag2, ...] or "None"
184
+ **Affiliation:** [affiliation or "Community (default)"]
185
+ **External Link:** [link text](url) or omit if none
186
+ [If coordinator:]
187
+ **Affinity Group:** [group name] or "None"
188
+ **Share to:** [list of selected options]
189
+ ---
190
+ Ask "Does this look correct?" before creating.
191
+
192
+ Returns: {success, uuid, title, edit_url}
193
+ ALWAYS display the edit_url to the user so they can review their draft in Drupal.`,
194
+ inputSchema: {
195
+ type: "object",
196
+ properties: {
197
+ title: {
45
198
  type: "string",
46
- description: "Filter by organization affiliation (e.g., 'ACCESS')"
199
+ description: "Announcement title - clear and specific, under 100 characters"
47
200
  },
48
- relative_start_date: {
201
+ body: {
49
202
  type: "string",
50
- description: "Filter announcements from a relative date. Examples: 'today', '-1 week', '-1 month', '-3 months', '-1 year'. Use negative values for past dates"
203
+ description: "Full announcement content. HTML allowed (basic_html format: <p>, <a>, <strong>, <em>, <ul>, <li>)"
51
204
  },
52
- relative_end_date: {
53
- type: "string",
54
- description: "Filter announcements up to a relative date. Examples: 'now', 'today', '-1 week' (past), '+1 week' (future)"
205
+ summary: {
206
+ type: "string",
207
+ description: "Brief teaser (1-2 sentences) shown in announcement listings. Required."
55
208
  },
56
- start_date: {
209
+ published_date: {
57
210
  type: "string",
58
- description: "Filter announcements from exact date onwards (YYYY-MM-DD). Use when users specify dates like 'since January 1st, 2024' or 'from March 15th'"
211
+ description: "When to display (YYYY-MM-DD). Defaults to today."
212
+ },
213
+ tags: {
214
+ type: "array",
215
+ items: { type: "string" },
216
+ description: "Tag names (1-6 required for publication). Use list_available_tags to find valid tags."
59
217
  },
60
- end_date: {
218
+ affiliation: {
61
219
  type: "string",
62
- description: "Filter announcements up to exact date (YYYY-MM-DD). Use when users specify dates like 'until December 31st, 2024' or 'before April 1st'"
220
+ description: "Source of announcement",
221
+ enum: ["ACCESS Collaboration", "Community"]
63
222
  },
64
- limit: {
65
- type: "number",
66
- description: "Maximum number of announcements to return. Use smaller values (5-10) for quick overviews, larger values (20-50) for comprehensive searches",
67
- default: 20
223
+ affinity_group: {
224
+ type: "string",
225
+ description: "Affinity group name or UUID. User must be coordinator of the group. Use list_affinity_groups to find valid groups."
226
+ },
227
+ external_link: {
228
+ type: "object",
229
+ description: "External link related to this announcement",
230
+ properties: {
231
+ uri: { type: "string", description: "URL (must include https://)" },
232
+ title: { type: "string", description: "Link text to display" }
233
+ },
234
+ required: ["uri"]
235
+ },
236
+ where_to_share: {
237
+ type: "array",
238
+ items: { type: "string" },
239
+ description: "Where to share the announcement. Defaults to 'Announcements page' + 'Bi-Weekly Digest'. Options: 'Announcements page', 'Bi-Weekly Digest', 'Affinity Group page', 'Email to Affinity Group'"
68
240
  }
69
- }
241
+ },
242
+ required: ["title", "body", "summary"]
70
243
  }
71
244
  },
72
245
  {
73
- name: "get_announcements_by_tags",
74
- description: "Find announcements about specific topics or systems. Use when users ask about particular subjects like 'GPU maintenance', 'machine learning resources', 'training workshops', or 'cloud computing updates'.",
246
+ name: "update_announcement",
247
+ description: `Update an existing announcement. User must own the announcement.
248
+
249
+ BEFORE CALLING:
250
+ 1. Use get_my_announcements to find the announcement UUID
251
+ 2. Confirm which fields the user wants to change
252
+ 3. Only include fields that are changing
253
+ 4. Show a preview of the changes and ask for confirmation before updating
254
+
255
+ Returns: {success, uuid, title, edit_url}
256
+ ALWAYS display the edit_url to the user so they can review changes in Drupal.`,
75
257
  inputSchema: {
76
258
  type: "object",
77
259
  properties: {
260
+ uuid: {
261
+ type: "string",
262
+ description: "UUID of the announcement (get from get_my_announcements)"
263
+ },
264
+ title: {
265
+ type: "string",
266
+ description: "New title (only if changing)"
267
+ },
268
+ body: {
269
+ type: "string",
270
+ description: "New body content (only if changing)"
271
+ },
272
+ summary: {
273
+ type: "string",
274
+ description: "New summary (only if changing)"
275
+ },
276
+ published_date: {
277
+ type: "string",
278
+ description: "New publication date YYYY-MM-DD (only if changing)"
279
+ },
78
280
  tags: {
281
+ type: "array",
282
+ items: { type: "string" },
283
+ description: "New tags - replaces ALL existing tags (only if changing)"
284
+ },
285
+ affinity_group: {
79
286
  type: "string",
80
- description: "Specific topics to search for (comma-separated). Popular examples: 'gpu,nvidia', 'machine-learning,ai', 'training,professional-development', 'data-science,python', 'cloud-computing', 'allocations-proposal'",
81
- required: true
287
+ description: "Affinity group name or UUID. User must be coordinator."
82
288
  },
83
- limit: {
84
- type: "number",
85
- description: "Maximum number of announcements to return",
86
- default: 10
289
+ external_link: {
290
+ type: "object",
291
+ description: "External link related to this announcement",
292
+ properties: {
293
+ uri: { type: "string", description: "URL (must include https://)" },
294
+ title: { type: "string", description: "Link text to display" }
295
+ },
296
+ required: ["uri"]
297
+ },
298
+ where_to_share: {
299
+ type: "array",
300
+ items: { type: "string" },
301
+ description: "Where to share the announcement. Options: 'Announcements page', 'Bi-Weekly Digest', 'Affinity Group page', 'Email to Affinity Group'"
87
302
  }
88
303
  },
89
- required: ["tags"]
304
+ required: ["uuid"]
90
305
  }
91
306
  },
92
307
  {
93
- name: "get_announcements_by_affinity_group",
94
- description: "Get announcements for a specific ACCESS system or community group. Use when users ask about updates for particular resources like DELTA, Anvil, or Bridges-2, or community groups like CSSN.",
308
+ name: "delete_announcement",
309
+ description: `Permanently delete an announcement. User must own the announcement.
310
+
311
+ CRITICAL: NEVER delete without explicit user confirmation for EACH announcement.
312
+
313
+ BEFORE CALLING (required for EVERY delete):
314
+ 1. Use get_my_announcements to find the announcement
315
+ 2. Show the user: "Delete '[title]' (status: [status])? This cannot be undone."
316
+ 3. For published announcements, add warning: "⚠️ This is currently visible to the public."
317
+ 4. Wait for explicit "yes" or confirmation - general statements like "sure" or "go ahead" are NOT sufficient
318
+ 5. Only proceed after receiving clear confirmation for THIS SPECIFIC announcement
319
+
320
+ BULK DELETES: When user asks to delete multiple announcements, confirm EACH ONE individually.
321
+ Do NOT batch delete based on general consent. Each deletion requires its own confirmation prompt.
322
+
323
+ Returns: {success, uuid}`,
95
324
  inputSchema: {
96
- type: "object",
325
+ type: "object",
97
326
  properties: {
98
- ag: {
327
+ uuid: {
99
328
  type: "string",
100
- description: "The system or community group name (not the technical API ID). Examples: 'DELTA', 'Anvil', 'Bridges-2', 'ACCESS Support', 'Open OnDemand', 'Pegasus', 'CSSN (Computational Science Support Network)'",
101
- required: true
329
+ description: "UUID of the announcement to delete"
102
330
  },
103
- limit: {
104
- type: "number",
105
- description: "Maximum number of announcements to return",
106
- default: 10
331
+ confirmed: {
332
+ type: "boolean",
333
+ description: "Set to true only after user has explicitly confirmed deletion of THIS specific announcement. Required."
107
334
  }
108
335
  },
109
- required: ["ag"]
336
+ required: ["uuid", "confirmed"]
110
337
  }
111
338
  },
112
339
  {
113
- name: "get_recent_announcements",
114
- description: "Get the latest ACCESS support announcements from a recent time period. Use this when users ask 'what's new?', 'recent updates', 'latest announcements', or want a general overview of current activity.",
340
+ name: "get_my_announcements",
341
+ description: `List all announcements created by the authenticated user.
342
+
343
+ Returns announcements with: uuid, nid, title, status (draft/published), created date, published_date, summary, edit_url
344
+
345
+ Use this to:
346
+ - Find announcement UUIDs for update/delete operations
347
+ - Check status of submitted announcements
348
+ - Review what the user has created
349
+ - Get edit_url links for users to review in Drupal`,
115
350
  inputSchema: {
116
351
  type: "object",
117
352
  properties: {
118
- period: {
119
- type: "string",
120
- description: "How far back to look for announcements. Examples: '1 week', '2 weeks', '1 month', '3 months', '6 months'. Default is '1 month'",
121
- default: "1 month"
122
- },
123
353
  limit: {
124
- type: "number",
125
- description: "Maximum number of announcements to return",
126
- default: 10
354
+ type: "number",
355
+ description: "Max results (default: 25)",
356
+ default: 25
127
357
  }
128
358
  }
129
359
  }
360
+ },
361
+ {
362
+ name: "get_announcement_context",
363
+ description: `Get user context and options BEFORE creating an announcement. Call this first.
364
+
365
+ Returns:
366
+ - tags: Available tags for announcements [{name, uuid}]
367
+ - affinity_groups: Groups the user coordinates (empty if not a coordinator)
368
+ - is_coordinator: Boolean - if true, ask about affinity_group and where_to_share
369
+ - affiliations: Available affiliation options
370
+ - where_to_share_options: Available sharing options (only relevant for coordinators)
371
+
372
+ Use this to tailor the announcement creation conversation based on the user's role.`,
373
+ inputSchema: {
374
+ type: "object",
375
+ properties: {}
376
+ }
130
377
  }
131
378
  ];
132
379
  }
133
380
 
134
- protected getResources() {
381
+ protected getResources(): Resource[] {
135
382
  return [
136
383
  {
137
384
  uri: "accessci://announcements",
@@ -142,35 +389,166 @@ export class AnnouncementsServer extends BaseAccessServer {
142
389
  ];
143
390
  }
144
391
 
145
- async handleToolCall(request: any) {
392
+ protected getPrompts(): Prompt[] {
393
+ return [
394
+ {
395
+ name: "create_announcement_guide",
396
+ description: "Guide the user through creating a new ACCESS announcement step by step",
397
+ arguments: [
398
+ {
399
+ name: "topic",
400
+ description: "Brief description of what the announcement is about (optional, helps tailor guidance)",
401
+ required: false,
402
+ },
403
+ ],
404
+ },
405
+ {
406
+ name: "manage_announcements_guide",
407
+ description: "Help the user view, update, or delete their existing announcements",
408
+ arguments: [],
409
+ },
410
+ ];
411
+ }
412
+
413
+ protected async handleGetPrompt(request: { params: { name: string; arguments?: Record<string, string> } }): Promise<GetPromptResult> {
414
+ const { name, arguments: args = {} } = request.params;
415
+
416
+ if (name === "create_announcement_guide") {
417
+ const topic = args.topic || "";
418
+
419
+ return {
420
+ description: "Guide for creating an ACCESS announcement",
421
+ messages: [
422
+ {
423
+ role: "user",
424
+ content: {
425
+ type: "text",
426
+ text: topic
427
+ ? `I want to create an announcement about: ${topic}`
428
+ : "I want to create a new announcement",
429
+ },
430
+ },
431
+ {
432
+ role: "assistant",
433
+ content: {
434
+ type: "text",
435
+ text: `I'll help you create an ACCESS announcement. Let me first check your available options and coordinator status.
436
+
437
+ First, I'll call \`get_announcement_context\` to see what tags are available and whether you coordinate any affinity groups.
438
+
439
+ **Required Information:**
440
+
441
+ 1. **Title** - A clear, concise title (under 100 characters)
442
+
443
+ 2. **Body** - The main content (HTML supported)
444
+
445
+ **Recommended:**
446
+
447
+ 3. **Summary** - Brief teaser (1-2 sentences) for listings
448
+
449
+ 4. **Tags** - Help users find your announcement (1-6 recommended)
450
+
451
+ **Optional:**
452
+
453
+ 5. **Affiliation** - "ACCESS Collaboration" or "Community" (default)
454
+
455
+ 6. **External Link** - If referencing external content
456
+
457
+ **For Affinity Group Coordinators:**
458
+ - Associate with your affinity group
459
+ - Choose where to share (Announcements page, Bi-Weekly Digest, Affinity Group page, Email to group)
460
+
461
+ **Important:** Announcements are created as **drafts** requiring staff review. You'll receive an edit URL.
462
+
463
+ Let me check your context first, then we'll get started!${topic ? `\n\nI see you want to announce something about "${topic}" - I'll help you craft that.` : ""}`,
464
+ },
465
+ },
466
+ ],
467
+ };
468
+ }
469
+
470
+ if (name === "manage_announcements_guide") {
471
+ return {
472
+ description: "Guide for managing existing announcements",
473
+ messages: [
474
+ {
475
+ role: "user",
476
+ content: {
477
+ type: "text",
478
+ text: "I want to manage my announcements",
479
+ },
480
+ },
481
+ {
482
+ role: "assistant",
483
+ content: {
484
+ type: "text",
485
+ text: `I can help you manage your ACCESS announcements. Here's what you can do:
486
+
487
+ **View Your Announcements**
488
+ Use \`get_my_announcements\` to see all announcements you've created, including:
489
+ - Draft announcements awaiting review
490
+ - Published announcements
491
+ - Their current status
492
+
493
+ **Update an Announcement**
494
+ Use \`update_announcement\` with the announcement's UUID to modify:
495
+ - Title
496
+ - Body content
497
+ - Summary
498
+ - Published date
499
+ - Tags
500
+
501
+ **Delete an Announcement**
502
+ Use \`delete_announcement\` with the UUID to remove an announcement you own.
503
+
504
+ Would you like me to:
505
+ 1. **List your announcements** - See what you've created
506
+ 2. **Update a specific announcement** - Make changes to an existing one
507
+ 3. **Delete an announcement** - Remove one you no longer need
508
+
509
+ Which would you like to do?`,
510
+ },
511
+ },
512
+ ],
513
+ };
514
+ }
515
+
516
+ throw new Error(`Unknown prompt: ${name}`);
517
+ }
518
+
519
+ protected async handleToolCall(request: CallToolRequest): Promise<CallToolResult> {
146
520
  const { name, arguments: args } = request.params;
147
521
 
148
522
  try {
149
523
  switch (name) {
150
- case "get_announcements":
151
- return await this.getAnnouncements(args);
152
- case "get_announcements_by_tags":
153
- return await this.getAnnouncementsByTags(args.tags, args.limit);
154
- case "get_announcements_by_affinity_group":
155
- return await this.getAnnouncementsByAffinityGroup(args.ag, args.limit);
156
- case "get_recent_announcements":
157
- return await this.getRecentAnnouncements(args.period, args.limit);
524
+ // Read operations
525
+ case "search_announcements":
526
+ return await this.searchAnnouncements(args as SearchAnnouncementsArgs);
527
+
528
+ // CRUD operations
529
+ case "create_announcement":
530
+ return await this.createAnnouncement(args as unknown as CreateAnnouncementArgs);
531
+ case "update_announcement":
532
+ return await this.updateAnnouncement(args as unknown as UpdateAnnouncementArgs);
533
+ case "delete_announcement":
534
+ return await this.deleteAnnouncement(args as unknown as DeleteAnnouncementArgs);
535
+ case "get_my_announcements":
536
+ return await this.getMyAnnouncements(args as unknown as GetMyAnnouncementsArgs);
537
+
538
+ // Helper operations
539
+ case "get_announcement_context":
540
+ return await this.getAnnouncementContext();
541
+
158
542
  default:
159
- throw new Error(`Unknown tool: ${name}`);
543
+ return this.errorResponse(`Unknown tool: ${name}`);
160
544
  }
161
- } catch (error: any) {
162
- return {
163
- content: [
164
- {
165
- type: "text",
166
- text: `Error: ${error.message}`
167
- }
168
- ]
169
- };
545
+ } catch (error) {
546
+ const message = error instanceof Error ? error.message : String(error);
547
+ return this.errorResponse(message);
170
548
  }
171
549
  }
172
550
 
173
- async handleResourceRead(request: any) {
551
+ protected async handleResourceRead(request: ReadResourceRequest): Promise<ReadResourceResult> {
174
552
  const { uri } = request.params;
175
553
 
176
554
  if (uri === "accessci://announcements") {
@@ -185,13 +563,14 @@ export class AnnouncementsServer extends BaseAccessServer {
185
563
  }
186
564
  ]
187
565
  };
188
- } catch (error: any) {
566
+ } catch (error) {
567
+ const message = error instanceof Error ? error.message : String(error);
189
568
  return {
190
569
  contents: [
191
570
  {
192
571
  uri,
193
- mimeType: "text/plain",
194
- text: `Error loading announcements: ${error.message}`
572
+ mimeType: "text/plain",
573
+ text: `Error loading announcements: ${message}`
195
574
  }
196
575
  ]
197
576
  };
@@ -201,32 +580,46 @@ export class AnnouncementsServer extends BaseAccessServer {
201
580
  throw new Error(`Unknown resource: ${uri}`);
202
581
  }
203
582
 
583
+ // ============================================================================
584
+ // Read Operations (existing)
585
+ // ============================================================================
586
+
587
+ private normalizeLimit(limit?: number): number {
588
+ const requestedLimit = limit || 25;
589
+ if (requestedLimit <= 5) return 5;
590
+ if (requestedLimit <= 10) return 10;
591
+ if (requestedLimit <= 25) return 25;
592
+ return 50;
593
+ }
594
+
204
595
  private buildAnnouncementsUrl(filters: AnnouncementFilters): string {
205
596
  const params = new URLSearchParams();
597
+ params.append("items_per_page", String(this.normalizeLimit(filters.limit)));
598
+
599
+ if (filters.query) {
600
+ params.append("search_api_fulltext", filters.query);
601
+ }
206
602
 
207
603
  if (filters.tags) {
208
604
  params.append("tags", filters.tags);
209
605
  }
210
- if (filters.ag) {
211
- params.append("ag", filters.ag);
212
- }
213
- if (filters.affiliation) {
214
- params.append("affiliation", filters.affiliation);
215
- }
216
- if (filters.relative_start_date) {
217
- params.append("relative_start_date", filters.relative_start_date);
218
- }
219
- if (filters.relative_end_date) {
220
- params.append("relative_end_date", filters.relative_end_date);
221
- }
222
- if (filters.start_date) {
223
- params.append("start_date", filters.start_date);
224
- }
225
- if (filters.end_date) {
226
- params.append("end_date", filters.end_date);
606
+
607
+ const dateMap: Record<string, {start: string, end?: string}> = {
608
+ today: {start: "today"},
609
+ this_week: {start: "-1 week", end: "now"},
610
+ this_month: {start: "-1 month", end: "now"},
611
+ past: {start: "-1 year", end: "now"}
612
+ };
613
+
614
+ if (filters.date && dateMap[filters.date]) {
615
+ const dateRange = dateMap[filters.date];
616
+ params.append("relative_start_date", dateRange.start);
617
+ if (dateRange.end) {
618
+ params.append("relative_end_date", dateRange.end);
619
+ }
227
620
  }
228
621
 
229
- return `/api/2.1/announcements?${params.toString()}`;
622
+ return `/api/2.2/announcements?${params.toString()}`;
230
623
  }
231
624
 
232
625
  private async fetchAnnouncements(filters: AnnouncementFilters): Promise<Announcement[]> {
@@ -241,107 +634,531 @@ export class AnnouncementsServer extends BaseAccessServer {
241
634
  return this.enhanceAnnouncements(announcements);
242
635
  }
243
636
 
244
- private enhanceAnnouncements(rawAnnouncements: any[]): Announcement[] {
637
+ private enhanceAnnouncements(rawAnnouncements: Announcement[]): Announcement[] {
245
638
  return rawAnnouncements.map(announcement => ({
246
639
  ...announcement,
247
- date: announcement.field_published_date,
248
- tags: announcement.custom_announcement_tags
249
- ? announcement.custom_announcement_tags.split(',').map((t: string) => t.trim()).filter((t: string) => t)
250
- : [],
251
- formatted_date: announcement.field_published_date
252
- ? new Date(announcement.field_published_date).toLocaleDateString('en-US', {
253
- year: 'numeric',
254
- month: 'long',
255
- day: 'numeric'
256
- })
257
- : '',
258
- body_preview: announcement.body
259
- ? announcement.body.replace(/<[^>]*>/g, '').substring(0, 200) + '...'
260
- : '',
261
- affinity_groups: announcement.custom_announcement_ag
262
- ? announcement.custom_announcement_ag.split(',').map((g: string) => g.trim()).filter((g: string) => g)
263
- : []
640
+ // Tags come as comma-separated string from public API, convert to array
641
+ tags: Array.isArray(announcement.tags)
642
+ ? announcement.tags
643
+ : (typeof announcement.tags === 'string' && announcement.tags.trim()
644
+ ? announcement.tags.split(',').map((t: string) => t.trim())
645
+ : []),
646
+ summary: announcement.summary || (announcement.body ? announcement.body.replace(/<[^>]*>/g, '').substring(0, 200) + '...' : '')
264
647
  }));
265
648
  }
266
649
 
267
- private async getAnnouncements(filters: AnnouncementFilters) {
650
+ private async searchAnnouncements(filters: SearchAnnouncementsArgs): Promise<CallToolResult> {
268
651
  const announcements = await this.fetchAnnouncements(filters);
269
652
  const limited = filters.limit ? announcements.slice(0, filters.limit) : announcements;
270
-
271
- // Build filters_applied object
272
- const filters_applied: any = {};
273
- if (filters.tags) filters_applied.tags = filters.tags;
274
- if (filters.ag) filters_applied.affinity_group = filters.ag;
275
- if (filters.relative_start_date || filters.relative_end_date) {
276
- filters_applied.date_range = `${filters.relative_start_date || 'any'} to ${filters.relative_end_date || 'now'}`;
277
- }
278
- if (filters.start_date || filters.end_date) {
279
- filters_applied.date_range = `${filters.start_date || 'any'} to ${filters.end_date || 'now'}`;
280
- }
281
- if (filters.limit) filters_applied.limit = filters.limit;
282
-
283
- const result = {
284
- total_announcements: announcements.length,
285
- filtered_announcements: limited.length,
286
- announcements: limited,
287
- filters_applied,
288
- popular_tags: this.getPopularTags(limited),
289
- message: limited.length === 0 ? "No announcements found matching the filters" : undefined
290
- };
291
653
 
292
654
  return {
293
- content: [
294
- {
295
- type: "text",
296
- text: JSON.stringify(result, null, 2)
655
+ content: [{
656
+ type: "text" as const,
657
+ text: JSON.stringify({
658
+ total: announcements.length,
659
+ items: limited
660
+ })
661
+ }]
662
+ };
663
+ }
664
+
665
+ // ============================================================================
666
+ // CRUD Operations (new)
667
+ // ============================================================================
668
+
669
+ /**
670
+ * Get the acting user's UID from environment variable.
671
+ * This identifies who the announcement should be attributed to.
672
+ */
673
+ private getActingUserUid(): number {
674
+ const envUid = process.env.ACTING_USER_UID;
675
+ if (envUid) {
676
+ const parsed = parseInt(envUid, 10);
677
+ if (!isNaN(parsed)) {
678
+ return parsed;
679
+ }
680
+ }
681
+
682
+ throw new Error(
683
+ "Cannot create announcement: No acting user specified.\n\n" +
684
+ "The ACTING_USER_UID environment variable must be set to the Drupal user ID " +
685
+ "of the person creating the announcement. This should be configured by the chat system."
686
+ );
687
+ }
688
+
689
+ /**
690
+ * Create a new announcement via Drupal JSON:API
691
+ */
692
+ private async createAnnouncement(args: CreateAnnouncementArgs): Promise<CallToolResult> {
693
+ const auth = this.getDrupalAuth();
694
+
695
+ // Get the acting user - required for proper attribution
696
+ const actingUserUid = this.getActingUserUid();
697
+ const userUuid = await this.getUserUuidByUid(actingUserUid);
698
+
699
+ if (!userUuid) {
700
+ throw new Error(`Could not find user with UID ${actingUserUid}. Verify the ACTING_USER_UID is correct.`);
701
+ }
702
+
703
+ // Build the JSON:API request body
704
+ const requestBody: any = {
705
+ data: {
706
+ type: "node--access_news",
707
+ attributes: {
708
+ title: args.title,
709
+ moderation_state: "draft", // Use content moderation workflow
710
+ body: {
711
+ value: args.body,
712
+ format: "basic_html"
713
+ }
714
+ },
715
+ relationships: {
716
+ uid: {
717
+ data: {
718
+ type: "user--user",
719
+ id: userUuid
720
+ }
721
+ }
297
722
  }
298
- ]
723
+ }
724
+ };
725
+
726
+ // Add optional fields
727
+ if (args.summary) {
728
+ requestBody.data.attributes.body.summary = args.summary;
729
+ }
730
+
731
+ if (args.published_date) {
732
+ requestBody.data.attributes.field_published_date = args.published_date;
733
+ } else {
734
+ // Default to today
735
+ requestBody.data.attributes.field_published_date = new Date().toISOString().split('T')[0];
736
+ }
737
+
738
+ if (args.affiliation) {
739
+ requestBody.data.attributes.field_affiliation = args.affiliation;
740
+ }
741
+
742
+ // Look up tag UUIDs if tags provided
743
+ if (args.tags && args.tags.length > 0) {
744
+ const tagUuids = await this.getTagUuidsByName(args.tags);
745
+ if (tagUuids.length > 0) {
746
+ requestBody.data.relationships.field_tags = {
747
+ data: tagUuids.map(uuid => ({
748
+ type: "taxonomy_term--tags",
749
+ id: uuid
750
+ }))
751
+ };
752
+ }
753
+ }
754
+
755
+ // Look up affinity group UUID if provided
756
+ if (args.affinity_group) {
757
+ const groupUuid = await this.getAffinityGroupUuid(args.affinity_group);
758
+ if (groupUuid) {
759
+ requestBody.data.relationships.field_affinity_group_node = {
760
+ data: {
761
+ type: "node--affinity_group",
762
+ id: groupUuid
763
+ }
764
+ };
765
+ } else {
766
+ throw new Error(`Affinity group not found: ${args.affinity_group}. Use list_affinity_groups to see groups you coordinate.`);
767
+ }
768
+ }
769
+
770
+ // Add external link if provided
771
+ if (args.external_link) {
772
+ requestBody.data.attributes.field_news_external_link = {
773
+ uri: args.external_link.uri,
774
+ title: args.external_link.title || ""
775
+ };
776
+ }
777
+
778
+ // Add where to share (defaults handled by Drupal if not provided)
779
+ if (args.where_to_share && args.where_to_share.length > 0) {
780
+ requestBody.data.attributes.field_choose_where_to_share_this = this.normalizeWhereToShare(args.where_to_share);
781
+ }
782
+
783
+ const result = await auth.post("/jsonapi/node/access_news", requestBody);
784
+
785
+ return {
786
+ content: [{
787
+ type: "text" as const,
788
+ text: JSON.stringify({
789
+ success: true,
790
+ message: "Announcement created (draft status)",
791
+ uuid: result.data?.id,
792
+ title: result.data?.attributes?.title,
793
+ edit_url: `${process.env.DRUPAL_API_URL}/node/${result.data?.attributes?.drupal_internal__nid}/edit`
794
+ })
795
+ }]
299
796
  };
300
797
  }
301
798
 
302
- private async getAnnouncementsByTags(tags: string, limit: number = 10) {
303
- return await this.getAnnouncements({ tags, limit });
799
+ /**
800
+ * Update an existing announcement via Drupal JSON:API
801
+ */
802
+ private async updateAnnouncement(args: UpdateAnnouncementArgs): Promise<CallToolResult> {
803
+ const auth = this.getDrupalAuth();
804
+
805
+ const requestBody: any = {
806
+ data: {
807
+ type: "node--access_news",
808
+ id: args.uuid,
809
+ attributes: {}
810
+ }
811
+ };
812
+
813
+ // Add fields to update
814
+ if (args.title) {
815
+ requestBody.data.attributes.title = args.title;
816
+ }
817
+
818
+ // Handle body/summary updates
819
+ // Fetch existing to preserve values not being changed
820
+ if (args.body || args.summary) {
821
+ const existing = await auth.get(`/jsonapi/node/access_news/${args.uuid}`);
822
+ const existingBody = existing.data?.attributes?.body?.value || "";
823
+ const existingSummary = existing.data?.attributes?.body?.summary || "";
824
+
825
+ requestBody.data.attributes.body = {
826
+ value: args.body || existingBody,
827
+ format: "basic_html",
828
+ summary: args.summary !== undefined ? args.summary : existingSummary
829
+ };
830
+ }
831
+ // If neither body nor summary provided, don't include body in request at all
832
+
833
+ if (args.published_date) {
834
+ requestBody.data.attributes.field_published_date = args.published_date;
835
+ }
836
+
837
+ // Update tags if provided
838
+ if (args.tags && args.tags.length > 0) {
839
+ const tagUuids = await this.getTagUuidsByName(args.tags);
840
+ if (tagUuids.length > 0) {
841
+ if (!requestBody.data.relationships) {
842
+ requestBody.data.relationships = {};
843
+ }
844
+ requestBody.data.relationships.field_tags = {
845
+ data: tagUuids.map(uuid => ({
846
+ type: "taxonomy_term--tags",
847
+ id: uuid
848
+ }))
849
+ };
850
+ }
851
+ }
852
+
853
+ // Update affinity group if provided
854
+ if (args.affinity_group) {
855
+ const groupUuid = await this.getAffinityGroupUuid(args.affinity_group);
856
+ if (groupUuid) {
857
+ if (!requestBody.data.relationships) {
858
+ requestBody.data.relationships = {};
859
+ }
860
+ requestBody.data.relationships.field_affinity_group_node = {
861
+ data: {
862
+ type: "node--affinity_group",
863
+ id: groupUuid
864
+ }
865
+ };
866
+ } else {
867
+ throw new Error(`Affinity group not found: ${args.affinity_group}. Use list_affinity_groups to see groups you coordinate.`);
868
+ }
869
+ }
870
+
871
+ // Update external link if provided
872
+ if (args.external_link) {
873
+ requestBody.data.attributes.field_news_external_link = {
874
+ uri: args.external_link.uri,
875
+ title: args.external_link.title || ""
876
+ };
877
+ }
878
+
879
+ // Update where to share if provided
880
+ if (args.where_to_share && args.where_to_share.length > 0) {
881
+ requestBody.data.attributes.field_choose_where_to_share_this = this.normalizeWhereToShare(args.where_to_share);
882
+ }
883
+
884
+ const result = await auth.patch(`/jsonapi/node/access_news/${args.uuid}`, requestBody);
885
+ const nid = result.data?.attributes?.drupal_internal__nid;
886
+ const baseUrl = process.env.DRUPAL_API_URL;
887
+
888
+ return {
889
+ content: [{
890
+ type: "text" as const,
891
+ text: JSON.stringify({
892
+ success: true,
893
+ message: "Announcement updated",
894
+ uuid: result.data?.id,
895
+ title: result.data?.attributes?.title,
896
+ edit_url: nid ? `${baseUrl}/node/${nid}/edit` : null
897
+ })
898
+ }]
899
+ };
304
900
  }
305
901
 
306
- private async getAnnouncementsByAffinityGroup(ag: string, limit: number = 10) {
307
- return await this.getAnnouncements({ ag, limit });
902
+ /**
903
+ * Delete an announcement via Drupal JSON:API
904
+ */
905
+ private async deleteAnnouncement(args: DeleteAnnouncementArgs): Promise<CallToolResult> {
906
+ // Enforce confirmation parameter
907
+ if (!args.confirmed) {
908
+ return {
909
+ content: [{
910
+ type: "text" as const,
911
+ text: JSON.stringify({
912
+ error: "Deletion requires explicit confirmation. You must show the announcement title and status to the user and get explicit confirmation before setting confirmed=true.",
913
+ uuid: args.uuid
914
+ })
915
+ }]
916
+ };
917
+ }
918
+
919
+ const auth = this.getDrupalAuth();
920
+
921
+ await auth.delete(`/jsonapi/node/access_news/${args.uuid}`);
922
+
923
+ return {
924
+ content: [{
925
+ type: "text" as const,
926
+ text: JSON.stringify({
927
+ success: true,
928
+ message: "Announcement deleted",
929
+ uuid: args.uuid
930
+ })
931
+ }]
932
+ };
308
933
  }
309
934
 
310
- private async getRecentAnnouncements(period: string = "1 month", limit: number = 10) {
311
- const relativeStart = `-${period}`;
312
- return await this.getAnnouncements({
313
- relative_start_date: relativeStart,
314
- relative_end_date: "now",
315
- limit
935
+ /**
936
+ * Get announcements created by the acting user
937
+ */
938
+ private async getMyAnnouncements(args: GetMyAnnouncementsArgs): Promise<CallToolResult> {
939
+ const auth = this.getDrupalAuth();
940
+
941
+ // Get the acting user's UUID
942
+ const actingUserUid = this.getActingUserUid();
943
+ const userUuid = await this.getUserUuidByUid(actingUserUid);
944
+
945
+ if (!userUuid) {
946
+ throw new Error(`Could not find user with UID ${actingUserUid}. Verify the ACTING_USER_UID is correct.`);
947
+ }
948
+
949
+ const limit = args.limit || 25;
950
+ const result = await auth.get(
951
+ `/jsonapi/node/access_news?filter[uid.id]=${userUuid}&page[limit]=${limit}&sort=-created`
952
+ );
953
+
954
+ const baseUrl = process.env.DRUPAL_API_URL;
955
+ const announcements = (result.data || []).map((item: any) => {
956
+ const nid = item.attributes?.drupal_internal__nid;
957
+ return {
958
+ uuid: item.id,
959
+ nid,
960
+ title: item.attributes?.title,
961
+ status: item.attributes?.status ? "published" : "draft",
962
+ created: item.attributes?.created,
963
+ published_date: item.attributes?.field_published_date,
964
+ summary: item.attributes?.body?.summary ||
965
+ (item.attributes?.body?.value ?
966
+ item.attributes.body.value.replace(/<[^>]*>/g, '').substring(0, 200) + '...' : ''),
967
+ edit_url: nid ? `${baseUrl}/node/${nid}/edit` : null
968
+ };
316
969
  });
970
+
971
+ return {
972
+ content: [{
973
+ type: "text" as const,
974
+ text: JSON.stringify({
975
+ total: announcements.length,
976
+ items: announcements
977
+ })
978
+ }]
979
+ };
317
980
  }
318
981
 
319
- private getPopularTags(announcements: any[]): string[] {
320
- const tagCounts: { [key: string]: number } = {};
321
-
322
- announcements.forEach(announcement => {
323
- if (announcement.tags) {
324
- announcement.tags.forEach((tag: string) => {
325
- tagCounts[tag] = (tagCounts[tag] || 0) + 1;
326
- });
982
+ // ============================================================================
983
+ // Helper Methods
984
+ // ============================================================================
985
+
986
+ /**
987
+ * Get a user's UUID by their Drupal user ID (internal helper)
988
+ */
989
+ private async getUserUuidByUid(uid: number): Promise<string | null> {
990
+ const auth = this.getDrupalAuth();
991
+ const result = await auth.get(`/jsonapi/user/user?filter[drupal_internal__uid]=${uid}`);
992
+
993
+ if (!result.data || result.data.length === 0) {
994
+ return null;
995
+ }
996
+
997
+ return result.data[0].id;
998
+ }
999
+
1000
+ /**
1001
+ * Get announcement context - tags, affinity groups, and options for creating announcements
1002
+ */
1003
+ private async getAnnouncementContext(): Promise<CallToolResult> {
1004
+ const auth = this.getDrupalAuth();
1005
+
1006
+ // Get the acting user's UUID
1007
+ const actingUserUid = this.getActingUserUid();
1008
+ const userUuid = await this.getUserUuidByUid(actingUserUid);
1009
+
1010
+ if (!userUuid) {
1011
+ throw new Error(`Could not find user with UID ${actingUserUid}`);
1012
+ }
1013
+
1014
+ // Fetch tags and affinity groups in parallel
1015
+ const [tagsResult, groupsResult] = await Promise.all([
1016
+ auth.get("/jsonapi/taxonomy_term/tags?page[limit]=100"),
1017
+ auth.get(`/jsonapi/node/affinity_group?filter[field_coordinator.id]=${userUuid}&filter[status]=1&page[limit]=100`)
1018
+ ]);
1019
+
1020
+ const tags = (tagsResult.data || []).map((item: any) => ({
1021
+ name: item.attributes?.name,
1022
+ uuid: item.id
1023
+ }));
1024
+
1025
+ const affinityGroups = (groupsResult.data || []).map((item: any) => ({
1026
+ id: item.attributes?.field_group_id,
1027
+ uuid: item.id,
1028
+ name: item.attributes?.title,
1029
+ category: item.attributes?.field_affinity_group_category
1030
+ }));
1031
+
1032
+ const isCoordinator = affinityGroups.length > 0;
1033
+
1034
+ return {
1035
+ content: [{
1036
+ type: "text" as const,
1037
+ text: JSON.stringify({
1038
+ tags: tags,
1039
+ affinity_groups: affinityGroups,
1040
+ is_coordinator: isCoordinator,
1041
+ affiliations: ["ACCESS Collaboration", "Community"],
1042
+ where_to_share_options: [
1043
+ { value: "Announcements page", description: "Public announcements listing" },
1044
+ { value: "Bi-Weekly Digest", description: "ACCESS Support bi-weekly email digest" },
1045
+ { value: "Affinity Group page", description: "Your affinity group's page (coordinators only)" },
1046
+ { value: "Email to Affinity Group", description: "Direct email to affinity group members (coordinators only)" }
1047
+ ],
1048
+ guidance: isCoordinator
1049
+ ? "User is an affinity group coordinator. Ask about affinity_group association and where_to_share preferences."
1050
+ : "User is not a coordinator. Standard announcement fields apply."
1051
+ })
1052
+ }]
1053
+ };
1054
+ }
1055
+
1056
+ /**
1057
+ * Look up affinity group UUID by ID or name
1058
+ */
1059
+ private async getAffinityGroupUuid(idOrName: string): Promise<string | null> {
1060
+ const auth = this.getDrupalAuth();
1061
+
1062
+ // If it looks like a UUID, return as-is
1063
+ if (idOrName.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)) {
1064
+ return idOrName;
1065
+ }
1066
+
1067
+ // Try by field_group_id first
1068
+ let result = await auth.get(
1069
+ `/jsonapi/node/affinity_group?filter[field_group_id]=${encodeURIComponent(idOrName)}&filter[status]=1`
1070
+ );
1071
+
1072
+ if (result.data && result.data.length > 0) {
1073
+ return result.data[0].id;
1074
+ }
1075
+
1076
+ // Try by title
1077
+ result = await auth.get(
1078
+ `/jsonapi/node/affinity_group?filter[title]=${encodeURIComponent(idOrName)}&filter[status]=1`
1079
+ );
1080
+
1081
+ if (result.data && result.data.length > 0) {
1082
+ return result.data[0].id;
1083
+ }
1084
+
1085
+ return null;
1086
+ }
1087
+
1088
+ /**
1089
+ * Map human-friendly "where to share" labels to Drupal values
1090
+ */
1091
+ private static WHERE_TO_SHARE_MAP: Record<string, string> = {
1092
+ "announcements page": "on_the_announcements_page",
1093
+ "on the announcements page": "on_the_announcements_page",
1094
+ "bi-weekly digest": "in_the_access_support_bi_weekly_digest",
1095
+ "in the access support bi-weekly digest": "in_the_access_support_bi_weekly_digest",
1096
+ "affinity group page": "on_your_affinity_group_page",
1097
+ "on your affinity group page": "on_your_affinity_group_page",
1098
+ "email to affinity group": "email_to_your_affinity_group",
1099
+ "email to your affinity group": "email_to_your_affinity_group",
1100
+ // Also accept the raw values
1101
+ "on_the_announcements_page": "on_the_announcements_page",
1102
+ "in_the_access_support_bi_weekly_digest": "in_the_access_support_bi_weekly_digest",
1103
+ "on_your_affinity_group_page": "on_your_affinity_group_page",
1104
+ "email_to_your_affinity_group": "email_to_your_affinity_group",
1105
+ };
1106
+
1107
+ private normalizeWhereToShare(values: string[]): string[] {
1108
+ return values.map(v => {
1109
+ const normalized = AnnouncementsServer.WHERE_TO_SHARE_MAP[v.toLowerCase()];
1110
+ if (!normalized) {
1111
+ throw new Error(
1112
+ `Invalid where_to_share value: "${v}". ` +
1113
+ `Valid options: 'Announcements page', 'Bi-Weekly Digest', 'Affinity Group page', 'Email to Affinity Group'`
1114
+ );
327
1115
  }
1116
+ return normalized;
328
1117
  });
1118
+ }
329
1119
 
330
- return Object.entries(tagCounts)
331
- .sort(([,a], [,b]) => b - a)
332
- .slice(0, 10)
333
- .map(([tag]) => tag);
1120
+ /**
1121
+ * Check if tag cache is still valid
1122
+ */
1123
+ private isTagCacheValid(): boolean {
1124
+ return this.tagCacheExpiry !== undefined && new Date() < this.tagCacheExpiry;
334
1125
  }
335
1126
 
336
- private getAffinityGroups(announcements: any[]): string[] {
337
- const groups = new Set<string>();
338
- announcements.forEach(announcement => {
339
- if (announcement.affinity_groups && Array.isArray(announcement.affinity_groups)) {
340
- announcement.affinity_groups.forEach((group: string) => {
341
- if (group) groups.add(group);
342
- });
1127
+ /**
1128
+ * Populate the tag cache with all available tags
1129
+ */
1130
+ private async populateTagCache(): Promise<void> {
1131
+ const auth = this.getDrupalAuth();
1132
+ const result = await auth.get("/jsonapi/taxonomy_term/tags?page[limit]=500");
1133
+
1134
+ this.tagCache.clear();
1135
+ for (const item of result.data || []) {
1136
+ const name = item.attributes?.name?.toLowerCase();
1137
+ if (name && item.id) {
1138
+ this.tagCache.set(name, item.id);
343
1139
  }
344
- });
345
- return Array.from(groups);
1140
+ }
1141
+
1142
+ this.tagCacheExpiry = new Date(Date.now() + AnnouncementsServer.TAG_CACHE_TTL_MS);
346
1143
  }
347
- }
1144
+
1145
+ /**
1146
+ * Get tag UUIDs by their names (with caching)
1147
+ */
1148
+ private async getTagUuidsByName(tagNames: string[]): Promise<string[]> {
1149
+ // Ensure cache is populated
1150
+ if (!this.isTagCacheValid()) {
1151
+ await this.populateTagCache();
1152
+ }
1153
+
1154
+ const uuids: string[] = [];
1155
+ for (const name of tagNames) {
1156
+ const uuid = this.tagCache.get(name.toLowerCase());
1157
+ if (uuid) {
1158
+ uuids.push(uuid);
1159
+ }
1160
+ }
1161
+
1162
+ return uuids;
1163
+ }
1164
+ }