infinitecampus-mcp 3.1.8 → 3.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.
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { lstat, realpath } from 'fs/promises';
2
2
  import { basename, dirname, join, resolve } from 'path';
3
- import { assertPathWithinRoots, detectEdgeBlock, EdgeBlockedError, FileWriteRefusedError, parseCookieJar, truncateErrorMessage, writeFileSafe, } from '@chrischall/mcp-utils';
3
+ import { assertPathWithinRoots, detectEdgeBlock, EdgeBlockedError, FileWriteRefusedError, parseCookieJar, truncateErrorMessage, withAmbientCancellation, writeFileSafe, } from '@chrischall/mcp-utils';
4
4
  import { createCookieSessionManager } from '@chrischall/mcp-utils/session';
5
5
  import { resolveDownloadDir } from './config.js';
6
6
  import { createSessionCache, reportCacheWriteFailure } from './session-cache.js';
@@ -32,6 +32,10 @@ export class ICClient {
32
32
  linkedTo = new Map(); // linkedDistrictName → primaryDistrictName
33
33
  primaryName;
34
34
  featuresCache = new Map();
35
+ /** Campus version per district, read once. A failed read is dropped, to be retried after VERSION_RETRY_MS. */
36
+ versions = new Map();
37
+ /** When each district's last version read failed — see VERSION_RETRY_MS. */
38
+ versionFailedAt = new Map();
35
39
  /**
36
40
  * True when the primary account has empty creds (fetchproxy mode). The
37
41
  * client uses pre-loaded cookies in place of the `verify.jsp` POST and
@@ -248,7 +252,43 @@ export class ICClient {
248
252
  async request(district, path, opts = {}) {
249
253
  const account = await this.resolveAccount(district);
250
254
  await this.managers.get(account.name).ensure();
251
- return this.doRequest(account, path, opts);
255
+ try {
256
+ return await this.doRequest(account, path, opts);
257
+ }
258
+ catch (e) {
259
+ // A 5xx is the failure most likely to be a Campus release changing
260
+ // behaviour under us (#253), so it carries the version into the report.
261
+ if (e instanceof PortalUnreachableError)
262
+ e.setCampusVersion(await this.campusVersion(account.name));
263
+ throw e;
264
+ }
265
+ }
266
+ /**
267
+ * The district's Campus version (e.g. "2635.16"), or null when it cannot be
268
+ * read. DIAGNOSTIC ONLY — nothing chooses behaviour by it. The only place IC
269
+ * states it is the parent login page footer ("Version:Campus-2635.16"),
270
+ * which needs no session, so this works in fetchproxy mode too and never
271
+ * touches a district's cookies.
272
+ */
273
+ campusVersion(district) {
274
+ const account = this.accounts.get(district);
275
+ if (!account)
276
+ return Promise.resolve(null);
277
+ const failedAt = this.versionFailedAt.get(account.name);
278
+ if (failedAt !== undefined && Date.now() - failedAt < VERSION_RETRY_MS)
279
+ return Promise.resolve(null);
280
+ let pending = this.versions.get(account.name);
281
+ if (!pending) {
282
+ pending = fetchCampusVersion(account).then((v) => {
283
+ if (v === null) {
284
+ this.versions.delete(account.name);
285
+ this.versionFailedAt.set(account.name, Date.now());
286
+ }
287
+ return v;
288
+ });
289
+ this.versions.set(account.name, pending);
290
+ }
291
+ return pending;
252
292
  }
253
293
  /**
254
294
  * The account for `district`, running CUPS discovery once on a miss.
@@ -323,7 +363,7 @@ export class ICClient {
323
363
  // Credentials go in the urlencoded form body, NOT the URL query string —
324
364
  // query-string creds land in proxy/LB/server access logs even over HTTPS.
325
365
  // Mirrors the CUPS switch POST body construction against the same host.
326
- const postRes = await fetch(`${account.baseUrl}/campus/verify.jsp?nonBrowser=true`, {
366
+ const postRes = await icFetch(`${account.baseUrl}/campus/verify.jsp?nonBrowser=true`, {
327
367
  method: 'POST',
328
368
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
329
369
  body: new URLSearchParams({
@@ -393,7 +433,7 @@ export class ICClient {
393
433
  ...(session.xsrfToken ? { 'X-XSRF-TOKEN': session.xsrfToken } : {}),
394
434
  };
395
435
  // 1. Get linked accounts
396
- const laRes = await fetch(`${account.baseUrl}/campus/api/campus/authentication/cups/linkedAccounts`, { headers: baseHeaders });
436
+ const laRes = await icFetch(`${account.baseUrl}/campus/api/campus/authentication/cups/linkedAccounts`, { headers: baseHeaders });
397
437
  if (!laRes.ok) {
398
438
  // A 401/403 here does not mean "no CUPS" — it means the session this
399
439
  // probe used is dead. Leaving it in place was the half-fix: the latch
@@ -425,8 +465,8 @@ export class ICClient {
425
465
  }
426
466
  // 2. Get original district info (needed for all linked accounts)
427
467
  const [origRes, currRes] = await Promise.all([
428
- fetch(`${account.baseUrl}/campus/api/campus/user/userAccountSwitch/originalDistrict`, { headers: baseHeaders }),
429
- fetch(`${account.baseUrl}/campus/api/campus/districts/current`, { headers: baseHeaders }),
468
+ icFetch(`${account.baseUrl}/campus/api/campus/user/userAccountSwitch/originalDistrict`, { headers: baseHeaders }),
469
+ icFetch(`${account.baseUrl}/campus/api/campus/districts/current`, { headers: baseHeaders }),
430
470
  ]);
431
471
  // Same shape as above: the session answered, so no re-mint — but
432
472
  // discovery did not complete, so no latch either, and a later call
@@ -438,8 +478,19 @@ export class ICClient {
438
478
  // 3. For each linked account, get CUPS token and authenticate
439
479
  for (const linked of laData.accounts) {
440
480
  try {
481
+ // The linked district's login URL comes from the primary's JSON, not
482
+ // from config, so hold it to loadAccount's IC_BASE_URL rule before
483
+ // anything is sent to it: the CUPS token is POSTed there and its
484
+ // origin carries the linked session cookies for every later request.
485
+ // Checked before the token is minted, so a cleartext URL never even
486
+ // gets one. An unparseable URL throws into the catch below.
487
+ const loginUrl = new URL(linked.districtLoginUrl);
488
+ if (loginUrl.protocol !== 'https:') {
489
+ console.error(`[ic] CUPS: skipping ${linked.districtName} — its login URL is not https (${loginUrl.protocol})`);
490
+ continue;
491
+ }
441
492
  // Get CUPS login token
442
- const tokenRes = await fetch(`${account.baseUrl}/campus/api/campus/authentication/cups/loginToken`, {
493
+ const tokenRes = await icFetch(`${account.baseUrl}/campus/api/campus/authentication/cups/loginToken`, {
443
494
  method: 'POST',
444
495
  headers: baseHeaders,
445
496
  body: JSON.stringify({ dstClientId: linked.clientId, dstUserId: linked.userId }),
@@ -449,10 +500,9 @@ export class ICClient {
449
500
  continue;
450
501
  }
451
502
  const tokenData = await tokenRes.json();
452
- // Extract base URL from districtLoginUrl
453
- const linkedBaseUrl = new URL(linked.districtLoginUrl).origin;
503
+ const linkedBaseUrl = loginUrl.origin;
454
504
  // POST to linked district's verify.jsp with CUPS token
455
- const switchRes = await fetch(`${linked.districtLoginUrl}?nonBrowser=true&appName=${encodeURIComponent(linked.appName)}&portalLoginPage=parents`, {
505
+ const switchRes = await icFetch(`${linked.districtLoginUrl}?nonBrowser=true&appName=${encodeURIComponent(linked.appName)}&portalLoginPage=parents`, {
456
506
  method: 'POST',
457
507
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
458
508
  body: new URLSearchParams({
@@ -543,12 +593,12 @@ export class ICClient {
543
593
  // session (one restored from disk, or idled out server-side), re-logs in
544
594
  // and replays exactly once. A bare ensure()+fetch left a stale session in
545
595
  // place, so every retry 401'd until some unrelated call refreshed it.
546
- const res = await this.managers.get(account.name).withSession(async (session) => fetch(url, {
596
+ const res = await this.managers.get(account.name).withSession(async (session) => icFetch(url, {
547
597
  headers: {
548
598
  Cookie: session.cookieHeader,
549
599
  ...(session.xsrfToken ? { 'X-XSRF-TOKEN': session.xsrfToken } : {}),
550
600
  },
551
- }));
601
+ }, DOWNLOAD_TIMEOUT_MS));
552
602
  if (!res.ok) {
553
603
  // A CDN/WAF refusal page (chrischall/mcp-host#1015) never reached IC, so
554
604
  // nothing judged the session: withSession already returned it untouched
@@ -564,7 +614,7 @@ export class ICClient {
564
614
  throw new SessionExpiredError(account.name);
565
615
  if (!res.ok)
566
616
  throw new Error(`IC download ${res.status} for ${path}`);
567
- const buf = new Uint8Array(await res.arrayBuffer());
617
+ const buf = await readCapped(res, path);
568
618
  await writeConfined(target.real, destinationPath, buf, !!opts.overwrite);
569
619
  return {
570
620
  path: target.requested,
@@ -579,7 +629,7 @@ export class ICClient {
579
629
  // primary + sibling sessions for a linked district), the manager
580
630
  // invalidates this district, re-logs-in single-flight, and replays the
581
631
  // request EXACTLY once.
582
- const res = await mgr.withSession(async (session) => fetch(`${account.baseUrl}${path}`, {
632
+ const res = await mgr.withSession(async (session) => icFetch(`${account.baseUrl}${path}`, {
583
633
  method: opts.method ?? 'GET',
584
634
  headers: {
585
635
  Cookie: session.cookieHeader,
@@ -782,12 +832,35 @@ export class AuthFailedError extends Error {
782
832
  export class PortalUnreachableError extends Error {
783
833
  district;
784
834
  status;
835
+ /** The district's Campus version, when it could be read — for bug reports. */
836
+ campusVersion;
785
837
  constructor(district, status) {
786
838
  super(`Portal unreachable for district '${district}' (status ${status})`);
787
839
  this.district = district;
788
840
  this.status = status;
789
841
  this.name = 'PortalUnreachableError';
790
842
  }
843
+ setCampusVersion(version) {
844
+ if (version === null)
845
+ return;
846
+ this.campusVersion = version;
847
+ this.message += ` [Campus ${version}]`;
848
+ }
849
+ }
850
+ /** The version from a Campus login page footer ("Version:Campus-2635.16"), or null. */
851
+ export function parseCampusVersion(html) {
852
+ return /Version:\s*Campus-([0-9][\w.-]*)/.exec(html)?.[1] ?? null;
853
+ }
854
+ async function fetchCampusVersion(account) {
855
+ try {
856
+ const res = await icFetch(`${account.baseUrl}/campus/portal/parents/${encodeURIComponent(account.district)}.jsp`, {}, VERSION_TIMEOUT_MS);
857
+ if (!res.ok)
858
+ return null;
859
+ return parseCampusVersion(await res.text());
860
+ }
861
+ catch {
862
+ return null;
863
+ }
791
864
  }
792
865
  export class SessionExpiredError extends Error {
793
866
  district;
@@ -809,6 +882,76 @@ export class DocumentOriginNotAllowedError extends Error {
809
882
  this.name = 'DocumentOriginNotAllowedError';
810
883
  }
811
884
  }
885
+ /** Per-request ceiling for every IC call except a document download. */
886
+ export const REQUEST_TIMEOUT_MS = 30_000;
887
+ /**
888
+ * The Campus version read rides on failures (request() reads it on every 5xx),
889
+ * so it must not add the full request timeout to a call that already failed.
890
+ */
891
+ export const VERSION_TIMEOUT_MS = 5_000;
892
+ /** How long a failed version read is remembered before the page is read again. */
893
+ export const VERSION_RETRY_MS = 5 * 60 * 1000;
894
+ /** Ceiling for a document download, which moves a whole file. */
895
+ export const DOWNLOAD_TIMEOUT_MS = 120_000;
896
+ /**
897
+ * Largest document download accepted. Report cards and transcripts are
898
+ * single-digit MB; anything past this is not a school document worth holding
899
+ * in memory before it is written.
900
+ */
901
+ export const MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024;
902
+ /**
903
+ * The one way this client calls Infinite Campus (fleet-audit#1026): every
904
+ * request carries a timeout, combined with the running tool call's cancel
905
+ * signal, so a stalled portal cannot hang a tool and a cancelled call stops
906
+ * its fetch instead of letting it run on.
907
+ */
908
+ function icFetch(url, init = {}, timeoutMs = REQUEST_TIMEOUT_MS) {
909
+ return fetch(url, { ...init, signal: withAmbientCancellation(AbortSignal.timeout(timeoutMs)) });
910
+ }
911
+ /**
912
+ * Read a download body into memory, refusing it past {@link MAX_DOWNLOAD_BYTES}
913
+ * — up front from content-length when the server declares one, and otherwise
914
+ * by counting as it streams, so an oversized body is never fully buffered.
915
+ */
916
+ async function readCapped(res, path) {
917
+ if (!res.body)
918
+ return new Uint8Array(0);
919
+ if (Number(res.headers.get('content-length')) > MAX_DOWNLOAD_BYTES) {
920
+ await res.body.cancel();
921
+ throw new DownloadTooLargeError(path, MAX_DOWNLOAD_BYTES);
922
+ }
923
+ const reader = res.body.getReader();
924
+ const chunks = [];
925
+ let total = 0;
926
+ for (;;) {
927
+ const { done, value } = await reader.read();
928
+ if (done)
929
+ break;
930
+ total += value.byteLength;
931
+ if (total > MAX_DOWNLOAD_BYTES) {
932
+ await reader.cancel();
933
+ throw new DownloadTooLargeError(path, MAX_DOWNLOAD_BYTES);
934
+ }
935
+ chunks.push(value);
936
+ }
937
+ const buf = new Uint8Array(total);
938
+ let offset = 0;
939
+ for (const c of chunks) {
940
+ buf.set(c, offset);
941
+ offset += c.byteLength;
942
+ }
943
+ return buf;
944
+ }
945
+ export class DownloadTooLargeError extends Error {
946
+ path;
947
+ limit;
948
+ constructor(path, limit) {
949
+ super(`DownloadTooLarge: ${path} exceeds the ${limit / (1024 * 1024)} MB download limit`);
950
+ this.path = path;
951
+ this.limit = limit;
952
+ this.name = 'DownloadTooLargeError';
953
+ }
954
+ }
812
955
  export class InvalidPathError extends Error {
813
956
  path;
814
957
  constructor(path, reason = 'is a directory') {
package/dist/index.js CHANGED
@@ -56,7 +56,7 @@ catch (e) {
56
56
  // avoids — see `unconfiguredClient`.
57
57
  const COMMON = {
58
58
  name: 'infinitecampus',
59
- version: '3.1.8', // x-release-please-version
59
+ version: '3.2.0', // x-release-please-version
60
60
  };
61
61
  // Shared with the healthcheck so it can report the SAME state the tools see,
62
62
  // including on the unconfigured path where there are no tools at all.
@@ -8,7 +8,7 @@ const argsSchema = z.object({
8
8
  export function registerAssessmentTools(server, client) {
9
9
  server.registerTool('ic_list_assessments', {
10
10
  description: "List a student's standardized test scores (state, national, district tests). Auto-resolves calendarID from each of the student's enrollments and returns one entry per enrollment. The shape of individual test records varies by district and test type — fields are passed through unchanged.",
11
- annotations: { readOnlyHint: true },
11
+ annotations: { readOnlyHint: true, openWorldHint: true },
12
12
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
13
13
  }, async (rawArgs) => {
14
14
  const args = argsSchema.parse(rawArgs);
@@ -11,7 +11,7 @@ const argsSchema = z.object({
11
11
  export function registerAssignmentTools(server, client) {
12
12
  server.registerTool('ic_list_assignments', {
13
13
  description: "List a student's assignments. The IC endpoint returns the full term history (~hundreds of items); date and missing filters are applied client-side. For a single course, pass courseId (the sectionID from ic_get_schedule).",
14
- annotations: { readOnlyHint: true },
14
+ annotations: { readOnlyHint: true, openWorldHint: true },
15
15
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
16
16
  }, async (rawArgs) => {
17
17
  const args = argsSchema.parse(rawArgs);
@@ -41,7 +41,7 @@ function processList(list, since, until) {
41
41
  export function registerAttendanceTools(server, client) {
42
42
  server.registerTool('ic_list_attendance', {
43
43
  description: "List a student's absences and tardies (per-course summary grouped by term). Auto-resolves enrollmentID from the student record.",
44
- annotations: { readOnlyHint: true },
44
+ annotations: { readOnlyHint: true, openWorldHint: true },
45
45
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
46
46
  }, async (rawArgs) => {
47
47
  const args = argsSchema.parse(rawArgs);
@@ -42,7 +42,7 @@ function trimEvent(e) {
42
42
  export function registerAttendanceEventsTools(server, client) {
43
43
  server.registerTool('ic_list_attendance_events', {
44
44
  description: "List individual attendance events (absences, tardies, early releases) for a student. Each event has a code, description, excuse reason, and optional human-readable comments. Auto-resolves enrollmentID from the student record. Use since/until to filter by date and excusedOnly to show only excused events.",
45
- annotations: { readOnlyHint: true },
45
+ annotations: { readOnlyHint: true, openWorldHint: true },
46
46
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
47
47
  }, async (rawArgs) => {
48
48
  const args = argsSchema.parse(rawArgs);
@@ -10,7 +10,7 @@ const argsSchema = z.object({
10
10
  export function registerBehaviorTools(server, client) {
11
11
  server.registerTool('ic_list_behavior', {
12
12
  description: "List a student's behavior events / referrals. Returns FeatureDisabled if the district has the behavior module turned off (detected via displayOptions or a 404 backstop).",
13
- annotations: { readOnlyHint: true },
13
+ annotations: { readOnlyHint: true, openWorldHint: true },
14
14
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
15
15
  }, async (rawArgs) => {
16
16
  const args = argsSchema.parse(rawArgs);
@@ -1,6 +1,84 @@
1
1
  import { viewArg, viewResponse } from '../view.js';
2
2
  import { z } from 'zod';
3
- import { findStudent, studentNotFound, toArray } from './_shared.js';
3
+ import { PortalUnreachableError } from '../client.js';
4
+ import { findStudent, is404, studentNotFound, toArray } from './_shared.js';
5
+ /** The portal answered, but not with this resource: worth trying another route. */
6
+ function isRouteFailure(e) {
7
+ return e instanceof PortalUnreachableError || is404(e);
8
+ }
9
+ /**
10
+ * Districts (per client) that last answered on calendar/day rather than
11
+ * instructionalDay. Asking the broken route first on every call would cost one
12
+ * guaranteed-failing request per enrollment. It is a preference, not a
13
+ * verdict: if calendar/day stops answering, instructionalDay is tried again.
14
+ */
15
+ const preferDayRoute = new WeakMap();
16
+ async function fetchDayRoute(client, district, calendarID, route) {
17
+ if (route === 'instructionalDay') {
18
+ return toArray(await client.request(district, `/campus/resources/calendar/instructionalDay?calendarID=${calendarID}`));
19
+ }
20
+ const all = toArray(await client.request(district, `/campus/resources/calendar/day?calendarID=${calendarID}`));
21
+ return all.filter((d) => d.isInstructionalDay);
22
+ }
23
+ /**
24
+ * The calendar's instructional days, or null when no route to them answers.
25
+ *
26
+ * Some districts now 500 on calendar/instructionalDay: Campus matches it to
27
+ * calendar/{calendarID} and reads "instructionalDay" as the ID (#253).
28
+ * calendar/day returns the same days plus the non-instructional ones, flagged
29
+ * by isInstructionalDay. Session and auth errors are not route failures and
30
+ * propagate, so a dead session never reads as "days unknown".
31
+ */
32
+ async function fetchInstructionalDays(client, district, calendarID) {
33
+ let preferred = preferDayRoute.get(client);
34
+ if (!preferred)
35
+ preferDayRoute.set(client, (preferred = new Set()));
36
+ const routes = preferred.has(district) ? ['day', 'instructionalDay'] : ['instructionalDay', 'day'];
37
+ for (const route of routes) {
38
+ try {
39
+ const days = await fetchDayRoute(client, district, calendarID, route);
40
+ if (route === 'day')
41
+ preferred.add(district);
42
+ else
43
+ preferred.delete(district);
44
+ return days;
45
+ }
46
+ catch (e) {
47
+ if (!isRouteFailure(e))
48
+ throw e;
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+ /**
54
+ * Event labels by calendarID → date, from portal/dayEvent/byEnrollment. Neither
55
+ * day route carries `comments` any more, so this is where "Holiday" or
56
+ * "Teacher Work Day" lives now. Labels are a nicety: a route failure costs only
57
+ * the labels (an empty map), but a session error still propagates.
58
+ */
59
+ async function fetchDayEvents(client, district, personID) {
60
+ let groups;
61
+ try {
62
+ groups = toArray(await client.request(district, `/campus/resources/portal/dayEvent/byEnrollment?personID=${encodeURIComponent(personID)}`));
63
+ }
64
+ catch (e) {
65
+ if (!isRouteFailure(e))
66
+ throw e;
67
+ groups = [];
68
+ }
69
+ const byCalendar = new Map();
70
+ for (const ev of groups.flatMap((g) => toArray(g.events))) {
71
+ let byDate = byCalendar.get(ev.calendarID);
72
+ if (!byDate)
73
+ byCalendar.set(ev.calendarID, (byDate = new Map()));
74
+ byDate.set(ev.date, [...(byDate.get(ev.date) ?? []), ev]);
75
+ }
76
+ return byCalendar;
77
+ }
78
+ /** Distinct, non-empty labels joined the way IC's old `comments` read. */
79
+ function joinLabels(labels) {
80
+ return [...new Set(labels.filter((l) => !!l))].join('; ');
81
+ }
4
82
  const argsSchema = z.object({
5
83
  district: z.string(),
6
84
  studentId: z.string().describe('Student personID from ic_list_students'),
@@ -9,8 +87,8 @@ const argsSchema = z.object({
9
87
  });
10
88
  export function registerCalendarTools(server, client) {
11
89
  server.registerTool('ic_list_school_days', {
12
- description: "List a student's school days (instructional calendar) grouped by term. Returns one entry per enrollment, with term boundaries (Q1-Q4 start/end dates) and the school days inside each term — including comments like 'Teacher Workday' or 'Spring Break'. Use since/until to narrow the range.",
13
- annotations: { readOnlyHint: true },
90
+ description: "List a student's school days (instructional calendar) grouped by term. Returns one entry per enrollment, with term boundaries (Q1-Q4 start/end dates) and the school days inside each term — a day carries comments when the calendar labels it (e.g. 'Early Release Day'). Each enrollment also lists its labelled daysOff (e.g. 'Holiday', 'Teacher Work Day', 'Spring Break'), including breaks that fall between terms. Use since/until to narrow the range. An enrollment whose day list the district won't serve comes back with warning 'SchoolDaysUnavailable' (plus campusVersion when known), its terms and days off, and no school days.",
91
+ annotations: { readOnlyHint: true, openWorldHint: true },
14
92
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
15
93
  }, async (rawArgs) => {
16
94
  const args = argsSchema.parse(rawArgs);
@@ -19,22 +97,27 @@ export function registerCalendarTools(server, client) {
19
97
  if (!student)
20
98
  return studentNotFound(args.studentId);
21
99
  const result = [];
100
+ const enrollments = student.enrollments ?? [];
101
+ // One call covers every enrollment; skip it when there are none.
102
+ const events = enrollments.length > 0
103
+ ? await fetchDayEvents(client, args.district, args.studentId)
104
+ : new Map();
22
105
  // 2. For each enrollment, fetch terms + instructional days
23
- for (const enr of student.enrollments ?? []) {
24
- const [termsRaw, daysRaw] = await Promise.all([
106
+ for (const enr of enrollments) {
107
+ const [termsRaw, days] = await Promise.all([
25
108
  client.request(args.district, `/campus/resources/term?structureID=${enr.structureID}`),
26
- client.request(args.district, `/campus/resources/calendar/instructionalDay?calendarID=${enr.calendarID}`),
109
+ fetchInstructionalDays(client, args.district, enr.calendarID),
27
110
  ]);
28
111
  const terms = toArray(termsRaw);
29
- const days = toArray(daysRaw);
30
112
  // 3. Filter days by since/until range
31
- const filteredDays = days.filter((d) => {
32
- if (args.since && d.date < args.since)
33
- return false;
34
- if (args.until && d.date > args.until)
35
- return false;
36
- return true;
37
- });
113
+ const inRange = (date) => !(args.since && date < args.since) && !(args.until && date > args.until);
114
+ const filteredDays = (days ?? []).filter((d) => inRange(d.date));
115
+ const calendarEvents = events.get(enr.calendarID) ?? new Map();
116
+ // Labelled dates IC itself marks as out of instruction, oldest first.
117
+ const daysOff = [...calendarEvents.entries()]
118
+ .filter(([date, evs]) => inRange(date) && evs.some((e) => e.instruction === false))
119
+ .map(([date, evs]) => ({ date, comments: joinLabels(evs.map((e) => e.name)) }))
120
+ .sort((a, b) => a.date.localeCompare(b.date));
38
121
  // 4. Group days into terms (only terms in this structureID; sorted by seq)
39
122
  const enrollmentTerms = terms
40
123
  .filter((t) => t.structureID === enr.structureID)
@@ -49,19 +132,27 @@ export function registerCalendarTools(server, client) {
49
132
  .filter((d) => d.date >= t.startDate && d.date <= t.endDate)
50
133
  .map((d) => {
51
134
  const out = { date: d.date, requiresAttendance: d.requiresAttendance };
52
- if (d.comments)
53
- out.comments = d.comments;
135
+ const comments = joinLabels([d.comments, ...(calendarEvents.get(d.date) ?? []).map((e) => e.name)]);
136
+ if (comments)
137
+ out.comments = comments;
54
138
  return out;
55
139
  }),
56
140
  }))
57
- // Drop empty terms (term entirely outside the since/until range)
58
- .filter((t) => t.days.length > 0 || (!args.since && !args.until));
141
+ // Drop terms entirely outside the since/until range. With no days to
142
+ // go on, judge a term by whether its own dates overlap the range.
143
+ .filter((t) => days === null
144
+ ? !(args.since && t.endDate < args.since) && !(args.until && t.startDate > args.until)
145
+ : t.days.length > 0 || (!args.since && !args.until));
146
+ const campusVersion = days === null ? await client.campusVersion(args.district) : null;
59
147
  result.push({
60
148
  enrollmentID: enr.enrollmentID,
61
149
  calendarID: enr.calendarID,
62
150
  structureID: enr.structureID,
63
151
  calendarName: enr.calendarName,
152
+ ...(days === null ? { warning: 'SchoolDaysUnavailable' } : {}),
153
+ ...(campusVersion ? { campusVersion } : {}),
64
154
  terms: trimmedTerms,
155
+ ...(daysOff.length > 0 ? { daysOff } : {}),
65
156
  });
66
157
  }
67
158
  return viewResponse(rawArgs.view, result);
@@ -6,7 +6,7 @@ export function registerDistrictTools(server, client) {
6
6
  inputSchema: z.object({
7
7
  view: viewArg(),
8
8
  }),
9
- annotations: { readOnlyHint: true },
9
+ annotations: { readOnlyHint: true, openWorldHint: true },
10
10
  }, async ({ view }) => {
11
11
  await client.ensureDiscovery();
12
12
  const data = client.listDistricts();
@@ -15,7 +15,7 @@ const downloadArgs = z.object({
15
15
  export function registerDocumentTools(server, client) {
16
16
  server.registerTool('ic_list_documents', {
17
17
  description: "List a student's available documents (report cards, transcripts, schedules). Returns metadata only — use ic_download_document to fetch the file. Returns FeatureDisabled if the district has the module turned off.",
18
- annotations: { readOnlyHint: true },
18
+ annotations: { readOnlyHint: true, openWorldHint: true },
19
19
  inputSchema: z.object({ ...listArgs.shape, view: viewArg() }),
20
20
  }, async (rawArgs) => {
21
21
  const args = listArgs.parse(rawArgs);
@@ -51,7 +51,7 @@ export function registerDocumentTools(server, client) {
51
51
  });
52
52
  server.registerTool('ic_download_document', {
53
53
  description: "Download a student's document (PDF) to disk, inside the download directory (IC_DOWNLOAD_DIR, default ~/Downloads). documentId is the url field returned by ic_list_documents. Will not overwrite an existing file unless overwrite is true. Returns FeatureDisabled if the district has the module turned off.",
54
- annotations: { destructiveHint: true },
54
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
55
55
  inputSchema: downloadArgs,
56
56
  }, async (rawArgs) => {
57
57
  const args = downloadArgs.parse(rawArgs);
@@ -7,8 +7,8 @@ const argsSchema = z.object({
7
7
  });
8
8
  export function registerFeaturesTools(server, client) {
9
9
  server.registerTool('ic_get_features', {
10
- description: "List the district's displayOptions feature-flag allow-list for each of a student's enrollments. Each enrollment's `features` object is a map of ~90 flag names (attendance, behavior, assessment, documents, grades, schedule, etc.) to booleans. A `false` value means the district has that feature disabled for this enrollment; `true` or missing means it's available. Used internally by other tools to short-circuit disabled features, but exposed here so the LLM can answer capability questions directly.",
11
- annotations: { readOnlyHint: true },
10
+ description: "List the district's displayOptions feature-flag allow-list for each of a student's enrollments. Each enrollment's `features` object is a map of ~90 flag names (attendance, behavior, assessment, documents, grades, schedule, etc.) to booleans. A `false` value means the district has that feature disabled for this enrollment; `true` or missing means it's available. An enrollment whose flags could not be fetched carries `error` instead of `features`. Used internally by other tools to short-circuit disabled features, but exposed here so the LLM can answer capability questions directly.",
11
+ annotations: { readOnlyHint: true, openWorldHint: true },
12
12
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
13
13
  }, async (rawArgs) => {
14
14
  const args = argsSchema.parse(rawArgs);
@@ -17,13 +17,18 @@ export function registerFeaturesTools(server, client) {
17
17
  return studentNotFound(args.studentId);
18
18
  const result = [];
19
19
  for (const enr of student.enrollments ?? []) {
20
- const features = await client.getFeatures(args.district, enr.structureID, args.studentId);
21
- result.push({
22
- enrollmentID: enr.enrollmentID,
23
- structureID: enr.structureID,
24
- schoolName: enr.schoolName,
25
- features,
26
- });
20
+ const entry = { enrollmentID: enr.enrollmentID, structureID: enr.structureID, schoolName: enr.schoolName };
21
+ // Per-enrollment, not per-call: a prior-year or cross-site enrollment
22
+ // whose structureID 404s/403s must not throw away the flags for the
23
+ // enrollments that did answer (checkFeatureDisabled treats the same
24
+ // failure as non-fatal too).
25
+ try {
26
+ const features = await client.getFeatures(args.district, enr.structureID, args.studentId);
27
+ result.push({ ...entry, features });
28
+ }
29
+ catch (e) {
30
+ result.push({ ...entry, error: e instanceof Error ? e.message : String(e) });
31
+ }
27
32
  }
28
33
  return viewResponse(rawArgs.view, result);
29
34
  });
@@ -8,7 +8,7 @@ const argsSchema = z.object({
8
8
  export function registerFeeTools(server, client) {
9
9
  server.registerTool('ic_list_fees', {
10
10
  description: "List a student's fee assignments (charges owed) and running balance/surplus. Combines two endpoints: fee assignments and totalSurplus. Returns FeatureDisabled only if both endpoints 404; if only one works, returns that side with warning: 'PartialSuccess' and an issues[] explaining which endpoint failed.",
11
- annotations: { readOnlyHint: true },
11
+ annotations: { readOnlyHint: true, openWorldHint: true },
12
12
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
13
13
  }, async (rawArgs) => {
14
14
  const args = argsSchema.parse(rawArgs);
@@ -11,7 +11,7 @@ const EMPTY_FOOD = { balance: null, transactions: [] };
11
11
  export function registerFoodServiceTools(server, client) {
12
12
  server.registerTool('ic_list_food_service', {
13
13
  description: "List a student's lunch balance and recent food-service transactions. Returns FeatureDisabled if the district has the module turned off (detected via displayOptions or a 404 backstop).",
14
- annotations: { readOnlyHint: true },
14
+ annotations: { readOnlyHint: true, openWorldHint: true },
15
15
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
16
16
  }, async (rawArgs) => {
17
17
  const args = argsSchema.parse(rawArgs);
@@ -8,7 +8,7 @@ const argsSchema = z.object({
8
8
  export function registerGradeTools(server, client) {
9
9
  server.registerTool('ic_list_grades', {
10
10
  description: "List a student's term grades and in-progress course grades.",
11
- annotations: { readOnlyHint: true },
11
+ annotations: { readOnlyHint: true, openWorldHint: true },
12
12
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
13
13
  }, async (rawArgs) => {
14
14
  const args = argsSchema.parse(rawArgs);
@@ -28,6 +28,9 @@ export function registerHealthcheckTools(server, state) {
28
28
  base_url: state.account.baseUrl,
29
29
  configured_district: state.account.district,
30
30
  auth_source: state.source ?? 'unknown',
31
+ // Read off the login page, so it needs no session and is reported
32
+ // even when discovery cannot run. Diagnostic only (#253).
33
+ campus_version: await state.client.campusVersion(state.account.name),
31
34
  };
32
35
  try {
33
36
  // Discovery is what knows about LINKED districts, and it needs a live
@@ -35,7 +38,11 @@ export function registerHealthcheckTools(server, state) {
35
38
  // is known and let the probe below decide.
36
39
  await state.client.ensureDiscovery();
37
40
  const districts = state.client.listDistricts();
38
- detail.districts = districts.map((d) => ({ name: d.name, linked: d.linked }));
41
+ detail.districts = await Promise.all(districts.map(async (d) => ({
42
+ name: d.name,
43
+ linked: d.linked,
44
+ campus_version: await state.client.campusVersion(d.name),
45
+ })));
39
46
  const linked = districts.filter((d) => d.linked).map((d) => d.name);
40
47
  detail.configured_district_is_linked = districts.some((d) => d.name === state.account.district && d.linked);
41
48
  if (linked.length > 0)