From 5b19648a62a3cf1348a5dd92d95464e9a2faefd5 Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:02:47 -0500 Subject: [PATCH 1/3] Add current course coverage, official CS schedules, and public Prince search --- app/COURSE_CONNECTOR.md | 44 ++++++++++++- app/scripts/smoke-current-course-data.ts | 24 +++++++ app/src/server/course-consent.ts | 2 +- app/src/server/course-mcp.ts | 43 ++++++++++--- app/src/server/course-public-data.ts | 81 ++++++++++++++++++++++++ app/src/server/pi.ts | 1 + app/tests/course-mcp.test.ts | 35 +++++++++- app/tests/course-public-data.test.ts | 50 +++++++++++++++ 8 files changed, 267 insertions(+), 13 deletions(-) create mode 100644 app/scripts/smoke-current-course-data.ts create mode 100644 app/src/server/course-public-data.ts create mode 100644 app/tests/course-public-data.test.ts diff --git a/app/COURSE_CONNECTOR.md b/app/COURSE_CONNECTOR.md index 0f8eeaf..b1b63be 100644 --- a/app/COURSE_CONNECTOR.md +++ b/app/COURSE_CONNECTOR.md @@ -43,7 +43,9 @@ Overlapping upstream tool catalogs cannot change a tool's designated source. | PrincetonCourses | Course evaluations, review summaries, instructor information | None | | TigerPath | Degree requirement trees, aggregate planning statistics, own four-year plan | Add or remove a course in a semester | -There are 24 allowlisted read tools and 5 optional write tools. Whole-schedule +The baseline engine provides 24 allowlisted read tools and 5 optional write tools. +With the published-data engine extension and three local public/coverage tools, +the connector offers up to 30 read tools. Whole-schedule deletion, seat alerts, TigerHub registration, Canvas, calendar access, and PI workspaces are excluded. A saved plan is not a transcript or actual enrollment. @@ -122,3 +124,43 @@ require the assistant to report that gap instead of substituting an older term. Production CAS-to-Claude authorization, real personal-plan ownership enforcement, and saved-plan changes still require an authorized staging check. No production deployment or real plan mutation is part of these local checks. + +## Published data and coverage + +The connector now includes three local read tools independently of engine catalog +availability. `get_course_data_status(term)` checks the imported catalog, the live +published-term source and the CS department fallback. It does not read a student's +plans. `get_cs_course_schedule(term)` reads the official department page for that +exact semester, and rejects a page that silently selects a different term. +`search_prince_articles(query, page)` searches the Daily Princetonian public site, +returning bounded excerpts with source identity, article dates and canonical URLs. +This is not Clio and does not access its database, newsletters, retrieval service, +credentials or chats. Publication date, fetch time and unknown ingestion history +are separate fields. Public fetches send neither NetID nor session credentials. + +A companion engine change exposes `list_published_terms`, +`search_published_courses` and `get_published_course` on the junction MCP scope. +These read Princeton's authenticated OIT course API directly and do not require a +completed database import. Deploy that change and configure the engine's existing +`CONSUMER_KEY`/`CONSUMER_SECRET` (preferred) or `API_ACCESS_TOKEN`. PI does not receive +those credentials. Without that deployment/configuration, only the CS fallback +and public Prince search are independently available. Imported search results and +saved-plan validation may still be stale. Do not claim the database was refreshed. + +Successful public reads are cached for at most five minutes per process/isolate, +with fetch timestamps and bounded cache sizes. Errors are not empty catalogs. +A working source is not proof it covers every department or the requested term. +The CS page provides course-level meetings, not every precept or lab; missing or +ambiguous times stay unknown. Prince reporting cannot establish degree policy or +current section availability. Ratings remain historical and a saved plan is not +a transcript. No automatic import, production mutation or registration is added. + +Local live checks on November 26, 2026 retrieved Spring 2027 COS 217 with +`MW 10:40 - 11:30` and dated Prince search results. The existing production engine +still returned only seven terms through Fall 2026 and no Spring 2027 COS results. +The authenticated engine reads have fixture tests, but require a deployed smoke +check with valid OIT credentials before university-wide coverage can be claimed. + +Reproduce the read-only live public-source check from `app` with +`npx tsx scripts/smoke-current-course-data.ts 1274`. It uses the real MCP transport +with a local test identity, without production sessions or saved-plan writes. diff --git a/app/scripts/smoke-current-course-data.ts b/app/scripts/smoke-current-course-data.ts new file mode 100644 index 0000000..4d33736 --- /dev/null +++ b/app/scripts/smoke-current-course-data.ts @@ -0,0 +1,24 @@ +/** Read-only live source check through the actual connector MCP transport. + * Run from app: npx tsx scripts/smoke-current-course-data.ts 1274 + * Does not use production identities, credentials, plans or the production MCP. + */ +import assert from "node:assert/strict"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { COURSE_READ, handleCourseMcp } from "../src/server/course-mcp.ts"; +const term = Number(process.argv[2]); +assert.ok(Number.isInteger(term) && term >= 1000 && term <= 1999 && [2, 4].includes(term % 10), "Pass an explicit Fall/Spring term, e.g. 1274"); +const client = new Client({ name: "pi-live-public-smoke", version: "1" }); +const upstream = { list: async () => [], call: async () => { throw new Error("No engine in this public-source smoke test"); } }; +try { + await client.connect(new StreamableHTTPClientTransport(new URL("https://local.test/mcp"), { + fetch: (url, init) => handleCourseMcp(new Request(url, init), { netid: "teststudent", scope: [COURSE_READ] }, upstream), + })); + for (const [name, args] of [["get_cs_course_schedule", { term }], ["search_prince_articles", { query: "course offerings" }]] as const) { + const result = await client.callTool({ name, arguments: args }); + assert.notEqual(result.isError, true, JSON.stringify(result)); + const text = result.content?.find(c => c.type === "text"); + assert.ok(text?.type === "text"); + const data = JSON.parse(text.text); + console.log(JSON.stringify({ tool: name, status: "PASS", source: data.source, sourceUrl: data.sourceUrl, fetchedAt: data.fetchedAt, coverage: data.coverage, resultCount: data.courses?.length ?? data.articles?.length, sample: data.courses?.find((c: any) => c.code === "COS217") ?? data.articles?.[0] })); + } +} finally { await client.close(); } diff --git a/app/src/server/course-consent.ts b/app/src/server/course-consent.ts index f39157a..6fdb5e7 100644 --- a/app/src/server/course-consent.ts +++ b/app/src/server/course-consent.ts @@ -29,7 +29,7 @@ export function consentPage(details: ConsentDescription, handle: string, netid: ${details.clientDomain ? `Client domain verified as ${escapeHtml(details.clientDomain)}.` : "The application name is supplied by the client. Check the destination before connecting."}${details.redirectIsLoopback ? " This destination is a local app. Another local process could be listening there." : ""}
- +

Your conversation stays in your assistant. This connection does not import memories, PI chats, Canvas, or calendars.

Access can renew for up to 30 days. Disconnect any time at PI / My apps / Course connector. diff --git a/app/src/server/course-mcp.ts b/app/src/server/course-mcp.ts index ff043fd..8f196ca 100644 --- a/app/src/server/course-mcp.ts +++ b/app/src/server/course-mcp.ts @@ -1,3 +1,4 @@ +import { PUBLIC_COURSE_TOOLS, publicCourseData } from "./course-public-data"; import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { Server, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server"; @@ -11,6 +12,7 @@ type Source = "junction" | "princetoncourses" | "path"; const READ_TOOLS: Record = { junction: [ "search_courses", "get_course_details", "get_course_sections", "list_departments", + "list_published_terms", "search_published_courses", "get_published_course", "discover_courses", "list_terms", "compare_courses", "get_enrollment_stats", "get_user_schedules", "get_schedule_details", "verify_schedule", ], @@ -34,7 +36,8 @@ const policy = new Map(sources.flatM ])); export const COURSE_INSTRUCTIONS = `Help Princeton students select courses using current TigerApps data. -Start with list_terms and use an explicit term throughout. Tool descriptions may contain stale labels such as 'current' or 'upcoming'; rely on returned catalog data. If the requested term is absent, check it explicitly and report missing coverage when no results are available. Never substitute an older offering or treat missing data as proof that a course will not be offered. Ask for the student's degree (AB or BSE), major, graduation year, completed courses, interests, and time constraints when unknown. Use saved plans only with their permission. A TigerPath plan is not an official transcript or proof of completed prerequisites. +Start with get_course_data_status for the requested term. Prefer list_published_terms, search_published_courses and get_published_course for official current offerings, instructors, sections and prerequisite text. These live engine tools may require a backend deployment/configuration before they are available. list_terms describes the imported TigerJunction database only, not everything Princeton has published. Use an explicit term throughout. Tool descriptions may contain stale labels such as 'current' or 'upcoming'; rely on returned catalog data. If the requested term is absent, check it explicitly and report missing coverage when no results are available. Never substitute an older offering or treat missing data as proof that a course will not be offered. Ask for the student's degree (AB or BSE), major, graduation year, completed courses, interests, and time constraints when unknown. Use saved plans only with their permission. A TigerPath plan is not an official transcript or proof of completed prerequisites. +If official engine reads are unavailable, get_cs_course_schedule can verify COS course-level times directly from the department. Its coverage excludes full precept/lab combinations and other departments. Do not substitute this fallback for a complete schedule. search_prince_articles adds dated campus reporting from public Prince search, not Clio; reporting is context, not authoritative requirements or section times. Keep article publication dates, fetch times, corpus coverage and unknown ingestion history separate. Read course details, sections, degree requirements, and reviews before recommending a shortlist. Distinguish catalog facts, historical student opinions, and your own assessment. Include course links or identifiers and explain workload, prerequisite uncertainty, and tradeoffs. verify_schedule is an upstream screening check, not proof of a globally feasible selection of lecture, precept, and lab sections. Inspect the actual section choices and times. Never claim prerequisite eligibility, degree completion, available seats, or registration based solely on a plan or this check. Propose alternatives before changing anything. Only call plan-writing tools after the student explicitly asks you to save or edit the named plan. Saving in TigerJunction or TigerPath does not enroll the student in a course. This connector cannot access TigerHub registration, Canvas, calendars, PI chats, or the assistant's private memory. @@ -96,14 +99,19 @@ export function courseUpstream(env: EngineEnv, netid: string): CourseUpstream { }; } -export function createCourseServer(identity: CourseIdentity, upstream: CourseUpstream): Server { +const livePublicData = publicCourseData(); +const statusTool = { name: "get_course_data_status", description: "Check imported and official live course coverage for a requested term, plus the public CS schedule fallback. Does not read personal plans. Unknown import/ingestion timestamps remain unknown. Call this first when planning a semester.", inputSchema: { type: "object" as const, properties: { term: { type: "integer", minimum: 1000, maximum: 1999 } }, required: ["term"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true } }; +const localTools = [...PUBLIC_COURSE_TOOLS, statusTool]; + +export function createCourseServer(identity: CourseIdentity, upstream: CourseUpstream, publicData = livePublicData): Server { if (!/^[a-z][a-z0-9]{0,63}$/.test(identity.netid) || !identity.scope.includes(COURSE_READ)) throw new Error("Course access requires a verified identity and read permission."); const canWrite = identity.scope.includes(PLAN_WRITE); const server = new Server({ name: "Princeton Courses by TigerApps", version: "1.0.0" }, { capabilities: { tools: {}, prompts: {} }, instructions: COURSE_INSTRUCTIONS, }); server.setRequestHandler("tools/list", async () => { - // Fail explicitly rather than making an outage look like a complete catalog. + // Keep independent public sources usable during an engine outage. The + // status tool reports source availability and coverage explicitly. const catalogs = await Promise.allSettled(sources.map(async (source) => { let tools: Tool[]; try { tools = await upstream.list(source); } @@ -121,16 +129,14 @@ export function createCourseServer(identity: CourseIdentity, upstream: CourseUps }); })); // Let every connection finish its cleanup even if one source fails early. - return { tools: catalogs.flatMap((result) => { - if (result.status === "rejected") throw result.reason; - return result.value; - }) }; + return { tools: [...localTools, ...catalogs.flatMap((result) => result.status === "fulfilled" ? result.value : [])] }; }); server.setRequestHandler("tools/call", async ({ params }) => { const rule = policy.get(params.name); const fail = (text: string) => ({ isError: true, content: [{ type: "text" as const, text }] }); - if (!identity.scope.includes(COURSE_READ) || !rule) return fail("This tool is not available through this connector."); - if (rule.write && !canWrite) return fail("Plan editing is disabled. Reconnect and explicitly allow saved-plan changes first."); + const local = localTools.some(t => t.name === params.name); + if (!identity.scope.includes(COURSE_READ) || (!rule && !local)) return fail("This tool is not available through this connector."); + if (rule?.write && !canWrite) return fail("Plan editing is disabled. Reconnect and explicitly allow saved-plan changes first."); const args = params.arguments ?? {}; // Instructor NetIDs are public search keys. No other tool accepts a caller- // supplied identity; personal records are scoped by our verified header. @@ -140,6 +146,25 @@ export function createCourseServer(identity: CourseIdentity, upstream: CourseUps return fail("User identity comes from Princeton sign-in, not tool arguments."); } } + if (local) { + try { + let data: unknown; + if (params.name === "get_course_data_status") { + const term = args.term; + if (typeof term !== "number" || !Number.isInteger(term) || term < 1000 || term > 1999 || ![2, 4].includes(term % 10)) return fail("Provide an explicit four-digit Fall or Spring term."); + const checkedAt = new Date().toISOString(); + const checks = await Promise.allSettled([ + upstream.call("junction", "list_terms", {}), + upstream.call("junction", "list_published_terms", {}), + publicData.csSchedule(term), + ]); + const names = ["tigerjunction_imported_catalog", "princeton_published_terms", "princeton_cs_schedule"]; + data = { term, checkedAt, latestSuccessfulDatabaseImport: null, sources: checks.map((r, i) => ({ source: names[i], status: r.status === "fulfilled" && !(r.value as { isError?: boolean }).isError ? "available" : "unavailable", ...(r.status === "fulfilled" ? { result: r.value } : {}) })), warning: "Available means the source answered, not that it covers this term or all departments. Compare returned terms and coverage. Historical ratings and saved plans do not verify current offerings. No personal records were queried." }; + } else data = await publicData.call(params.name, args); + return { content: [{ type: "text" as const, text: JSON.stringify(data) }] }; + } catch { return fail("The public source is unavailable or returned an unexpected format, or the arguments are invalid. Coverage is unknown, not an empty catalog. Try another source and disclose the gap."); } + } + if (!rule) return fail("Unknown tool."); try { return await upstream.call(rule.source, params.name, args); } catch { diff --git a/app/src/server/course-public-data.ts b/app/src/server/course-public-data.ts new file mode 100644 index 0000000..b2b7a58 --- /dev/null +++ b/app/src/server/course-public-data.ts @@ -0,0 +1,81 @@ +import { z } from "zod"; + +const CS = "https://www.cs.princeton.edu/courses/schedule"; +const PRINCE = "https://www.dailyprincetonian.com"; +const term = z.number().int().min(1000).max(1999).refine(n => [2, 4].includes(n % 10)); +const definitions = { + get_cs_course_schedule: { description: "Read the official CS department schedule for an explicit term, directly from Princeton. Includes published course-level times and instructors, not a complete precept/lab schedule. Independent of TigerJunction's database.", schema: z.object({ term }) }, + search_prince_articles: { description: "Search the Daily Princetonian public website for recent or historical campus reporting. Returns dated, linked article excerpts. This is public Prince search, not Clio or an exhaustive archive. Reporting is not authoritative course scheduling or degree policy.", schema: z.object({ query: z.string().trim().min(2).max(150), page: z.number().int().min(1).max(50).default(1) }) }, +}; +export const PUBLIC_COURSE_TOOLS = Object.entries(definitions).map(([name, d]) => ({ name, description: d.description, inputSchema: z.toJSONSchema(d.schema) as { type: "object"; [key: string]: unknown }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true } })); +export function publicCourseData(fetcher: typeof fetch = fetch) { + const cache = new Map(); + async function read(url: string) { + const hit = cache.get(url); + if (hit && hit.expires > Date.now()) return hit; + const response = await fetcher(url, { redirect: "manual", signal: AbortSignal.timeout(12_000), headers: { "User-Agent": "PI-TigerApps-CourseConnector/1.0", accept: "text/html, application/json" } }); + if (!response.ok || !response.body) throw new Error("Source unavailable"); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + while (true) { + const part = await reader.read(); + if (part.done) break; + size += part.value.byteLength; + if (size > 2_000_000) throw new Error("Source too large"); + chunks.push(part.value); + } + } finally { await reader.cancel(); } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + const value = { text: new TextDecoder().decode(bytes), fetchedAt: new Date().toISOString(), expires: Date.now() + 300_000 }; + if (cache.size >= 32) cache.delete(cache.keys().next().value!); + cache.set(url, value); + return value; + } + async function csSchedule(termCode: number) { + const semester = `${termCode % 10 === 2 ? "fall" : "spring"}${String(Math.floor(termCode / 10) - (termCode % 10 === 2 ? 1 : 0)).slice(-2)}`; + const sourceUrl = `${CS}?semester=${semester}`; + const page = await read(sourceUrl); + const options = [...page.text.matchAll(/]*)>([\s\S]*?)<\/option>/gi)]; + const selected = options.find(o => /\bselected(?:\s|=|$)/i.test(o[1])); + if (!selected || !new RegExp(`\\bvalue=["']${semester}["']`).test(selected[1])) throw new Error("Source selected another term"); + const table = page.text.match(/]*class="[^"]*course-schedule__table[^"]*"[^>]*>([\s\S]*?)<\/table>/)?.[1]; + if (!table) throw new Error("Schedule missing"); + const courses = [...table.matchAll(/]*>([\s\S]*?)<\/tr>/g)].flatMap(row => { + const cell = (field: string) => row[1].match(new RegExp(`]*class="[^"]*course-schedule__${field}[^"]*"[^>]*>([\\s\\S]*?)<\\/td>`))?.[1]; + const code = plain(cell("number") ?? ""); + if (!/^COS\s*\d{3}[A-Z]?$/i.test(code)) return []; + return [{ code, title: plain(cell("title") ?? ""), instructors: plain(cell("instructors") ?? "") || null, publishedMeeting: plain(cell("time") ?? "") || null }]; + }); + if (!courses.length) throw new Error("No parseable courses"); + return { source: "Princeton CS department", sourceUrl, fetchedAt: page.fetchedAt, cacheMaxAgeSeconds: 300, term: termCode, coverage: "COS_course_level_schedule_only", courses, warning: "Times are reproduced as published in America/New_York. Do not infer missing AM/PM, precepts, labs, seats or completed prerequisites. Use official course sections before validating a full schedule." }; + } + async function prince(query: string, pageNumber: number) { + const params = new URLSearchParams({ a: "1", s: query, ty: "article", o: "date", page: String(pageNumber), per_page: "10" }); + const sourceUrl = `${PRINCE}/search?${params}`; + const result = await read(`${PRINCE}/search.json?${params}`); + const parsed = JSON.parse(result.text); + if (!Array.isArray(parsed.items)) throw new Error("Invalid Prince response"); + const articles = parsed.items.filter((i: any) => i && typeof i.id === "string" && typeof i.slug === "string" && /^[a-z0-9-]+$/i.test(i.slug) && /^\d{4}-\d{2}-\d{2}/.test(i.published_at)).slice(0, 10).map((i: any) => ({ + source_type: "prince_public_article", source_id: i.id, title: plain(i.headline ?? ""), published_at: i.published_at, + url: `${PRINCE}/article/${i.published_at.slice(0, 4)}/${i.published_at.slice(5, 7)}/${i.slug}`, excerpt: plain(i.abstract ?? "").slice(0, 600), + })); + return { source: "Daily Princetonian public search (not Clio)", sourceUrl, fetchedAt: result.fetchedAt, cacheMaxAgeSeconds: 300, coverage: "search_page_only", query, page: pageNumber, articles, newest_published_at: articles.reduce((latest: string | null, a: { published_at: string }) => !latest || a.published_at > latest ? a.published_at : latest, null), latest_successful_ingestion: null, corpus_range: null, warning: "No local archive ingestion. Fetch time does not establish article revision freshness. Search coverage and publication timestamps come from the public site; results may be partial." }; + } + return { + csSchedule, + async call(name: string, args: Record) { + if (name === "get_cs_course_schedule") return csSchedule(definitions.get_cs_course_schedule.schema.parse(args).term); + if (name === "search_prince_articles") { const a = definitions.search_prince_articles.schema.parse(args); return prince(a.query, a.page); } + throw new Error("Unknown public tool"); + }, + }; +} +export function plain(html: string): string { + return String(html).replace(/]*>[\s\S]*?<\/script>|]*>[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ") + .replace(/&(amp|lt|gt|quot|apos|nbsp|ndash|mdash);/g, (_, name) => ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—" })[name as string] ?? " ") + .replace(/&#(x[\da-f]+|\d+);/gi, (_, code) => { const n = code[0].toLowerCase() === "x" ? parseInt(code.slice(1), 16) : Number(code); return n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : " "; }).replace(/\s+/g, " ").trim(); +} diff --git a/app/src/server/pi.ts b/app/src/server/pi.ts index 225940c..5d86c44 100644 --- a/app/src/server/pi.ts +++ b/app/src/server/pi.ts @@ -298,6 +298,7 @@ export class Pi extends Think { "- One of these per turn, and never write a menu of options out in prose — that's what offer_choices is for.", "", "Ground rules:", + "- For current or upcoming course selection, prefer list_published_terms, search_published_courses and get_published_course when available. These read Princeton directly. list_terms and search_courses reflect an imported database that may lag. Never silently substitute a historical term or claim missing imported data means a course is not offered.", "- Princeton term codes end in 2 for Fall and 4 for Spring (e.g. 1272 = Fall 2026). When unsure which term is current, call list_terms rather than guessing.", "- The interface renders schedule, course, seat-demand, trending and past-term tool results as visual cards automatically. After a tool call, add a short takeaway (conflicts, standouts, whether a seat is realistic, next step) — never re-list every row the card already shows.", "- When a tool errors or comes back empty, say plainly what didn't work and offer the closest thing you can still do. Never paste raw error text, URLs or status codes at the student.", diff --git a/app/tests/course-mcp.test.ts b/app/tests/course-mcp.test.ts index 14045c8..9be0f9a 100644 --- a/app/tests/course-mcp.test.ts +++ b/app/tests/course-mcp.test.ts @@ -37,7 +37,7 @@ test("real MCP handshake exposes only allowlisted read tools from their designat const client = await connected([COURSE_READ], upstream); t.after(() => client.close()); const catalog = await client.listTools(); - assert.deepEqual(catalog.tools.map(t => t.name).sort(), ["search_courses", "get_user_schedules", "get_course_evaluations", "get_instructor", "get_requirement_tree", "get_user_schedule"].sort()); + assert.deepEqual(catalog.tools.map(t => t.name).sort(), ["get_cs_course_schedule", "search_prince_articles", "get_course_data_status", "search_courses", "get_user_schedules", "get_course_evaluations", "get_instructor", "get_requirement_tree", "get_user_schedule"].sort()); assert.ok(catalog.tools.every(t => t.annotations?.readOnlyHint)); await client.callTool({ name: "get_course_evaluations", arguments: { code: "COS 217" } }); assert.deepEqual(calls, [{ source: "princetoncourses", name: "get_course_evaluations", args: { code: "COS 217" } }]); @@ -93,7 +93,9 @@ test("upstream failures omit credentials and uncertain writes are never retried" assert.match(JSON.stringify(result), /may have been saved/); assert.doesNotMatch(JSON.stringify(result), /secret-token|private.example/); assert.equal(attempts, 1); - await assert.rejects(client.listTools(), error => !String(error).includes("catalog-secret-token") && String(error).includes("catalog is unavailable")); + const tools = await client.listTools(); + assert.deepEqual(tools.tools.map(t => t.name).sort(), ["get_cs_course_schedule", "search_prince_articles", "get_course_data_status"].sort()); + assert.doesNotMatch(JSON.stringify(tools), /catalog-secret-token/); }); test("missing permission or malformed identity cannot create a course session", () => { @@ -121,3 +123,32 @@ test("consent CSP permits only the callback origin and cannot inject directives" assert.equal(policy(uri), "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"); } }); + +test("coverage reports partial sources without reading plans or confusing availability with term coverage", async (t) => { + const { WebStandardStreamableHTTPServerTransport } = await import("@modelcontextprotocol/server"); + const { publicCourseData } = await import("../src/server/course-public-data.ts"); + const calls: string[] = []; + const upstream: CourseUpstream = { + list: async () => [], + call: async (_source, name) => { + calls.push(name); + if (name === "list_published_terms") throw new Error("private credential detail"); + return { content: [{ type: "text", text: JSON.stringify({ terms: [{ term: 1272 }] }) }] }; + }, + }; + const publicData = publicCourseData((async () => { throw new Error("offline"); }) as typeof fetch); + const server = createCourseServer({ netid: "student1", scope: [COURSE_READ] }, upstream, publicData); + const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + await server.connect(transport); + const client = new Client({ name: "coverage-test", version: "1" }); + await client.connect(new StreamableHTTPClientTransport(new URL("https://pi.test/mcp"), { fetch: (url, init) => transport.handleRequest(new Request(url, init)) })); + t.after(async () => { await client.close(); await server.close(); }); + const result = await client.callTool({ name: "get_course_data_status", arguments: { term: 1274 } }); + const body = JSON.parse((result.content as any)[0].text); + assert.deepEqual(body.sources.map((s: any) => s.status), ["available", "unavailable", "unavailable"]); + assert.equal(body.latestSuccessfulDatabaseImport, null); + assert.deepEqual(calls.sort(), ["list_published_terms", "list_terms"]); + assert.doesNotMatch(JSON.stringify(result), /private credential detail/); + assert.match(body.warning, /not that it covers this term/); + assert.equal((await client.callTool({ name: "get_course_data_status", arguments: { term: 1274, netid: "student2" } })).isError, true); +}); diff --git a/app/tests/course-public-data.test.ts b/app/tests/course-public-data.test.ts new file mode 100644 index 0000000..f5580ca --- /dev/null +++ b/app/tests/course-public-data.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { publicCourseData } from "../src/server/course-public-data.ts"; + +const html = `
COS217Systems & CProfessorMW 10:40 - 11:30
`; + +test("CS fallback preserves actual term, meetings and limited coverage without sending identity", async () => { + let calls = 0; + const api = publicCourseData((async (url, init) => { + calls++; + assert.equal(String(url), "https://www.cs.princeton.edu/courses/schedule?semester=spring27"); + assert.equal(new Headers(init?.headers).has("authorization"), false); + assert.equal(new Headers(init?.headers).has("x-user-netid"), false); + assert.equal(new Headers(init?.headers).has("cookie"), false); + return new Response(html); + }) as typeof fetch); + const result = await api.csSchedule(1274); + assert.equal(result.courses[0].publishedMeeting, "MW 10:40 - 11:30"); + assert.equal(result.courses[0].title, "Systems & C"); + assert.equal(result.coverage, "COS_course_level_schedule_only"); + assert.ok(result.fetchedAt); + await api.csSchedule(1274); + assert.equal(calls, 1); +}); + +test("wrong selected term, markup changes, redirects and oversized responses fail closed", async () => { + for (const response of [new Response(html.replace('value="spring27"', 'value="fall26"')), new Response("challenge page"), new Response(null, { status: 302, headers: { location: "https://other.test" } }), new Response("x".repeat(2_000_001))]) { + const api = publicCourseData((async () => response) as typeof fetch); + await assert.rejects(api.csSchedule(1274)); + } +}); + +test("Prince returns public dated excerpts, skips malformed records and makes no ingestion claims", async () => { + const api = publicCourseData((async url => { + const u = new URL(String(url)); + assert.equal(u.hostname, "www.dailyprincetonian.com"); + assert.equal(u.searchParams.get("s"), "Spring 2027"); + return Response.json({ items: [false, { id: "1", slug: "course-changes", headline: "Changes", published_at: "2026-11-05 12:00:00", abstract: "

Summary

", content: "private unused full text" }, { id: "2", slug: "../../bad", published_at: "2026-11-05" }] }); + }) as typeof fetch); + const result = await api.call("search_prince_articles", { query: "Spring 2027" }) as any; + assert.equal(result.articles.length, 1); + assert.equal(result.articles[0].source_type, "prince_public_article"); + assert.equal(result.articles[0].url, "https://www.dailyprincetonian.com/article/2026/11/course-changes"); + assert.equal(result.latest_successful_ingestion, null); + assert.equal(result.corpus_range, null); + assert.equal(result.articles[0].excerpt, "Summary"); + assert.doesNotMatch(JSON.stringify(result), /private unused/); + await assert.rejects(api.call("search_prince_articles", { query: "x" })); + await assert.rejects(api.call("get_cs_course_schedule", { term: 1273 })); +}); From 42c6c14769fc7b4a4faa02046e32cd30a202530d Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:27:32 -0500 Subject: [PATCH 2/3] Honor PI-only source boundaries in connector instructions --- app/COURSE_CONNECTOR.md | 10 ++++++++++ app/src/server/course-mcp.ts | 1 + 2 files changed, 11 insertions(+) diff --git a/app/COURSE_CONNECTOR.md b/app/COURSE_CONNECTOR.md index b1b63be..3efacd9 100644 --- a/app/COURSE_CONNECTOR.md +++ b/app/COURSE_CONNECTOR.md @@ -164,3 +164,13 @@ check with valid OIT credentials before university-wide coverage can be claimed. Reproduce the read-only live public-source check from `app` with `npx tsx scripts/smoke-current-course-data.ts 1274`. It uses the real MCP transport with a local test identity, without production sessions or saved-plan writes. + +### PI-only requests + +The MCP instructions tell the host assistant to honor a student's PI-only request, +use the connector's own source tools and report gaps instead of silently switching +to web search or browser control. Official pages fetched server-side by PI remain +PI tool calls. An absent saved plan is not an empty transcript. These are assistant +instructions, not an access-control mechanism for the host's other tools. PI +cannot disable a separately enabled Chrome connector or verify that the host +complied. Strict tool isolation must be enforced in the host client. diff --git a/app/src/server/course-mcp.ts b/app/src/server/course-mcp.ts index 8f196ca..d38ed94 100644 --- a/app/src/server/course-mcp.ts +++ b/app/src/server/course-mcp.ts @@ -36,6 +36,7 @@ const policy = new Map(sources.flatM ])); export const COURSE_INSTRUCTIONS = `Help Princeton students select courses using current TigerApps data. +Respect the student's source and tool restrictions. When they say 'PI only', use only this connector's tools. Those tools may retrieve official Princeton pages and public Prince reporting server-side; this remains a PI connector call and does not require opening Chrome. Do not switch to another connector, web search, or browser/computer control to fill a data gap unless the student explicitly authorizes it. If PI cannot verify something, state the exact missing coverage and continue with the supported parts. A missing saved plan means no saved plan was returned, not that the student has completed no courses. Never claim to have used a PI tool unless you actually called it. Start with get_course_data_status for the requested term. Prefer list_published_terms, search_published_courses and get_published_course for official current offerings, instructors, sections and prerequisite text. These live engine tools may require a backend deployment/configuration before they are available. list_terms describes the imported TigerJunction database only, not everything Princeton has published. Use an explicit term throughout. Tool descriptions may contain stale labels such as 'current' or 'upcoming'; rely on returned catalog data. If the requested term is absent, check it explicitly and report missing coverage when no results are available. Never substitute an older offering or treat missing data as proof that a course will not be offered. Ask for the student's degree (AB or BSE), major, graduation year, completed courses, interests, and time constraints when unknown. Use saved plans only with their permission. A TigerPath plan is not an official transcript or proof of completed prerequisites. If official engine reads are unavailable, get_cs_course_schedule can verify COS course-level times directly from the department. Its coverage excludes full precept/lab combinations and other departments. Do not substitute this fallback for a complete schedule. search_prince_articles adds dated campus reporting from public Prince search, not Clio; reporting is context, not authoritative requirements or section times. Keep article publication dates, fetch times, corpus coverage and unknown ingestion history separate. Read course details, sections, degree requirements, and reviews before recommending a shortlist. Distinguish catalog facts, historical student opinions, and your own assessment. Include course links or identifiers and explain workload, prerequisite uncertainty, and tradeoffs. From 57b0d81ae682c7176e5c6f0897ac2a3581291e3b Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:12 -0500 Subject: [PATCH 3/3] Keep PI course coverage on the maintained Junction catalog --- app/COURSE_CONNECTOR.md | 30 ++++++++++++++++-------------- app/src/server/course-mcp.ts | 11 +++++------ app/src/server/pi.ts | 2 +- app/tests/course-mcp.test.ts | 13 +++++++++---- 4 files changed, 31 insertions(+), 25 deletions(-) diff --git a/app/COURSE_CONNECTOR.md b/app/COURSE_CONNECTOR.md index 3efacd9..6386f60 100644 --- a/app/COURSE_CONNECTOR.md +++ b/app/COURSE_CONNECTOR.md @@ -44,8 +44,7 @@ Overlapping upstream tool catalogs cannot change a tool's designated source. | TigerPath | Degree requirement trees, aggregate planning statistics, own four-year plan | Add or remove a course in a semester | The baseline engine provides 24 allowlisted read tools and 5 optional write tools. -With the published-data engine extension and three local public/coverage tools, -the connector offers up to 30 read tools. Whole-schedule +With three local public/coverage tools, the connector offers up to 27 read tools. Whole-schedule deletion, seat alerts, TigerHub registration, Canvas, calendar access, and PI workspaces are excluded. A saved plan is not a transcript or actual enrollment. @@ -128,8 +127,9 @@ deployment or real plan mutation is part of these local checks. ## Published data and coverage The connector now includes three local read tools independently of engine catalog -availability. `get_course_data_status(term)` checks the imported catalog, the live -published-term source and the CS department fallback. It does not read a student's +availability. `get_course_data_status(term)` checks the maintained catalog term +list, probes that exact term with `search_courses`, and checks the CS department +fallback. It does not read a student's plans. `get_cs_course_schedule(term)` reads the official department page for that exact semester, and rejects a page that silently selects a different term. `search_prince_articles(query, page)` searches the Daily Princetonian public site, @@ -138,14 +138,15 @@ This is not Clio and does not access its database, newsletters, retrieval servic credentials or chats. Publication date, fetch time and unknown ingestion history are separate fields. Public fetches send neither NetID nor session credentials. -A companion engine change exposes `list_published_terms`, -`search_published_courses` and `get_published_course` on the junction MCP scope. -These read Princeton's authenticated OIT course API directly and do not require a -completed database import. Deploy that change and configure the engine's existing -`CONSUMER_KEY`/`CONSUMER_SECRET` (preferred) or `API_ACCESS_TOKEN`. PI does not receive -those credentials. Without that deployment/configuration, only the CS fallback -and public Prince search are independently available. Imported search results and -saved-plan validation may still be stale. Do not claim the database was refreshed. +The existing TigerJunction importer owns catalog ingestion and freshness. PI uses +its existing `list_terms`, `search_courses`, `get_course_details` and +`get_course_sections` tools. There is no second OIT tool family or dependency on a +separate engine PR. The CS fallback and public Prince search remain independently +available during an engine outage. Imported results and saved-plan validation +may still be stale until the importer is repaired and backfilled. A successful +one-course probe establishes only that some data exists for the requested term, +not that every department or section is complete. Do not claim a database refresh +or a full-catalog verification based on that probe. Successful public reads are cached for at most five minutes per process/isolate, with fetch timestamps and bounded cache sizes. Errors are not empty catalogs. @@ -158,8 +159,9 @@ a transcript. No automatic import, production mutation or registration is added. Local live checks on November 26, 2026 retrieved Spring 2027 COS 217 with `MW 10:40 - 11:30` and dated Prince search results. The existing production engine still returned only seven terms through Fall 2026 and no Spring 2027 COS results. -The authenticated engine reads have fixture tests, but require a deployed smoke -check with valid OIT credentials before university-wide coverage can be claimed. +That is a historical observation, not proof of the current production state. +University-wide coverage requires verification of the importer backfill through +the existing engine tools; PI does not acquire or configure OIT credentials. Reproduce the read-only live public-source check from `app` with `npx tsx scripts/smoke-current-course-data.ts 1274`. It uses the real MCP transport diff --git a/app/src/server/course-mcp.ts b/app/src/server/course-mcp.ts index d38ed94..8c2ce85 100644 --- a/app/src/server/course-mcp.ts +++ b/app/src/server/course-mcp.ts @@ -12,7 +12,6 @@ type Source = "junction" | "princetoncourses" | "path"; const READ_TOOLS: Record = { junction: [ "search_courses", "get_course_details", "get_course_sections", "list_departments", - "list_published_terms", "search_published_courses", "get_published_course", "discover_courses", "list_terms", "compare_courses", "get_enrollment_stats", "get_user_schedules", "get_schedule_details", "verify_schedule", ], @@ -37,8 +36,8 @@ const policy = new Map(sources.flatM export const COURSE_INSTRUCTIONS = `Help Princeton students select courses using current TigerApps data. Respect the student's source and tool restrictions. When they say 'PI only', use only this connector's tools. Those tools may retrieve official Princeton pages and public Prince reporting server-side; this remains a PI connector call and does not require opening Chrome. Do not switch to another connector, web search, or browser/computer control to fill a data gap unless the student explicitly authorizes it. If PI cannot verify something, state the exact missing coverage and continue with the supported parts. A missing saved plan means no saved plan was returned, not that the student has completed no courses. Never claim to have used a PI tool unless you actually called it. -Start with get_course_data_status for the requested term. Prefer list_published_terms, search_published_courses and get_published_course for official current offerings, instructors, sections and prerequisite text. These live engine tools may require a backend deployment/configuration before they are available. list_terms describes the imported TigerJunction database only, not everything Princeton has published. Use an explicit term throughout. Tool descriptions may contain stale labels such as 'current' or 'upcoming'; rely on returned catalog data. If the requested term is absent, check it explicitly and report missing coverage when no results are available. Never substitute an older offering or treat missing data as proof that a course will not be offered. Ask for the student's degree (AB or BSE), major, graduation year, completed courses, interests, and time constraints when unknown. Use saved plans only with their permission. A TigerPath plan is not an official transcript or proof of completed prerequisites. -If official engine reads are unavailable, get_cs_course_schedule can verify COS course-level times directly from the department. Its coverage excludes full precept/lab combinations and other departments. Do not substitute this fallback for a complete schedule. search_prince_articles adds dated campus reporting from public Prince search, not Clio; reporting is context, not authoritative requirements or section times. Keep article publication dates, fetch times, corpus coverage and unknown ingestion history separate. +Start with get_course_data_status for the requested term. Use list_terms, search_courses, get_course_details and get_course_sections from the maintained TigerJunction catalog for offerings, instructors, sections and prerequisite text. Catalog freshness depends on the existing importer. Keep that maintained catalog as the primary source; a separate public-page read does not verify its freshness. list_terms describes the imported TigerJunction database only, not everything Princeton has published. Use an explicit term throughout. Tool descriptions may contain stale labels such as 'current' or 'upcoming'; rely on returned catalog data. If the requested term is absent, check it explicitly and report missing coverage when no results are available. Never substitute an older offering or treat missing data as proof that a course will not be offered. Ask for the student's degree (AB or BSE), major, graduation year, completed courses, interests, and time constraints when unknown. Use saved plans only with their permission. A TigerPath plan is not an official transcript or proof of completed prerequisites. +If the engine catalog is unavailable or lacks the requested term, get_cs_course_schedule can verify COS course-level times directly from the department. Its coverage excludes full precept/lab combinations and other departments. Do not substitute this fallback for a complete schedule. search_prince_articles adds dated campus reporting from public Prince search, not Clio; reporting is context, not authoritative requirements or section times. Keep article publication dates, fetch times, corpus coverage and unknown ingestion history separate. Read course details, sections, degree requirements, and reviews before recommending a shortlist. Distinguish catalog facts, historical student opinions, and your own assessment. Include course links or identifiers and explain workload, prerequisite uncertainty, and tradeoffs. verify_schedule is an upstream screening check, not proof of a globally feasible selection of lecture, precept, and lab sections. Inspect the actual section choices and times. Never claim prerequisite eligibility, degree completion, available seats, or registration based solely on a plan or this check. Propose alternatives before changing anything. Only call plan-writing tools after the student explicitly asks you to save or edit the named plan. Saving in TigerJunction or TigerPath does not enroll the student in a course. This connector cannot access TigerHub registration, Canvas, calendars, PI chats, or the assistant's private memory. @@ -101,7 +100,7 @@ export function courseUpstream(env: EngineEnv, netid: string): CourseUpstream { } const livePublicData = publicCourseData(); -const statusTool = { name: "get_course_data_status", description: "Check imported and official live course coverage for a requested term, plus the public CS schedule fallback. Does not read personal plans. Unknown import/ingestion timestamps remain unknown. Call this first when planning a semester.", inputSchema: { type: "object" as const, properties: { term: { type: "integer", minimum: 1000, maximum: 1999 } }, required: ["term"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true } }; +const statusTool = { name: "get_course_data_status", description: "Check the maintained TigerJunction catalog with both its term list and an explicit-term course probe, plus the public CS schedule fallback. Does not read personal plans. Unknown import/ingestion timestamps remain unknown. Call this first when planning a semester.", inputSchema: { type: "object" as const, properties: { term: { type: "integer", minimum: 1000, maximum: 1999 } }, required: ["term"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true } }; const localTools = [...PUBLIC_COURSE_TOOLS, statusTool]; export function createCourseServer(identity: CourseIdentity, upstream: CourseUpstream, publicData = livePublicData): Server { @@ -156,10 +155,10 @@ export function createCourseServer(identity: CourseIdentity, upstream: CourseUps const checkedAt = new Date().toISOString(); const checks = await Promise.allSettled([ upstream.call("junction", "list_terms", {}), - upstream.call("junction", "list_published_terms", {}), + upstream.call("junction", "search_courses", { term, limit: 1 }), publicData.csSchedule(term), ]); - const names = ["tigerjunction_imported_catalog", "princeton_published_terms", "princeton_cs_schedule"]; + const names = ["tigerjunction_imported_catalog", "tigerjunction_requested_term_probe", "princeton_cs_schedule"]; data = { term, checkedAt, latestSuccessfulDatabaseImport: null, sources: checks.map((r, i) => ({ source: names[i], status: r.status === "fulfilled" && !(r.value as { isError?: boolean }).isError ? "available" : "unavailable", ...(r.status === "fulfilled" ? { result: r.value } : {}) })), warning: "Available means the source answered, not that it covers this term or all departments. Compare returned terms and coverage. Historical ratings and saved plans do not verify current offerings. No personal records were queried." }; } else data = await publicData.call(params.name, args); return { content: [{ type: "text" as const, text: JSON.stringify(data) }] }; diff --git a/app/src/server/pi.ts b/app/src/server/pi.ts index 5d86c44..42de646 100644 --- a/app/src/server/pi.ts +++ b/app/src/server/pi.ts @@ -298,7 +298,7 @@ export class Pi extends Think { "- One of these per turn, and never write a menu of options out in prose — that's what offer_choices is for.", "", "Ground rules:", - "- For current or upcoming course selection, prefer list_published_terms, search_published_courses and get_published_course when available. These read Princeton directly. list_terms and search_courses reflect an imported database that may lag. Never silently substitute a historical term or claim missing imported data means a course is not offered.", + "- For current or upcoming course selection, use list_terms and an explicit-term search_courses query, then get_course_details and get_course_sections. These use the maintained TigerJunction catalog, whose importer may lag. Never silently substitute a historical term or claim missing imported data means a course is not offered.", "- Princeton term codes end in 2 for Fall and 4 for Spring (e.g. 1272 = Fall 2026). When unsure which term is current, call list_terms rather than guessing.", "- The interface renders schedule, course, seat-demand, trending and past-term tool results as visual cards automatically. After a tool call, add a short takeaway (conflicts, standouts, whether a seat is realistic, next step) — never re-list every row the card already shows.", "- When a tool errors or comes back empty, say plainly what didn't work and offer the closest thing you can still do. Never paste raw error text, URLs or status codes at the student.", diff --git a/app/tests/course-mcp.test.ts b/app/tests/course-mcp.test.ts index 9be0f9a..719c7a2 100644 --- a/app/tests/course-mcp.test.ts +++ b/app/tests/course-mcp.test.ts @@ -51,7 +51,7 @@ test("guessing a write or unlisted tool cannot bypass read-only authorization", const { upstream, calls } = fakeEngine(); const client = await connected([COURSE_READ], upstream); t.after(() => client.close()); - for (const name of ["create_schedule", "update_user_schedule", "delete_schedule", "subscribe_to_snatch", "delete_everything", "toString"]) { + for (const name of ["create_schedule", "update_user_schedule", "delete_schedule", "subscribe_to_snatch", "delete_everything", "list_published_terms", "search_published_courses", "get_published_course", "toString"]) { assert.equal((await client.callTool({ name, arguments: {} })).isError, true); } assert.equal(calls.length, 0); @@ -128,11 +128,15 @@ test("coverage reports partial sources without reading plans or confusing availa const { WebStandardStreamableHTTPServerTransport } = await import("@modelcontextprotocol/server"); const { publicCourseData } = await import("../src/server/course-public-data.ts"); const calls: string[] = []; + const queries: Record[] = []; const upstream: CourseUpstream = { list: async () => [], - call: async (_source, name) => { + call: async (_source, name, args) => { calls.push(name); - if (name === "list_published_terms") throw new Error("private credential detail"); + if (name === "search_courses") { + queries.push(args); + throw new Error("private credential detail"); + } return { content: [{ type: "text", text: JSON.stringify({ terms: [{ term: 1272 }] }) }] }; }, }; @@ -147,7 +151,8 @@ test("coverage reports partial sources without reading plans or confusing availa const body = JSON.parse((result.content as any)[0].text); assert.deepEqual(body.sources.map((s: any) => s.status), ["available", "unavailable", "unavailable"]); assert.equal(body.latestSuccessfulDatabaseImport, null); - assert.deepEqual(calls.sort(), ["list_published_terms", "list_terms"]); + assert.deepEqual(calls.sort(), ["list_terms", "search_courses"]); + assert.deepEqual(queries, [{ term: 1274, limit: 1 }]); assert.doesNotMatch(JSON.stringify(result), /private credential detail/); assert.match(body.warning, /not that it covers this term/); assert.equal((await client.callTool({ name: "get_course_data_status", arguments: { term: 1274, netid: "student2" } })).isError, true);